path
stringlengths 5
300
| repo_name
stringlengths 6
76
| content
stringlengths 26
1.05M
|
---|---|---|
src/px-key-value-pair/index.js | jonniespratley/px-components-react | import React from 'react';
import classnames from 'classnames';
import style from './style.scss';
/**
* px-key-value-pair component
*/
export default ({
label = 'px-key-value-pair',
value,
size,
uom,
children
}) => {
const _getAdjustedSize = (s) => {
return (
s === 'alpha' ? 'delta' :
s === 'beta' ? 'epsilon' :
s === 'gamma' ? 'value' :
s === 'delta' ? 'value' : 'zeta'
);
};
const baseClassnames = classnames(
'px-key-value-pair'
);
const valueClassnames = classnames(
size,
`kvp-value--${size}`
);
return (
<div className={baseClassnames}>
<div className='label'>{label}</div>
<div className={valueClassnames}>
{value}
{uom && <span className={_getAdjustedSize(size)}>{uom}</span>}
</div>
<style jsx>{style}</style>
</div>
);
}
|
app.js | nick/react-skeleton | import React from 'react';
import ReactDOM from 'react-dom';
class App extends React.Component {
render() {
return <div>React Loaded OK!</div>;
}
}
ReactDOM.render(<App />, document.getElementById('react'));
|
app/Resources/js/containers/home.js | ryota-murakami/tweet-pick | import React from 'react'
import { connect } from 'react-redux'
import ImportModal from '../components/import/importModal'
import Timeline from '../components/timeline'
import Header from '../components/header'
import '../../sass/common/common.scss'
import '../../sass/page/home.scss'
class App extends React.Component {
render() {
return (
<div>
<ImportModal/>
<Header/>
<Timeline/>
</div>
)
}
}
export default connect()(App)
|
src/components/about-ipfs/AboutIpfs.js | ipfs/webui | import React from 'react'
import { withTranslation, Trans } from 'react-i18next'
import Box from '../box/Box'
export const AboutIpfs = ({ t }) => {
return (
<Box>
<h2 className='mt0 mb3 montserrat fw2 f3 charcoal'>{t('aboutIpfs.header')}</h2>
<ul className='pl3'>
<Trans i18nKey='aboutIpfs.paragraph1' t={t}>
<li className='mb2'><strong>A hypermedia distribution protocol</strong> that incorporates ideas from Kademlia, BitTorrent, Git, and more</li>
</Trans>
<Trans i18nKey='aboutIpfs.paragraph2' t={t}>
<li className='mb2'><strong>A peer-to-peer file transfer network</strong> with a completely decentralized architecture and no central point of failure, censorship, or control</li>
</Trans>
<Trans i18nKey='aboutIpfs.paragraph3' t={t}>
<li className='mb2'><strong>An on-ramp to tomorrow's web</strong> — traditional browsers can access IPFS files through gateways like <code className='f5 bg-light-gray br2 pa1'>https://ipfs.io</code> or directly using the <a className='link blue' target='_blank' rel='noopener noreferrer' href='https://github.com/ipfs-shipyard/ipfs-companion#ipfs-companion'>IFPS Companion</a> extension</li>
</Trans>
<Trans i18nKey='aboutIpfs.paragraph4' t={t}>
<li className='mb2'><strong>A next-gen CDN</strong> — just add a file to your node to make it available to the world with cache-friendly content-hash addressing and BitTorrent-style bandwidth distribution</li>
</Trans>
<Trans i18nKey='aboutIpfs.paragraph5' t={t}>
<li className='mb2'><strong>A developer toolset</strong> for building completely <a className='link blue' target='_blank' rel='noopener noreferrer' href='https://awesome.ipfs.io/'>distributed apps and services</a>, backed by a robust open-source community</li>
</Trans>
</ul>
</Box>
)
}
export default withTranslation('welcome')(AboutIpfs)
|
src/components/SearchInput/index.js | yiweimatou/admin-antd | import React from 'react'
import { Input, Button } from 'antd';
import classNames from 'classnames';
const InputGroup = Input.Group;
class SearchInput extends React.Component {
constructor(props) {
super(props)
this.state = {
value: '',
focus: false,
}
}
handleInputChange = (e) => {
this.setState({
value: e.target.value,
});
}
handleFocusBlur = (e) => {
this.setState({
focus: e.target === document.activeElement,
});
}
handleSearch = () => {
if (this.props.onSearch) {
this.props.onSearch(this.state.value);
}
}
render() {
const { style, size, placeholder } = this.props;
const btnCls = classNames({
'ant-search-btn': true,
'ant-search-btn-noempty': !!this.state.value.trim(),
});
const searchCls = classNames({
'ant-search-input': true,
'ant-search-input-focus': this.state.focus,
});
return (
<div className="ant-search-input-wrapper" style={style}>
<InputGroup className={searchCls}>
<Input
placeholder={placeholder}
value={this.state.value}
onChange={this.handleInputChange}
onFocus={this.handleFocusBlur} onBlur={this.handleFocusBlur} onPressEnter={this.handleSearch}
/>
<div className="ant-input-group-wrap">
<Button icon="search" className={btnCls} size={size} onClick={this.handleSearch} />
</div>
</InputGroup>
</div>
)
}
}
export default SearchInput
|
node_modules/react-icons/md/pie-chart-outlined.js | bengimbel/Solstice-React-Contacts-Project |
import React from 'react'
import Icon from 'react-icon-base'
const MdPieChartOutlined = props => (
<Icon viewBox="0 0 40 40" {...props}>
<g><path d="m21.6 33.2c6.1-0.8 10.8-5.5 11.6-11.6h-11.6v11.6z m-15-13.2c0 6.8 5.2 12.3 11.8 13.2v-26.4c-6.6 0.8-11.8 6.4-11.8 13.2z m15-13.2v11.6h11.6c-0.8-6.1-5.5-10.8-11.6-11.6z m-1.6-3.4c9.1 0 16.6 7.5 16.6 16.6s-7.5 16.6-16.6 16.6-16.6-7.5-16.6-16.6 7.5-16.6 16.6-16.6z"/></g>
</Icon>
)
export default MdPieChartOutlined
|
app/components/PropertyMap/GoogleApiComponent.js | koofka/singleproperty_redux | import React from 'react';
import cache from 'utils/ScriptCache';
import GoogleApi from 'utils/GoogleApi';
const GoogleApiComponent = (options) => (WrappedComponent) => {
const apiKey = options.apiKey;
const libraries = options.libraries || ['places'];
class Wrapper extends React.Component {
constructor(props, context) {
super(props, context);
this.state = {
loaded: false,
google: null,
};
}
componentWillMount() {
this.scriptCache = cache({
google: GoogleApi({
apiKey,
libraries,
}),
});
}
componentDidMount() {
this.scriptCache.google.onLoad(() => {
this.setState({
loaded: true,
google: window.google,
});
});
}
render() {
const props = Object.assign({}, this.props, {
loaded: this.state.loaded,
google: this.state.google,
});
return (
<div>
<WrappedComponent {...props} />
<div
ref={(c) => this.mapDiv = c} // eslint-disable-line
/>
</div>
);
}
}
return Wrapper;
};
export default GoogleApiComponent;
|
client/src/bundles/ConfirmFolder.js | silverstripe/silverstripe-userforms | /* global window */
import i18n from 'i18n';
import jQuery from 'jquery';
import React from 'react';
import ReactDOM from 'react-dom';
import { loadComponent } from 'lib/Injector';
import url from 'url';
import qs from 'qs';
const FormBuilderModal = loadComponent('FormBuilderModal');
jQuery.entwine('ss', ($) => {
/** Mark newly added fields as new */
$('#Form_EditForm_Fields').entwine({
onmatch() {
this._super();
this.on('addnewinline', () => {
this.one('reload', () => {
const newField = this.find('.ss-gridfield-item').last();
newField.find('.col-ClassName select').attr('data-folderconfirmed', 0);
});
});
}
});
function toggleVisibility(check, show, hide) {
if (check) {
$(show).show();
$(hide).hide();
} else {
$(hide).show();
$(show).hide();
}
}
/** Move our options under the radio button areas */
$('#Form_ConfirmFolderForm_FolderOptions-new').entwine({
onmatch() {
$('#Form_ConfirmFolderForm_CreateFolder_Holder').detach().appendTo($('#Form_ConfirmFolderForm_FolderOptions-new').parent().parent());
toggleVisibility($(this).prop('checked'), '#Form_ConfirmFolderForm_CreateFolder_Holder', '#Form_ConfirmFolderForm_FolderID_Holder');
},
onchange() {
toggleVisibility($(this).prop('checked'), '#Form_ConfirmFolderForm_CreateFolder_Holder', '#Form_ConfirmFolderForm_FolderID_Holder');
}
});
/** Move our options under the radio button areas */
$('#Form_ConfirmFolderForm_FolderOptions-existing').entwine({
onmatch() {
$('#Form_ConfirmFolderForm_FolderID_Holder').detach().appendTo($('#Form_ConfirmFolderForm_FolderOptions-existing').parent().parent());
toggleVisibility($(this).prop('checked'), '#Form_ConfirmFolderForm_FolderID_Holder', '#Form_ConfirmFolderForm_CreateFolder_Holder');
},
onchange() {
toggleVisibility($(this).prop('checked'), '#Form_ConfirmFolderForm_FolderID_Holder', '#Form_ConfirmFolderForm_CreateFolder_Holder');
}
});
/** Display permissions for folder selected */
$('#Form_ConfirmFolderForm_FolderID_Holder .treedropdownfield.is-open,#Form_ItemEditForm_FolderID .treedropdownfield.is-open').entwine({
onunmatch() {
// Build url
const adminUrl = $(this).closest('#Form_ConfirmFolderForm').data('adminUrl');
const parsedURL = url.parse(`${adminUrl}user-forms/getfoldergrouppermissions`);
const parsedQs = qs.parse(parsedURL.query);
parsedQs.FolderID = $(this).find('input[name=FolderID]').val();
const fetchURL = url.format({ ...parsedURL, search: qs.stringify(parsedQs) });
return fetch(fetchURL, {
credentials: 'same-origin',
})
.then(response => response.json())
.then(response => {
$(this).siblings('.form__field-description').html(response);
$(this).parent().siblings('.form__field-description').html(response);
return response;
})
.catch((error) => {
jQuery.noticeAdd({ text: error.message, stay: false, type: 'error' });
});
}
});
/**
* Monitor new fields to intercept when EditableFileField is selected
*/
$(".uf-field-editor .ss-gridfield-items .dropdown.editable-column-field.form-group--no-label:not([data-folderconfirmed='1'])").entwine({
onchange() {
// ensure EditableFileField is selected
if (this.get(0).value !== 'SilverStripe\\UserForms\\Model\\EditableFormField\\EditableFileField') {
return;
}
// ensure there are no other EditableFileField confirmed
if ($(".uf-field-editor .ss-gridfield-items .dropdown.editable-column-field.form-group--no-label[data-folderconfirmed='1']").length) {
return;
}
// open folder confirmation dialog
let dialog = $('#confirm-folder__dialog-wrapper');
if (dialog.length) {
dialog.remove();
}
dialog = $('<div id="confirm-folder__dialog-wrapper" />');
const id = $(this).closest('tr').data('id');
const adminUrl = $(this).closest('.uf-field-editor').data('adminUrl');
dialog.data('id', id);
dialog.data('adminUrl', adminUrl);
$('body').append(dialog);
dialog.open();
},
});
/** handle modal rendering */
$('#confirm-folder__dialog-wrapper').entwine({
onunmatch() {
// solves errors given by ReactDOM "no matched root found" error.
this._clearModal();
},
open() {
this._renderModal(true);
},
close(noRevert) {
if (!noRevert) {
// revert field to TextField
const id = $('#confirm-folder__dialog-wrapper').data('id');
const select = $(`.ss-gridfield-item[data-id='${id}'] .dropdown.editable-column-field.form-group--no-label[data-folderconfirmed='0']`);
select.val('SilverStripe\\UserForms\\Model\\EditableFormField\\EditableTextField');
}
this._renderModal(false);
},
_renderModal(isOpen) {
const handleHide = (...args) => this._handleHideModal(...args);
const handleSubmit = (...args) => this._handleSubmitModal(...args);
const title = i18n._t('UserForms.FILE_CONFIRMATION_TITLE', 'Select file upload folder');
const editableFileFieldID = $(this).data('id');
// Build schema url
const adminUrl = $(this).data('adminUrl');
const parsedURL = url.parse(`${adminUrl}user-forms/confirmfolderformschema`);
const parsedQs = qs.parse(parsedURL.query);
parsedQs.ID = editableFileFieldID;
const schemaUrl = url.format({ ...parsedURL, search: qs.stringify(parsedQs) });
ReactDOM.render(
<FormBuilderModal
title={title}
isOpen={isOpen}
onSubmit={handleSubmit}
onClosed={handleHide}
schemaUrl={schemaUrl}
bodyClassName="modal__dialog"
className="confirm-folder-modal"
responseClassBad="modal__response modal__response--error"
responseClassGood="modal__response modal__response--good"
identifier="UserForms.ConfirmFolder"
/>,
this[0]
);
},
_clearModal() {
ReactDOM.unmountComponentAtNode(this[0]);
// this.empty();
},
_handleHideModal() {
// close the modal
return this.close();
},
_handleSubmitModal(data, action, submitFn) {
return submitFn()
.then(() => {
jQuery.noticeAdd({ text: i18n._t('UserForms.FILE_CONFIRMATION_CONFIRMATION', 'Folder confirmed successfully.'), stay: false, type: 'success' });
this.close(true);
$('[name=action_doSave], [name=action_save]').click();
})
.catch((error) => {
jQuery.noticeAdd({ text: error.message, stay: false, type: 'error' });
});
},
});
$('#Form_ConfirmFolderForm_action_cancel').entwine({
onclick() {
$('#confirm-folder__dialog-wrapper').close();
}
});
});
|
docs/src/app/components/pages/components/TextField/ExampleCustomize.js | lawrence-yu/material-ui | import React from 'react';
import TextField from 'material-ui/TextField';
import {orange500, blue500} from 'material-ui/styles/colors';
const styles = {
errorStyle: {
color: orange500,
},
underlineStyle: {
borderColor: orange500,
},
floatingLabelStyle: {
color: orange500,
},
floatingLabelFocusStyle: {
color: blue500,
},
};
const TextFieldExampleCustomize = () => (
<div>
<TextField
hintText="Styled Hint Text"
hintStyle={styles.errorStyle}
/><br />
<TextField
hintText="Custom error color"
errorText="This field is required."
errorStyle={styles.errorStyle}
/><br />
<TextField
hintText="Custom Underline Color"
underlineStyle={styles.underlineStyle}
/><br />
<TextField
hintText="Custom Underline Focus Color"
underlineFocusStyle={styles.underlineStyle}
/><br />
<TextField
floatingLabelText="Styled Floating Label Text"
floatingLabelStyle={styles.floatingLabelStyle}
floatingLabelFocusStyle={styles.floatingLabelFocusStyle}
/>
</div>
);
export default TextFieldExampleCustomize;
|
fields/types/location/LocationFilter.js | davibe/keystone | import _ from 'underscore';
import classNames from 'classnames';
import React from 'react';
import { FormField, FormInput, FormRow, SegmentedControl } from 'elemental';
const MODE_OPTIONS = [
{ label: 'Exactly', value: 'exactly' },
{ label: 'Contains', value: 'contains' }
];
const TOGGLE_OPTIONS = [
{ label: 'Matches', value: false },
{ label: 'Does NOT Match', value: true }
];
var TextFilter = React.createClass({
getInitialState () {
return {
inverted: TOGGLE_OPTIONS[0].value,
city: '',
state: '',
code: '',
country: ''
};
},
componentDidMount () {
// focus the text focusTarget
React.findDOMNode(this.refs.focusTarget).focus();
},
toggleInverted (value) {
this.setState({
inverted: value
});
},
render () {
let { modeLabel, modeValue } = this.state;
return (
<div>
<FormField>
<SegmentedControl equalWidthSegments options={TOGGLE_OPTIONS} value={this.state.inverted} onChange={this.toggleInverted} />
</FormField>
<FormField>
<FormInput ref="focusTarget" placeholder="Address" />
</FormField>
<FormRow>
<FormField width="two-thirds">
<FormInput placeholder="City" value={this.state.city} />
</FormField>
<FormField width="one-third">
<FormInput placeholder="State" value={this.state.state} />
</FormField>
<FormField width="one-third" style={{ marginBottom: 0 }}>
<FormInput placeholder="Postcode" value={this.state.code} />
</FormField>
<FormField width="two-thirds" style={{ marginBottom: 0 }}>
<FormInput placeholder="Country" value={this.state.country} />
</FormField>
</FormRow>
</div>
);
}
});
module.exports = TextFilter;
|
ajax/libs/forerunnerdb/1.3.709/fdb-core.min.js | redmunds/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/Shim.IE8");"undefined"!=typeof window&&(window.ForerunnerDB=d),b.exports=d},{"../lib/Core":5,"../lib/Shim.IE8":29}],2:[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":25,"./Shared":28}],3:[function(a,b,c){"use strict";var d,e;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}(),e=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},b.exports=e},{}],4:[function(a,b,c){"use strict";var d,e,f,g,h,i,j,k,l,m,n;d=a("./Shared");var o=function(a,b){this.init.apply(this,arguments)};o.prototype.init=function(a,b){this.sharedPathSolver=n,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",o),d.mixin(o.prototype,"Mixin.Common"),d.mixin(o.prototype,"Mixin.Events"),d.mixin(o.prototype,"Mixin.ChainReactor"),d.mixin(o.prototype,"Mixin.CRUD"),d.mixin(o.prototype,"Mixin.Constants"),d.mixin(o.prototype,"Mixin.Triggers"),d.mixin(o.prototype,"Mixin.Sorting"),d.mixin(o.prototype,"Mixin.Matching"),d.mixin(o.prototype,"Mixin.Updating"),d.mixin(o.prototype,"Mixin.Tags"),f=a("./Metrics"),g=a("./KeyValueStore"),h=a("./Path"),i=a("./IndexHashMap"),j=a("./IndexBinaryTree"),k=a("./Index2d"),e=d.modules.Db,l=a("./Overload"),m=a("./ReactorIO"),n=new h,d.synthesize(o.prototype,"deferredCalls"),d.synthesize(o.prototype,"state"),d.synthesize(o.prototype,"name"),d.synthesize(o.prototype,"metaData"),d.synthesize(o.prototype,"capped"),d.synthesize(o.prototype,"cappedSize"),o.prototype._asyncPending=function(a){this._deferQueue.async.push(a)},o.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")},o.prototype.data=function(){return this._data},o.prototype.drop=function(a){var b;if(this.isDropped())return a&&a.call(this,!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._data,delete this._metrics,delete this._listeners,a&&a.call(this,!1,!0),!0}return a&&a.call(this,!1,!0),!1},o.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",{keyName:a,oldData:b})}return this}return this._primaryKey},o.prototype._onInsert=function(a,b){this.emit("insert",a,b)},o.prototype._onUpdate=function(a){this.emit("update",a)},o.prototype._onRemove=function(a){this.emit("remove",a)},o.prototype._onChange=function(){this._options.changeTimestamp&&(this._metaData.lastChange=this.serialiser.convert(new Date))},d.synthesize(o.prototype,"db",function(a){return a&&"_id"===this.primaryKey()&&(this.primaryKey(a.primaryKey()),this.debug(a.debug())),this.$super.apply(this,arguments)}),d.synthesize(o.prototype,"mongoEmulation"),o.prototype.setData=new l("Collection.prototype.setData",{"*":function(a){return this.$main.call(this,a,{})},"*, object":function(a,b){return this.$main.call(this,a,b)},"*, function":function(a,b){return this.$main.call(this,a,{},b)},"*, *, function":function(a,b,c){return this.$main.call(this,a,b,c)},"*, *, *":function(a,b,c){return this.$main.call(this,a,b,c)},$main:function(a,b,c){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";if(a){var d=this.deferredCalls(),e=[].concat(this._data);this.deferredCalls(!1),b=this.options(b),b.$decouple&&(a=this.decouple(a)),a instanceof Array||(a=[a]),this.remove({}),this.insert(a),this.deferredCalls(d),this._onChange(),this.emit("setData",this._data,e)}return c&&c.call(this),this}}),o.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.hash(d),i.set(d[k],e),j.set(e,d)}},o.prototype.ensurePrimaryKey=function(a){void 0===a[this._primaryKey]&&(a[this._primaryKey]=this.objectId())},o.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},o.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.call(this),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.call(this),{}},o.prototype.filter=function(a,b,c){return this.find(a,c).filter(b)},o.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},o.prototype.update=function(a,b,c,d){if(this.isDropped())throw this.logIdentifier()+" Cannot operate in a dropped state!";return this.mongoEmulation()?(this.convertToFdb(a),this.convertToFdb(b)):b=this.decouple(b),b=this.transformIn(b),this._handleUpdate(a,b,c,d)},o.prototype._handleUpdate=function(a,b,c,d){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.chainWillSend()&&this.chainSend("update",{query:a,update:b,dataSet:this.decouple(f)},c),h.time("Resolve chains"),this._onUpdate(f),this._onChange(),d&&d.call(this),this.emit("immediateChange",{type:"update",data:f}),this.deferEmit("change",{type:"update",data:f}))),h.stop(),f||[]},o.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},o.prototype.updateById=function(a,b){var c={};return c[this._primaryKey]=a,this.update(c,b)[0]},o.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},o.prototype._isPositionalKey=function(a){return".$"===a.substr(a.length-2,2)},o.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.call(this,!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.call(this,!1,g),g},o.prototype.removeById=function(a){var b={};return b[this._primaryKey]=a,this.remove(b)[0]},o.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.call(this,c),this._asyncComplete(a);this.isProcessingQueue()||this.deferEmit("queuesComplete")},o.prototype.isProcessingQueue=function(){var a;for(a in this._deferQueue)if(this._deferQueue.hasOwnProperty(a)&&this._deferQueue[a].length)return!0;return!1},o.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)},o.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.call(this,e),this._onChange(),this.emit("immediateChange",{type:"insert",data:i}),this.deferEmit("change",{type:"insert",data:i}),e},o.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.chainWillSend()&&g.chainSend("insert",{dataSet:g.decouple([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"},o.prototype._dataInsertAtIndex=function(a,b){this._data.splice(a,0,b)},o.prototype._dataRemoveAtIndex=function(a){this._data.splice(a,1)},o.prototype._dataReplace=function(a){for(;this._data.length;)this._data.pop();this._data=this._data.concat(a)},o.prototype._insertIntoIndexes=function(a){var b,c,d=this._indexByName,e=this.hash(a),f=this._primaryKey;c=this._primaryIndex.uniqueSet(a[f],a),this._primaryCrc.uniqueSet(a[f],e),this._crcLookup.uniqueSet(e,a);for(b in d)d.hasOwnProperty(b)&&d[b].insert(a);return c},o.prototype._removeFromIndexes=function(a){var b,c=this._indexByName,d=this.hash(a),e=this._primaryKey;this._primaryIndex.unSet(a[e]),this._primaryCrc.unSet(a[e]),this._crcLookup.unSet(d);for(b in c)c.hasOwnProperty(b)&&c[b].remove(a)},o.prototype._updateIndexes=function(a,b){this._removeFromIndexes(a),this._insertIntoIndexes(b)},o.prototype._rebuildIndexes=function(){var a,b=this._indexByName;for(a in b)b.hasOwnProperty(a)&&b[a].rebuild()},o.prototype.subset=function(a,b){var c,d=this.find(a,b);return c=new o,c.db(this._db),c.subsetOf(this).primaryKey(this._primaryKey).setData(d),c},d.synthesize(o.prototype,"subsetOf"),o.prototype.isSubsetOf=function(a){return this._subsetOf===a},o.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},o.prototype.findById=function(a,b){var c={};return c[this._primaryKey]=a,this.find(c,b)[0]},o.prototype.peek=function(a,b){var c,d,e=this._data,f=e.length,g=new o,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)},o.prototype.explain=function(a,b){var c=this.find(a,b);return c.__fdbOp._data},o.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},o.prototype.find=function(a,b,c){return this.mongoEmulation()&&this.convertToFdb(a),c?(c.call(this,"Callbacks for the find() operation are not yet implemented!",[]),[]):this._find.call(this,a,b,c)},o.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=this._metrics.create("find"),y=this.primaryKey(),z=this,A=!0,B={},C=[],D=[],E=[],F={},G={};if(b instanceof Array||(b=this.options(b)),w=function(c){return z._match(c,a,b,"and",F)},x.start(),a){if(a instanceof Array){for(v=this,n=0;n<a.length;n++)v=v.subset(a[n],b&&b[n]?b[n]:{});return v.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(x.time("analyseQuery"),c=this._analyseQuery(z.decouple(a),b,x),x.time("analyseQuery"),x.data("analysis",c),c.hasJoin&&c.queriesJoin){for(x.time("joinReferences"),f=0;f<c.joinsOn.length;f++)m=c.joinsOn[f],j=m.key,k=m.type,l=m.id,i=new h(c.joinQueries[j]),g=i.value(a)[0],B[l]=this._db[k](j).subset(g),delete a[c.joinQueries[j]];x.time("joinReferences")}if(c.indexMatch.length&&(!b||b&&!b.$skipIndex)?(x.data("index.potential",c.indexMatch),x.data("index.used",c.indexMatch[0].index),x.time("indexLookup"),e=c.indexMatch[0].lookup||[],x.time("indexLookup"),c.indexMatch[0].keyData.totalKeyCount===c.indexMatch[0].keyData.score&&(A=!1)):x.flag("usedIndex",!1),A&&(e&&e.length?(d=e.length,x.time("tableScan: "+d),e=e.filter(w)):(d=this._data.length,x.time("tableScan: "+d),e=this._data.filter(w)),x.time("tableScan: "+d)),b.$orderBy&&(x.time("sort"),e=this.sort(b.$orderBy,e),x.time("sort")),void 0!==b.$page&&void 0!==b.$limit&&(G.page=b.$page,G.pages=Math.ceil(e.length/b.$limit),G.records=e.length,b.$page&&b.$limit>0&&(x.data("cursor",G),e.splice(0,b.$page*b.$limit))),b.$skip&&(G.skip=b.$skip,e.splice(0,b.$skip),x.data("skip",b.$skip)),b.$limit&&e&&e.length>b.$limit&&(G.limit=b.$limit,e.length=b.$limit,x.data("limit",b.$limit)),b.$decouple&&(x.time("decouple"),e=this.decouple(e),x.time("decouple"),x.data("flag.decouple",!0)),b.$join&&(C=C.concat(this.applyJoin(e,b.$join,B)),x.data("flag.join",!0)),C.length&&(x.time("removalQueue"),this.spliceArrayByIndexList(e,C),x.time("removalQueue")),b.$transform){for(x.time("transform"),n=0;n<e.length;n++)e.splice(n,1,b.$transform(e[n]));x.time("transform"),x.data("flag.transform",!0)}this._transformEnabled&&this._transformOut&&(x.time("transformOut"),e=this.transformOut(e),x.time("transformOut")),x.data("results",e.length)}else e=[];if(!b.$aggregate){x.time("scanFields");for(n in b)b.hasOwnProperty(n)&&0!==n.indexOf("$")&&(1===b[n]?D.push(n):0===b[n]&&E.push(n));if(x.time("scanFields"),D.length||E.length){for(x.data("flag.limitFields",!0),x.data("limitFields.on",D),x.data("limitFields.off",E),x.time("limitFields"),n=0;n<e.length;n++){t=e[n];for(o in t)t.hasOwnProperty(o)&&(D.length&&o!==y&&-1===D.indexOf(o)&&delete t[o],E.length&&E.indexOf(o)>-1&&delete t[o])}x.time("limitFields")}if(b.$elemMatch){x.data("flag.elemMatch",!0),x.time("projection-elemMatch");for(n in b.$elemMatch)if(b.$elemMatch.hasOwnProperty(n))for(q=new h(n),o=0;o<e.length;o++)if(r=q.value(e[o])[0],r&&r.length)for(p=0;p<r.length;p++)if(z._match(r[p],b.$elemMatch[n],b,"",{})){q.set(e[o],n,[r[p]]);break}x.time("projection-elemMatch")}if(b.$elemsMatch){x.data("flag.elemsMatch",!0),x.time("projection-elemsMatch");for(n in b.$elemsMatch)if(b.$elemsMatch.hasOwnProperty(n))for(q=new h(n),o=0;o<e.length;o++)if(r=q.value(e[o])[0],r&&r.length){for(s=[],p=0;p<r.length;p++)z._match(r[p],b.$elemsMatch[n],b,"",{})&&s.push(r[p]);q.set(e[o],n,s)}x.time("projection-elemsMatch")}}return b.$aggregate&&(x.data("flag.aggregate",!0),x.time("aggregate"),u=new h(b.$aggregate),e=u.value(e),x.time("aggregate")),x.stop(),e.__fdbOp=x,e.$cursor=G,e},o.prototype.findOne=function(){return this.find.apply(this,arguments)[0]},o.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},o.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},o.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},o.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}},o.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},o.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},o.prototype.sort=function(a,b){var c=this,d=n.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(n.get(a,f.path),n.get(b,f.path)):-1===f.value&&(g=c.sortDesc(n.get(a,f.path),n.get(b,f.path))),0!==g)return g;return g}),b},o.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)},o.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},o.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},o.prototype.count=function(a,b){return a?this.find(a,b).length:this._data.length},o.prototype.findSub=function(a,b,c,d){return this._findSub(this.find(a),b,c,d)},o.prototype._findSub=function(a,b,c,d){var e,f,g,i=new h(b),j=a.length,k=new o("__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},o.prototype.findSubOne=function(a,b,c,d){return this.findSub(a,b,c,d)[0]},o.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},o.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,e={start:(new Date).getTime()};if(b)if(b.type){if(!d.index[b.type])throw this.logIdentifier()+' Cannot create index of type "'+b.type+'", type not found in the index type register (Shared.index)';c=new d.index[b.type](a,b,this)}else 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,e.end=(new Date).getTime(),e.total=e.end-e.start,this._lastOp={type:"ensureIndex",stats:{time:e}},{index:c,id:c.id(),name:c.name(),state:c.state()})},o.prototype.index=function(a){return this._indexByName?this._indexByName[a]:void 0},o.prototype.lastOp=function(){return this._metrics.list()},o.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},o.prototype.collateAdd=new l("Collection.prototype.collateAdd",{"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.dataSet),c.update({},e)):c.insert(d.data.dataSet);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.dataSet)}})},"object, function":function(a,b){if("string"==typeof a&&(a=this._db.collection(a,{autoCreate:!1,throwError:!1})),a)return this._collate=this._collate||{},this._collate[a.name()]=new m(a,this,b),this;throw"Cannot collate from a non-existent collection!"}}),o.prototype.collateRemove=function(a){if("object"==typeof a&&(a=a.name()),a)return this._collate[a].drop(),delete this._collate[a],this;throw"No collection name passed to collateRemove() or collection not found!"},e.prototype.collection=new l("Db.prototype.collection",{"":function(){return this.$main.call(this,{name:this.objectId()})},object:function(a){return a instanceof o?"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 o(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=o},{"./Index2d":8,"./IndexBinaryTree":9,"./IndexHashMap":10,"./KeyValueStore":11,"./Metrics":12,"./Overload":24,"./Path":25,"./ReactorIO":26,"./Shared":28}],5:[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":6,"./Metrics.js":12,"./Overload":24,"./Shared":28}],6:[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("./Checksum.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.Checksum=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},{"./Checksum.js":3,"./Collection.js":4,"./Metrics.js":12,"./Overload":24,"./Shared":28}],7:[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},{}],8:[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.index["2d"]=k,d.finishModule("Index2d"),b.exports=k},{"./BinaryTree":2,"./GeoHash":7,"./Path":25,"./Shared":28}],9:[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.index.btree=g,d.finishModule("IndexBinaryTree"),b.exports=g},{"./BinaryTree":2,"./Path":25,"./Shared":28}],10:[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.index.hashed=f,d.finishModule("IndexHashMap"),b.exports=f},{"./Path":25,"./Shared":28}],11:[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":28}],12:[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":23,"./Shared":28}],13:[function(a,b,c){"use strict";var d={preSetData:function(){},postSetData:function(){}};b.exports=d},{}],14:[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)}},chainWillSend:function(){return Boolean(this._chain)},chainSend:function(a,b,c){if(this._chain){var d,e,f=this._chain,g=f.length,h=this.decouple(b,g);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,h[e],c)}}},chainReceive:function(a,b,c,d){var e={sender:a,type:b,data:c,options:d},f=!1;this.debug&&this.debug()&&console.log(this.logIdentifier()+" Received data from parent reactor node"),this._chainHandler&&(f=this._chainHandler(e)),f||this.chainSend(e.type,e.data,e.options)}};b.exports=d},{}],15:[function(a,b,c){"use strict";var d,e=0,f=a("./Overload"),g=a("./Serialiser"),h=new g;d={serialiser:h,make:function(a){return h.convert(a)},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 JSON.parse(a,h.reviver())},jStringify:function(a){return JSON.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},hash:function(a){return JSON.stringify(a)},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"ForerunnerDB "+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":24,"./Serialiser":27}],16:[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},{}],17:[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":24}],18:[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},applyJoin:function(a,b,c,d){var e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x=this,y=[];for(a instanceof Array||(a=[a]),e=0;e<b.length;e++)for(f in b[e])if(b[e].hasOwnProperty(f))for(g=b[e][f],h=g.$sourceType||"collection",i="$"+h+"."+f,j=f,c[i]?k=c[i]:this._db[h]&&"function"==typeof this._db[h]&&(k=this._db[h](f)),l=0;l<a.length;l++){m={},n=!1,o=!1,p="";for(q in g)if(g.hasOwnProperty(q))if(r=g[q],"$"===q.substr(0,1))switch(q){case"$where":if(!r.$query&&!r.$options)throw'$join $where clause requires "$query" and / or "$options" keys to work!';r.$query&&(m=x.resolveDynamicQuery(r.$query,a[l])),r.$options&&(s=r.$options);break;case"$as":j=r;break;case"$multi":n=r;break;case"$require":o=r;break;case"$prefix":p=r}else m[q]=x.resolveDynamicQuery(r,a[l]);if(t=k.find(m,s),!o||o&&t[0])if("$root"===j){if(n!==!1)throw this.logIdentifier()+' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!';u=t[0],v=a[l];for(w in u)u.hasOwnProperty(w)&&void 0===v[p+w]&&(v[p+w]=u[w])}else a[l][j]=n===!1?t[0]:t;else y.push(l)}return y},resolveDynamicQuery:function(a,b){var c,d,e,f,g,h=this;if("string"==typeof a)return f="$$."===a.substr(0,3)?this.sharedPathSolver.value(b,a.substr(3,a.length-3)):this.sharedPathSolver.value(b,a),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]=this.sharedPathSolver.value(b,e.substr(3,e.length-3))[0]:c[g]=e;break;case"object":c[g]=h.resolveDynamicQuery(e,b);break;default:c[g]=e}return c},spliceArrayByIndexList:function(a,b){var c;for(c=b.length-1;c>=0;c--)a.splice(b[c],1)}};b.exports=d},{}],19:[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},{}],20:[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},{}],21:[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":24}],22:[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+'" to val "'+c+'"')},_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},{}],23:[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":25,"./Shared":28}],24:[function(a,b,c){"use strict";var d=function(a,b){if(b||(b=a,a=void 0),b){var c,d,e,f,g,h,i=this;if(!(b instanceof Array)){e={};for(c in b)if(b.hasOwnProperty(c))if(f=c.replace(/ /g,""),-1===f.indexOf("*"))e[f]=b[c];else for(h=this.generateSignaturePermutations(f),g=0;g<h.length;g++)e[h[g]]||(e[h[g]]=b[c]);b=e}return function(){var e,f,g,h=[];if(b instanceof Array){for(d=b.length,c=0;d>c;c++)if(b[c].length===arguments.length)return i.callExtend(this,"$main",b,b[c],arguments)}else{for(c=0;c<arguments.length&&(f=typeof arguments[c],"object"===f&&arguments[c]instanceof Array&&(f="array"),1!==arguments.length||"undefined"!==f);c++)h.push(f);if(e=h.join(","),b[e])return i.callExtend(this,"$main",b,b[e],arguments);for(c=h.length;c>=0;c--)if(e=h.slice(0,c).join(","),b[e+",..."])return i.callExtend(this,"$main",b,b[e+",..."],arguments)}throw g=void 0!==a?a:"function"==typeof this.name?this.name():"Unknown",console.log("Overload Definition:",b),'ForerunnerDB.Overload "'+g+'": Overloaded method does not have a matching signature "'+e+'" for the passed arguments: '+this.jStringify(h)}}return function(){}};d.prototype.generateSignaturePermutations=function(a){var b,c,d=[],e=["array","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},{}],25:[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":28}],26:[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":28}],27:[function(a,b,c){"use strict";var d=function(){this.init.apply(this,arguments)};d.prototype.init=function(){var a=this;this._encoder=[],this._decoder=[],this.registerHandler("$date",function(a){return a instanceof Date?(a.toJSON=function(){return"$date:"+this.toISOString()},!0):!1},function(b){return"string"==typeof b&&0===b.indexOf("$date:")?a.convert(new Date(b.substr(6))):void 0}),this.registerHandler("$regexp",function(a){return a instanceof RegExp?(a.toJSON=function(){return"$regexp:"+this.source.length+":"+this.source+":"+(this.global?"g":"")+(this.ignoreCase?"i":"")},!0):!1},function(b){if("string"==typeof b&&0===b.indexOf("$regexp:")){var c=b.substr(8),d=c.indexOf(":"),e=Number(c.substr(0,d)),f=c.substr(d+1,e),g=c.substr(d+e+2);return a.convert(new RegExp(f,g))}})},d.prototype.registerHandler=function(a,b,c){void 0!==a&&(this._encoder.push(b),this._decoder.push(c))},d.prototype.convert=function(a){var b,c=this._encoder;for(b=0;b<c.length;b++)if(c[b](a))return a;return a},d.prototype.reviver=function(){var a=this._decoder;return function(b,c){var d,e;for(e=0;e<a.length;e++)if(d=a[e](c),void 0!==d)return d;return c}},b.exports=d},{}],28:[function(a,b,c){"use strict";var d=a("./Overload"),e={version:"1.3.709",modules:{},plugins:{},index:{},_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":13,"./Mixin.ChainReactor":14,"./Mixin.Common":15,"./Mixin.Constants":16,"./Mixin.Events":17,"./Mixin.Matching":18,"./Mixin.Sorting":19,"./Mixin.Tags":20,"./Mixin.Triggers":21,"./Mixin.Updating":22,"./Overload":24}],29:[function(a,b,c){Array.prototype.filter||(Array.prototype.filter=function(a){if(void 0===this||null===this)throw new TypeError;var b=Object(this),c=b.length>>>0;if("function"!=typeof a)throw new TypeError;for(var d=[],e=arguments.length>=2?arguments[1]:void 0,f=0;c>f;f++)if(f in b){var g=b[f];a.call(e,g,f,b)&&d.push(g)}return d}),"function"!=typeof Object.create&&(Object.create=function(){var a=function(){};return function(b){if(arguments.length>1)throw Error("Second argument not supported");if("object"!=typeof b)throw TypeError("Argument must be an object");a.prototype=b;var c=new a;return a.prototype=null,c}}()),Array.prototype.indexOf||(Array.prototype.indexOf=function(a,b){var c;if(null===this)throw new TypeError('"this" is null or not defined');var d=Object(this),e=d.length>>>0;if(0===e)return-1;var f=+b||0;if(Math.abs(f)===1/0&&(f=0),f>=e)return-1;for(c=Math.max(f>=0?f:e-Math.abs(f),0);e>c;){if(c in d&&d[c]===a)return c;c++}return-1}),b.exports={}},{}]},{},[1]); |
admin/client/App/shared/Popout/PopoutList.js | trentmillar/keystone | /**
* Render a popout list. Can also use PopoutListItem and PopoutListHeading
*/
import React from 'react';
import blacklist from 'blacklist';
import classnames from 'classnames';
const PopoutList = React.createClass({
displayName: 'PopoutList',
propTypes: {
children: React.PropTypes.node.isRequired,
className: React.PropTypes.string,
},
render () {
const className = classnames('PopoutList', this.props.className);
const props = blacklist(this.props, 'className');
return (
<div className={className} {...props} />
);
},
});
module.exports = PopoutList;
// expose the child to the top level export
module.exports.Item = require('./PopoutListItem');
module.exports.Heading = require('./PopoutListHeading');
|
react-flux-mui/js/material-ui/src/svg-icons/action/assignment-late.js | pbogdan/react-flux-mui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ActionAssignmentLate = (props) => (
<SvgIcon {...props}>
<path d="M19 3h-4.18C14.4 1.84 13.3 1 12 1c-1.3 0-2.4.84-2.82 2H5c-1.1 0-2 .9-2 2v14c0 1.1.9 2 2 2h14c1.1 0 2-.9 2-2V5c0-1.1-.9-2-2-2zm-6 15h-2v-2h2v2zm0-4h-2V8h2v6zm-1-9c-.55 0-1-.45-1-1s.45-1 1-1 1 .45 1 1-.45 1-1 1z"/>
</SvgIcon>
);
ActionAssignmentLate = pure(ActionAssignmentLate);
ActionAssignmentLate.displayName = 'ActionAssignmentLate';
ActionAssignmentLate.muiName = 'SvgIcon';
export default ActionAssignmentLate;
|
src/_common/__tests__/Direction-test.js | qingweibinary/binary-next-gen | import React from 'react';
import { expect } from 'chai';
import { shallow } from 'enzyme';
import Direction from '../Direction';
describe('<Direction />', () => {
it('renders without any properties', () => {
const wrapper = shallow(<Direction />);
expect(wrapper.type()).to.equal('svg');
});
it('renders when direction is negative', () => {
const wrapper = shallow(<Direction direction={-1} />);
expect(wrapper.type()).to.equal('svg');
});
it('renders when direction is positive', () => {
const wrapper = shallow(<Direction direction={1} />);
expect(wrapper.type()).to.equal('svg');
});
});
|
spec/javascripts/jsx/conditional_release_stats/components/studentRangeSpec.js | djbender/canvas-lms | /*
* Copyright (C) 2016 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react'
import TestUtils from 'react-dom/test-utils'
import StudentRange from 'jsx/conditional_release_stats/components/student-range'
QUnit.module('Student Range')
const defaultProps = () => ({
range: {
scoring_range: {
id: 1,
rule_id: 1,
lower_bound: 0.7,
upper_bound: 1.0,
created_at: null,
updated_at: null,
position: null
},
size: 0,
students: [
{
user: {name: 'Foo Bar', id: 1}
},
{
user: {name: 'Bar Foo', id: 2}
}
]
},
loadStudent: () => {},
onStudentSelect: () => {}
})
const renderComponent = props => TestUtils.renderIntoDocument(<StudentRange {...props} />)
test('renders items correctly', () => {
const props = defaultProps()
const component = renderComponent(props)
const renderedList = TestUtils.scryRenderedDOMComponentsWithClass(
component,
'crs-student-range__item'
)
equal(renderedList.length, props.range.students.length, 'renders full component')
})
|
src/components/CurrencyConverter.js | jhkmjnhamster/vcash-electron | import React from 'react'
import { translate } from 'react-i18next'
import { action, computed, observable } from 'mobx'
import { inject, observer } from 'mobx-react'
import { Input, Tooltip } from 'antd'
import { decimalSeparator } from '../utilities/common'
import moment from 'moment'
@translate(['wallet'], { wait: true })
@inject('gui', 'rates')
@observer
class CurrencyConverter extends React.Component {
@observable amount = 1
@observable from = 'vcash'
constructor (props) {
super(props)
this.t = props.t
this.gui = props.gui
this.rates = props.rates
}
/**
* Get converted amounts.
* @function amounts
* @return {object} Converted amounts.
*/
@computed
get amounts () {
const { average, local } = this.rates
switch (this.from) {
case 'bitcoin':
return {
bitcoin: this.amount,
local: Math.round(this.amount * local * 1e3) / 1e3,
vcash: Math.round(this.amount / average * 1e6) / 1e6
}
case 'local':
return {
bitcoin: Math.round(this.amount / local * 1e8) / 1e8,
local: this.amount,
vcash: Math.round(this.amount / local / average * 1e6) / 1e6
}
case 'vcash':
return {
bitcoin: Math.round(this.amount * average * 1e8) / 1e8,
local: Math.round(this.amount * local * average * 1e3) / 1e3,
vcash: this.amount
}
}
}
/**
* Set amount and converting currency.
* @function convert
* @param {object} e - Input element event.
*/
@action
convert = e => {
const amount = e.target.value
const from = e.target.name
/** Allow only amount in 0000000[.,]000000 format. */
switch (decimalSeparator()) {
case '.':
if (amount.match(/^\d{0,7}(?:\.\d{0,6})?$/) === null) return
break
case ',':
if (amount.match(/^\d{0,7}(?:,\d{0,6})?$/) === null) return
break
}
this.amount = amount
this.from = from
}
render () {
return (
<div>
<div className='flex-sb' style={{ margin: '0 0 10px 0' }}>
<div className='flex'>
<i className='material-icons md-16'>cached</i>
<p>{this.t('wallet:currencyConverter')}</p>
</div>
<div className='flex'>
<img src='./assets/images/exchangePoloniex.png' />
<Tooltip
placement='bottom'
title={''.concat(
this.t('wallet:lastUpdated'),
' ',
moment(this.rates.poloniex.updated).format('LTS')
)}
>
<p style={{ margin: '0 10px 0 5px' }}>
<span style={{ fontWeight: '500' }}>
{new Intl.NumberFormat(this.gui.language, {
minimumFractionDigits: 8,
maximumFractionDigits: 8
}).format(this.rates.poloniex.last)}
</span>{' '}
BTC
</p>
</Tooltip>
<img src='./assets/images/exchangeBittrex.png' />
<Tooltip
placement='bottomRight'
title={''.concat(
this.t('wallet:lastUpdated'),
' ',
moment(this.rates.bittrex.updated).format('LTS')
)}
>
<p style={{ margin: '0 0 0 5px' }}>
<span style={{ fontWeight: '500' }}>
{new Intl.NumberFormat(this.gui.language, {
minimumFractionDigits: 8,
maximumFractionDigits: 8
}).format(this.rates.bittrex.Last)}
</span>{' '}
BTC
</p>
</Tooltip>
</div>
</div>
<div className='flex-sb'>
<div style={{ flex: '1' }}>
<Input
addonBefore='XVC'
name='vcash'
onChange={this.convert}
placeholder={this.t('wallet:amount')}
size='small'
value={this.amounts.vcash}
/>
</div>
<div style={{ flex: 1, margin: '0 10px 0 10px' }}>
<Input
addonBefore='BTC'
name='bitcoin'
onChange={this.convert}
placeholder={this.t('wallet:amount')}
size='small'
value={this.amounts.bitcoin}
/>
</div>
<div style={{ flex: '1' }}>
<Input
addonBefore={this.gui.localCurrency}
name='local'
onChange={this.convert}
placeholder={this.t('wallet:amount')}
size='small'
value={this.amounts.local}
/>
</div>
</div>
</div>
)
}
}
export default CurrencyConverter
|
Libraries/Components/TextInput/TextInput.js | Guardiannw/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.
*
* @providesModule TextInput
* @flow
*/
'use strict';
const ColorPropType = require('ColorPropType');
const DocumentSelectionState = require('DocumentSelectionState');
const EventEmitter = require('EventEmitter');
const NativeMethodsMixin = require('NativeMethodsMixin');
const Platform = require('Platform');
const React = require('React');
const PropTypes = require('prop-types');
const ReactNative = require('ReactNative');
const StyleSheet = require('StyleSheet');
const Text = require('Text');
const TextInputState = require('TextInputState');
const TimerMixin = require('react-timer-mixin');
const TouchableWithoutFeedback = require('TouchableWithoutFeedback');
const UIManager = require('UIManager');
const ViewPropTypes = require('ViewPropTypes');
const emptyFunction = require('fbjs/lib/emptyFunction');
const invariant = require('fbjs/lib/invariant');
const requireNativeComponent = require('requireNativeComponent');
const warning = require('fbjs/lib/warning');
const onlyMultiline = {
onTextInput: true,
children: true,
};
if (Platform.OS === 'android') {
var AndroidTextInput = requireNativeComponent('AndroidTextInput', null);
} else if (Platform.OS === 'ios') {
var RCTTextView = requireNativeComponent('RCTTextView', null);
var RCTTextField = requireNativeComponent('RCTTextField', null);
}
type Event = Object;
type Selection = {
start: number,
end?: number,
};
const DataDetectorTypes = [
'phoneNumber',
'link',
'address',
'calendarEvent',
'none',
'all',
];
/**
* A foundational component for inputting text into the app via a
* keyboard. Props provide configurability for several features, such as
* auto-correction, auto-capitalization, placeholder text, and different keyboard
* types, such as a numeric keypad.
*
* The simplest use case is to plop down a `TextInput` and subscribe to the
* `onChangeText` events to read the user input. There are also other events,
* such as `onSubmitEditing` and `onFocus` that can be subscribed to. A simple
* example:
*
* ```ReactNativeWebPlayer
* import React, { Component } from 'react';
* import { AppRegistry, TextInput } from 'react-native';
*
* export default class UselessTextInput extends Component {
* constructor(props) {
* super(props);
* this.state = { text: 'Useless Placeholder' };
* }
*
* render() {
* return (
* <TextInput
* style={{height: 40, borderColor: 'gray', borderWidth: 1}}
* onChangeText={(text) => this.setState({text})}
* value={this.state.text}
* />
* );
* }
* }
*
* // skip this line if using Create React Native App
* AppRegistry.registerComponent('AwesomeProject', () => UselessTextInput);
* ```
*
* Note that some props are only available with `multiline={true/false}`.
* Additionally, border styles that apply to only one side of the element
* (e.g., `borderBottomColor`, `borderLeftWidth`, etc.) will not be applied if
* `multiline=false`. To achieve the same effect, you can wrap your `TextInput`
* in a `View`:
*
* ```ReactNativeWebPlayer
* import React, { Component } from 'react';
* import { AppRegistry, View, TextInput } from 'react-native';
*
* class UselessTextInput extends Component {
* render() {
* return (
* <TextInput
* {...this.props} // Inherit any props passed to it; e.g., multiline, numberOfLines below
* editable = {true}
* maxLength = {40}
* />
* );
* }
* }
*
* export default class UselessTextInputMultiline extends Component {
* constructor(props) {
* super(props);
* this.state = {
* text: 'Useless Multiline Placeholder',
* };
* }
*
* // If you type something in the text box that is a color, the background will change to that
* // color.
* render() {
* return (
* <View style={{
* backgroundColor: this.state.text,
* borderBottomColor: '#000000',
* borderBottomWidth: 1 }}
* >
* <UselessTextInput
* multiline = {true}
* numberOfLines = {4}
* onChangeText={(text) => this.setState({text})}
* value={this.state.text}
* />
* </View>
* );
* }
* }
*
* // skip these lines if using Create React Native App
* AppRegistry.registerComponent(
* 'AwesomeProject',
* () => UselessTextInputMultiline
* );
* ```
*
* `TextInput` has by default a border at the bottom of its view. This border
* has its padding set by the background image provided by the system, and it
* cannot be changed. Solutions to avoid this is to either not set height
* explicitly, case in which the system will take care of displaying the border
* in the correct position, or to not display the border by setting
* `underlineColorAndroid` to transparent.
*
* Note that on Android performing text selection in input can change
* app's activity `windowSoftInputMode` param to `adjustResize`.
* This may cause issues with components that have position: 'absolute'
* while keyboard is active. To avoid this behavior either specify `windowSoftInputMode`
* in AndroidManifest.xml ( https://developer.android.com/guide/topics/manifest/activity-element.html )
* or control this param programmatically with native code.
*
*/
// $FlowFixMe(>=0.41.0)
const TextInput = React.createClass({
statics: {
/* TODO(brentvatne) docs are needed for this */
State: TextInputState,
},
propTypes: {
...ViewPropTypes,
/**
* Can tell `TextInput` to automatically capitalize certain characters.
*
* - `characters`: all characters.
* - `words`: first letter of each word.
* - `sentences`: first letter of each sentence (*default*).
* - `none`: don't auto capitalize anything.
*/
autoCapitalize: PropTypes.oneOf([
'none',
'sentences',
'words',
'characters',
]),
/**
* If `false`, disables auto-correct. The default value is `true`.
*/
autoCorrect: PropTypes.bool,
/**
* If `false`, disables spell-check style (i.e. red underlines).
* The default value is inherited from `autoCorrect`.
* @platform ios
*/
spellCheck: PropTypes.bool,
/**
* If `true`, focuses the input on `componentDidMount`.
* The default value is `false`.
*/
autoFocus: PropTypes.bool,
/**
* If `false`, text is not editable. The default value is `true`.
*/
editable: PropTypes.bool,
/**
* Determines which keyboard to open, e.g.`numeric`.
*
* The following values work across platforms:
*
* - `default`
* - `numeric`
* - `email-address`
* - `phone-pad`
*/
keyboardType: PropTypes.oneOf([
// Cross-platform
'default',
'email-address',
'numeric',
'phone-pad',
// iOS-only
'ascii-capable',
'numbers-and-punctuation',
'url',
'number-pad',
'name-phone-pad',
'decimal-pad',
'twitter',
'web-search',
]),
/**
* Determines the color of the keyboard.
* @platform ios
*/
keyboardAppearance: PropTypes.oneOf([
'default',
'light',
'dark',
]),
/**
* Determines how the return key should look. On Android you can also use
* `returnKeyLabel`.
*
* *Cross platform*
*
* The following values work across platforms:
*
* - `done`
* - `go`
* - `next`
* - `search`
* - `send`
*
* *Android Only*
*
* The following values work on Android only:
*
* - `none`
* - `previous`
*
* *iOS Only*
*
* The following values work on iOS only:
*
* - `default`
* - `emergency-call`
* - `google`
* - `join`
* - `route`
* - `yahoo`
*/
returnKeyType: PropTypes.oneOf([
// Cross-platform
'done',
'go',
'next',
'search',
'send',
// Android-only
'none',
'previous',
// iOS-only
'default',
'emergency-call',
'google',
'join',
'route',
'yahoo',
]),
/**
* Sets the return key to the label. Use it instead of `returnKeyType`.
* @platform android
*/
returnKeyLabel: PropTypes.string,
/**
* Limits the maximum number of characters that can be entered. Use this
* instead of implementing the logic in JS to avoid flicker.
*/
maxLength: PropTypes.number,
/**
* Sets the number of lines for a `TextInput`. Use it with multiline set to
* `true` to be able to fill the lines.
* @platform android
*/
numberOfLines: PropTypes.number,
/**
* When `false`, if there is a small amount of space available around a text input
* (e.g. landscape orientation on a phone), the OS may choose to have the user edit
* the text inside of a full screen text input mode. When `true`, this feature is
* disabled and users will always edit the text directly inside of the text input.
* Defaults to `false`.
* @platform android
*/
disableFullscreenUI: PropTypes.bool,
/**
* If `true`, the keyboard disables the return key when there is no text and
* automatically enables it when there is text. The default value is `false`.
* @platform ios
*/
enablesReturnKeyAutomatically: PropTypes.bool,
/**
* If `true`, the text input can be multiple lines.
* The default value is `false`.
*/
multiline: PropTypes.bool,
/**
* Set text break strategy on Android API Level 23+, possible values are `simple`, `highQuality`, `balanced`
* The default value is `simple`.
* @platform android
*/
textBreakStrategy: PropTypes.oneOf(['simple', 'highQuality', 'balanced']),
/**
* Callback that is called when the text input is blurred.
*/
onBlur: PropTypes.func,
/**
* Callback that is called when the text input is focused.
*/
onFocus: PropTypes.func,
/**
* Callback that is called when the text input's text changes.
*/
onChange: PropTypes.func,
/**
* Callback that is called when the text input's text changes.
* Changed text is passed as an argument to the callback handler.
*/
onChangeText: PropTypes.func,
/**
* Callback that is called when the text input's content size changes.
* This will be called with
* `{ nativeEvent: { contentSize: { width, height } } }`.
*
* Only called for multiline text inputs.
*/
onContentSizeChange: PropTypes.func,
/**
* Callback that is called when text input ends.
*/
onEndEditing: PropTypes.func,
/**
* Callback that is called when the text input selection is changed.
* This will be called with
* `{ nativeEvent: { selection: { start, end } } }`.
*/
onSelectionChange: PropTypes.func,
/**
* Callback that is called when the text input's submit button is pressed.
* Invalid if `multiline={true}` is specified.
*/
onSubmitEditing: PropTypes.func,
/**
* Callback that is called when a key is pressed.
* This will be called with `{ nativeEvent: { key: keyValue } }`
* where `keyValue` is `'Enter'` or `'Backspace'` for respective keys and
* the typed-in character otherwise including `' '` for space.
* Fires before `onChange` callbacks.
* @platform ios
*/
onKeyPress: PropTypes.func,
/**
* Invoked on mount and layout changes with `{x, y, width, height}`.
*/
onLayout: PropTypes.func,
/**
* Invoked on content scroll with `{ nativeEvent: { contentOffset: { x, y } } }`.
* May also contain other properties from ScrollEvent but on Android contentSize
* is not provided for performance reasons.
*/
onScroll: PropTypes.func,
/**
* The string that will be rendered before text input has been entered.
*/
placeholder: PropTypes.node,
/**
* The text color of the placeholder string.
*/
placeholderTextColor: ColorPropType,
/**
* If `true`, the text input obscures the text entered so that sensitive text
* like passwords stay secure. The default value is `false`.
*/
secureTextEntry: PropTypes.bool,
/**
* The highlight and cursor color of the text input.
*/
selectionColor: ColorPropType,
/**
* An instance of `DocumentSelectionState`, this is some state that is responsible for
* maintaining selection information for a document.
*
* Some functionality that can be performed with this instance is:
*
* - `blur()`
* - `focus()`
* - `update()`
*
* > You can reference `DocumentSelectionState` in
* > [`vendor/document/selection/DocumentSelectionState.js`](https://github.com/facebook/react-native/blob/master/Libraries/vendor/document/selection/DocumentSelectionState.js)
*
* @platform ios
*/
selectionState: PropTypes.instanceOf(DocumentSelectionState),
/**
* The start and end of the text input's selection. Set start and end to
* the same value to position the cursor.
*/
selection: PropTypes.shape({
start: PropTypes.number.isRequired,
end: PropTypes.number,
}),
/**
* The value to show for the text input. `TextInput` is a controlled
* component, which means the native value will be forced to match this
* value prop if provided. For most uses, this works great, but in some
* cases this may cause flickering - one common cause is preventing edits
* by keeping value the same. In addition to simply setting the same value,
* either set `editable={false}`, or set/update `maxLength` to prevent
* unwanted edits without flicker.
*/
value: PropTypes.string,
/**
* Provides an initial value that will change when the user starts typing.
* Useful for simple use-cases where you do not want to deal with listening
* to events and updating the value prop to keep the controlled state in sync.
*/
defaultValue: PropTypes.string,
/**
* When the clear button should appear on the right side of the text view.
* @platform ios
*/
clearButtonMode: PropTypes.oneOf([
'never',
'while-editing',
'unless-editing',
'always',
]),
/**
* If `true`, clears the text field automatically when editing begins.
* @platform ios
*/
clearTextOnFocus: PropTypes.bool,
/**
* If `true`, all text will automatically be selected on focus.
*/
selectTextOnFocus: PropTypes.bool,
/**
* If `true`, the text field will blur when submitted.
* The default value is true for single-line fields and false for
* multiline fields. Note that for multiline fields, setting `blurOnSubmit`
* to `true` means that pressing return will blur the field and trigger the
* `onSubmitEditing` event instead of inserting a newline into the field.
*/
blurOnSubmit: PropTypes.bool,
/**
* Note that not all Text styles are supported,
* see [Issue#7070](https://github.com/facebook/react-native/issues/7070)
* for more detail.
*
* [Styles](docs/style.html)
*/
style: Text.propTypes.style,
/**
* The color of the `TextInput` underline.
* @platform android
*/
underlineColorAndroid: ColorPropType,
/**
* If defined, the provided image resource will be rendered on the left.
* @platform android
*/
inlineImageLeft: PropTypes.string,
/**
* Padding between the inline image, if any, and the text input itself.
* @platform android
*/
inlineImagePadding: PropTypes.number,
/**
* Determines the types of data converted to clickable URLs in the text input.
* Only valid if `multiline={true}` and `editable={false}`.
* By default no data types are detected.
*
* You can provide one type or an array of many types.
*
* Possible values for `dataDetectorTypes` are:
*
* - `'phoneNumber'`
* - `'link'`
* - `'address'`
* - `'calendarEvent'`
* - `'none'`
* - `'all'`
*
* @platform ios
*/
dataDetectorTypes: PropTypes.oneOfType([
PropTypes.oneOf(DataDetectorTypes),
PropTypes.arrayOf(PropTypes.oneOf(DataDetectorTypes)),
]),
/**
* If `true`, caret is hidden. The default value is `false`.
*/
caretHidden: PropTypes.bool,
},
/**
* `NativeMethodsMixin` will look for this when invoking `setNativeProps`. We
* make `this` look like an actual native component class.
*/
mixins: [NativeMethodsMixin, TimerMixin],
/**
* Returns `true` if the input is currently focused; `false` otherwise.
*/
isFocused: function(): boolean {
return TextInputState.currentlyFocusedField() ===
ReactNative.findNodeHandle(this._inputRef);
},
contextTypes: {
onFocusRequested: PropTypes.func,
focusEmitter: PropTypes.instanceOf(EventEmitter),
},
_inputRef: (undefined: any),
_focusSubscription: (undefined: ?Function),
_lastNativeText: (undefined: ?string),
_lastNativeSelection: (undefined: ?Selection),
componentDidMount: function() {
this._lastNativeText = this.props.value;
if (!this.context.focusEmitter) {
if (this.props.autoFocus) {
this.requestAnimationFrame(this.focus);
}
return;
}
this._focusSubscription = this.context.focusEmitter.addListener(
'focus',
(el) => {
if (this === el) {
this.requestAnimationFrame(this.focus);
} else if (this.isFocused()) {
this.blur();
}
}
);
if (this.props.autoFocus) {
this.context.onFocusRequested(this);
}
},
componentWillUnmount: function() {
this._focusSubscription && this._focusSubscription.remove();
if (this.isFocused()) {
this.blur();
}
},
getChildContext: function(): Object {
return {isInAParentText: true};
},
childContextTypes: {
isInAParentText: PropTypes.bool
},
/**
* Removes all text from the `TextInput`.
*/
clear: function() {
this.setNativeProps({text: ''});
},
render: function() {
if (Platform.OS === 'ios') {
return this._renderIOS();
} else if (Platform.OS === 'android') {
return this._renderAndroid();
}
},
_getText: function(): ?string {
return typeof this.props.value === 'string' ?
this.props.value :
(
typeof this.props.defaultValue === 'string' ?
this.props.defaultValue :
''
);
},
_setNativeRef: function(ref: any) {
this._inputRef = ref;
},
_renderIOS: function() {
var textContainer;
var props = Object.assign({}, this.props);
props.style = [this.props.style];
if (props.selection && props.selection.end == null) {
props.selection = {start: props.selection.start, end: props.selection.start};
}
if (!props.multiline) {
if (__DEV__) {
for (var propKey in onlyMultiline) {
if (props[propKey]) {
const error = new Error(
'TextInput prop `' + propKey + '` is only supported with multiline.'
);
warning(false, '%s', error.stack);
}
}
}
textContainer =
<RCTTextField
ref={this._setNativeRef}
{...props}
onFocus={this._onFocus}
onBlur={this._onBlur}
onChange={this._onChange}
onSelectionChange={this._onSelectionChange}
onSelectionChangeShouldSetResponder={emptyFunction.thatReturnsTrue}
text={this._getText()}
/>;
} else {
var children = props.children;
var childCount = 0;
React.Children.forEach(children, () => ++childCount);
invariant(
!(props.value && childCount),
'Cannot specify both value and children.'
);
if (childCount >= 1) {
children = <Text style={props.style}>{children}</Text>;
}
if (props.inputView) {
children = [children, props.inputView];
}
props.style.unshift(styles.multilineInput);
textContainer =
<RCTTextView
ref={this._setNativeRef}
{...props}
children={children}
onFocus={this._onFocus}
onBlur={this._onBlur}
onChange={this._onChange}
onContentSizeChange={this.props.onContentSizeChange}
onSelectionChange={this._onSelectionChange}
onTextInput={this._onTextInput}
onSelectionChangeShouldSetResponder={emptyFunction.thatReturnsTrue}
text={this._getText()}
dataDetectorTypes={this.props.dataDetectorTypes}
onScroll={this._onScroll}
/>;
}
return (
<TouchableWithoutFeedback
onLayout={props.onLayout}
onPress={this._onPress}
rejectResponderTermination={true}
accessible={props.accessible}
accessibilityLabel={props.accessibilityLabel}
accessibilityTraits={props.accessibilityTraits}
nativeID={this.props.nativeID}
testID={props.testID}>
{textContainer}
</TouchableWithoutFeedback>
);
},
_renderAndroid: function() {
const props = Object.assign({}, this.props);
props.style = [this.props.style];
props.autoCapitalize =
UIManager.AndroidTextInput.Constants.AutoCapitalizationType[this.props.autoCapitalize];
var children = this.props.children;
var childCount = 0;
React.Children.forEach(children, () => ++childCount);
invariant(
!(this.props.value && childCount),
'Cannot specify both value and children.'
);
if (childCount > 1) {
children = <Text>{children}</Text>;
}
if (props.selection && props.selection.end == null) {
props.selection = {start: props.selection.start, end: props.selection.start};
}
const textContainer =
<AndroidTextInput
ref={this._setNativeRef}
{...props}
mostRecentEventCount={0}
onFocus={this._onFocus}
onBlur={this._onBlur}
onChange={this._onChange}
onSelectionChange={this._onSelectionChange}
onTextInput={this._onTextInput}
text={this._getText()}
children={children}
disableFullscreenUI={this.props.disableFullscreenUI}
textBreakStrategy={this.props.textBreakStrategy}
onScroll={this._onScroll}
/>;
return (
<TouchableWithoutFeedback
onLayout={this.props.onLayout}
onPress={this._onPress}
accessible={this.props.accessible}
accessibilityLabel={this.props.accessibilityLabel}
accessibilityComponentType={this.props.accessibilityComponentType}
nativeID={this.props.nativeID}
testID={this.props.testID}>
{textContainer}
</TouchableWithoutFeedback>
);
},
_onFocus: function(event: Event) {
if (this.props.onFocus) {
this.props.onFocus(event);
}
if (this.props.selectionState) {
this.props.selectionState.focus();
}
},
_onPress: function(event: Event) {
if (this.props.editable || this.props.editable === undefined) {
this.focus();
}
},
_onChange: function(event: Event) {
// Make sure to fire the mostRecentEventCount first so it is already set on
// native when the text value is set.
if (this._inputRef) {
this._inputRef.setNativeProps({
mostRecentEventCount: event.nativeEvent.eventCount,
});
}
var text = event.nativeEvent.text;
this.props.onChange && this.props.onChange(event);
this.props.onChangeText && this.props.onChangeText(text);
if (!this._inputRef) {
// calling `this.props.onChange` or `this.props.onChangeText`
// may clean up the input itself. Exits here.
return;
}
this._lastNativeText = text;
this.forceUpdate();
},
_onSelectionChange: function(event: Event) {
this.props.onSelectionChange && this.props.onSelectionChange(event);
if (!this._inputRef) {
// calling `this.props.onSelectionChange`
// may clean up the input itself. Exits here.
return;
}
this._lastNativeSelection = event.nativeEvent.selection;
if (this.props.selection || this.props.selectionState) {
this.forceUpdate();
}
},
componentDidUpdate: function () {
// This is necessary in case native updates the text and JS decides
// that the update should be ignored and we should stick with the value
// that we have in JS.
const nativeProps = {};
if (this._lastNativeText !== this.props.value && typeof this.props.value === 'string') {
nativeProps.text = this.props.value;
}
// Selection is also a controlled prop, if the native value doesn't match
// JS, update to the JS value.
const {selection} = this.props;
if (this._lastNativeSelection && selection &&
(this._lastNativeSelection.start !== selection.start ||
this._lastNativeSelection.end !== selection.end)) {
nativeProps.selection = this.props.selection;
}
if (Object.keys(nativeProps).length > 0 && this._inputRef) {
this._inputRef.setNativeProps(nativeProps);
}
if (this.props.selectionState && selection) {
this.props.selectionState.update(selection.start, selection.end);
}
},
_onBlur: function(event: Event) {
this.blur();
if (this.props.onBlur) {
this.props.onBlur(event);
}
if (this.props.selectionState) {
this.props.selectionState.blur();
}
},
_onTextInput: function(event: Event) {
this.props.onTextInput && this.props.onTextInput(event);
},
_onScroll: function(event: Event) {
this.props.onScroll && this.props.onScroll(event);
},
});
var styles = StyleSheet.create({
multilineInput: {
// This default top inset makes RCTTextView seem as close as possible
// to single-line RCTTextField defaults, using the system defaults
// of font size 17 and a height of 31 points.
paddingTop: 5,
},
});
module.exports = TextInput;
|
ajax/libs/yui/3.4.1/event-focus/event-focus.js | hcxiong/cdnjs | YUI.add('event-focus', function(Y) {
/**
* Adds bubbling and delegation support to DOM events focus and blur.
*
* @module event
* @submodule event-focus
*/
var Event = Y.Event,
YLang = Y.Lang,
isString = YLang.isString,
useActivate = YLang.isFunction(
Y.DOM.create('<p onbeforeactivate=";"/>').onbeforeactivate);
function define(type, proxy, directEvent) {
var nodeDataKey = '_' + type + 'Notifiers';
Y.Event.define(type, {
_attach: function (el, notifier, delegate) {
if (Y.DOM.isWindow(el)) {
return Event._attach([type, function (e) {
notifier.fire(e);
}, el]);
} else {
return Event._attach(
[proxy, this._proxy, el, this, notifier, delegate],
{ capture: true });
}
},
_proxy: function (e, notifier, delegate) {
var node = e.target,
notifiers = node.getData(nodeDataKey),
yuid = Y.stamp(e.currentTarget._node),
defer = (useActivate || e.target !== e.currentTarget),
sub = notifier.handle.sub,
filterArgs = [node, e].concat(sub.args || []),
directSub;
notifier.currentTarget = (delegate) ? node : e.currentTarget;
notifier.container = (delegate) ? e.currentTarget : null;
if (!sub.filter || sub.filter.apply(node, filterArgs)) {
// Maintain a list to handle subscriptions from nested
// containers div#a>div#b>input #a.on(focus..) #b.on(focus..),
// use one focus or blur subscription that fires notifiers from
// #b then #a to emulate bubble sequence.
if (!notifiers) {
notifiers = {};
node.setData(nodeDataKey, notifiers);
// only subscribe to the element's focus if the target is
// not the current target (
if (defer) {
directSub = Event._attach(
[directEvent, this._notify, node._node]).sub;
directSub.once = true;
}
}
if (!notifiers[yuid]) {
notifiers[yuid] = [];
}
notifiers[yuid].push(notifier);
if (!defer) {
this._notify(e);
}
}
},
_notify: function (e, container) {
var node = e.currentTarget,
notifiers = node.getData(nodeDataKey),
// document.get('ownerDocument') returns null
doc = node.get('ownerDocument') || node,
target = node,
nots = [],
notifier, i, len;
if (notifiers) {
// Walk up the parent axis until the origin node,
while (target && target !== doc) {
nots.push.apply(nots, notifiers[Y.stamp(target)] || []);
target = target.get('parentNode');
}
nots.push.apply(nots, notifiers[Y.stamp(doc)] || []);
for (i = 0, len = nots.length; i < len; ++i) {
notifier = nots[i];
e.currentTarget = nots[i].currentTarget;
if (notifier.container) {
e.container = notifier.container;
}
notifier.fire(e);
}
// clear the notifications list (mainly for delegation)
node.clearData(nodeDataKey);
}
},
on: function (node, sub, notifier) {
sub.onHandle = this._attach(node._node, notifier);
},
detach: function (node, sub) {
sub.onHandle.detach();
},
delegate: function (node, sub, notifier, filter) {
if (isString(filter)) {
sub.filter = Y.delegate.compileFilter(filter);
}
sub.delegateHandle = this._attach(node._node, notifier, true);
},
detachDelegate: function (node, sub) {
sub.delegateHandle.detach();
}
}, true);
}
// For IE, we need to defer to focusin rather than focus because
// `el.focus(); doSomething();` executes el.onbeforeactivate, el.onactivate,
// el.onfocusin, doSomething, then el.onfocus. All others support capture
// phase focus, which executes before doSomething. To guarantee consistent
// behavior for this use case, IE's direct subscriptions are made against
// focusin so subscribers will be notified before js following el.focus() is
// executed.
if (useActivate) {
// name capture phase direct subscription
define("focus", "beforeactivate", "focusin");
define("blur", "beforedeactivate", "focusout");
} else {
define("focus", "focus", "focus");
define("blur", "blur", "blur");
}
}, '@VERSION@' ,{requires:['event-synthetic']});
|
ajax/libs/angular.js/1.2.0/angular-scenario.js | ajoslin/cdnjs | /*!
* 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 ) {'use strict';
// 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+
//
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 );
/**
* @license AngularJS v1.2.0
* (c) 2010-2012 Google, Inc. http://angularjs.org
* License: MIT
*/
(function(window, document){
var _jQuery = window.jQuery.noConflict(true);
/**
* @description
*
* This object provides a utility for producing rich Error messages within
* Angular. It can be called as follows:
*
* var exampleMinErr = minErr('example');
* throw exampleMinErr('one', 'This {0} is {1}', foo, bar);
*
* The above creates an instance of minErr in the example namespace. The
* resulting error will have a namespaced error code of example.one. The
* resulting error will replace {0} with the value of foo, and {1} with the
* value of bar. The object is not restricted in the number of arguments it can
* take.
*
* If fewer arguments are specified than necessary for interpolation, the extra
* interpolation markers will be preserved in the final string.
*
* Since data will be parsed statically during a build step, some restrictions
* are applied with respect to how minErr instances are created and called.
* Instances should have names of the form namespaceMinErr for a minErr created
* using minErr('namespace') . Error codes, namespaces and template strings
* should all be static strings, not variables or general expressions.
*
* @param {string} module The namespace to use for the new minErr instance.
* @returns {function(string, string, ...): Error} instance
*/
function minErr(module) {
return function () {
var code = arguments[0],
prefix = '[' + (module ? module + ':' : '') + code + '] ',
template = arguments[1],
templateArgs = arguments,
stringify = function (obj) {
if (isFunction(obj)) {
return obj.toString().replace(/ \{[\s\S]*$/, '');
} else if (isUndefined(obj)) {
return 'undefined';
} else if (!isString(obj)) {
return JSON.stringify(obj);
}
return obj;
},
message, i;
message = prefix + template.replace(/\{\d+\}/g, function (match) {
var index = +match.slice(1, -1), arg;
if (index + 2 < templateArgs.length) {
arg = templateArgs[index + 2];
if (isFunction(arg)) {
return arg.toString().replace(/ ?\{[\s\S]*$/, '');
} else if (isUndefined(arg)) {
return 'undefined';
} else if (!isString(arg)) {
return toJson(arg);
}
return arg;
}
return match;
});
message = message + '\nhttp://errors.angularjs.org/' + version.full + '/' +
(module ? module + '/' : '') + code;
for (i = 2; i < arguments.length; i++) {
message = message + (i == 2 ? '?' : '&') + 'p' + (i-2) + '=' +
encodeURIComponent(stringify(arguments[i]));
}
return new Error(message);
};
}
/* We need to tell jshint what variables are being exported */
/* global
-angular,
-msie,
-jqLite,
-jQuery,
-slice,
-push,
-toString,
-ngMinErr,
-_angular,
-angularModule,
-nodeName_,
-uid,
-lowercase,
-uppercase,
-manualLowercase,
-manualUppercase,
-nodeName_,
-isArrayLike,
-forEach,
-sortedKeys,
-forEachSorted,
-reverseParams,
-nextUid,
-setHashKey,
-extend,
-int,
-inherit,
-noop,
-identity,
-valueFn,
-isUndefined,
-isDefined,
-isObject,
-isString,
-isNumber,
-isDate,
-isArray,
-isFunction,
-isRegExp,
-isWindow,
-isScope,
-isFile,
-isBoolean,
-trim,
-isElement,
-makeMap,
-map,
-size,
-includes,
-indexOf,
-arrayRemove,
-isLeafNode,
-copy,
-shallowCopy,
-equals,
-csp,
-concat,
-sliceArgs,
-bind,
-toJsonReplacer,
-toJson,
-fromJson,
-toBoolean,
-startingTag,
-tryDecodeURIComponent,
-parseKeyValue,
-toKeyValue,
-encodeUriSegment,
-encodeUriQuery,
-angularInit,
-bootstrap,
-snake_case,
-bindJQuery,
-assertArg,
-assertArgFn,
-assertNotHasOwnProperty,
-getter,
-getBlockElements
*/
////////////////////////////////////
/**
* @ngdoc function
* @name angular.lowercase
* @function
*
* @description Converts the specified string to lowercase.
* @param {string} string String to be converted to lowercase.
* @returns {string} Lowercased string.
*/
var lowercase = function(string){return isString(string) ? string.toLowerCase() : string;};
/**
* @ngdoc function
* @name angular.uppercase
* @function
*
* @description Converts the specified string to uppercase.
* @param {string} string String to be converted to uppercase.
* @returns {string} Uppercased string.
*/
var uppercase = function(string){return isString(string) ? string.toUpperCase() : string;};
var manualLowercase = function(s) {
/* jshint bitwise: false */
return isString(s)
? s.replace(/[A-Z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) | 32);})
: s;
};
var manualUppercase = function(s) {
/* jshint bitwise: false */
return isString(s)
? s.replace(/[a-z]/g, function(ch) {return String.fromCharCode(ch.charCodeAt(0) & ~32);})
: s;
};
// String#toLowerCase and String#toUpperCase don't produce correct results in browsers with Turkish
// locale, for this reason we need to detect this case and redefine lowercase/uppercase methods
// with correct but slower alternatives.
if ('i' !== 'I'.toLowerCase()) {
lowercase = manualLowercase;
uppercase = manualUppercase;
}
var /** holds major version number for IE or NaN for real browsers */
msie,
jqLite, // delay binding since jQuery could be loaded after us.
jQuery, // delay binding
slice = [].slice,
push = [].push,
toString = Object.prototype.toString,
ngMinErr = minErr('ng'),
_angular = window.angular,
/** @name angular */
angular = window.angular || (window.angular = {}),
angularModule,
nodeName_,
uid = ['0', '0', '0'];
/**
* IE 11 changed the format of the UserAgent string.
* See http://msdn.microsoft.com/en-us/library/ms537503.aspx
*/
msie = int((/msie (\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]);
if (isNaN(msie)) {
msie = int((/trident\/.*; rv:(\d+)/.exec(lowercase(navigator.userAgent)) || [])[1]);
}
/**
* @private
* @param {*} obj
* @return {boolean} Returns true if `obj` is an array or array-like object (NodeList, Arguments,
* String ...)
*/
function isArrayLike(obj) {
if (obj == null || isWindow(obj)) {
return false;
}
var length = obj.length;
if (obj.nodeType === 1 && length) {
return true;
}
return isString(obj) || isArray(obj) || length === 0 ||
typeof length === 'number' && length > 0 && (length - 1) in obj;
}
/**
* @ngdoc function
* @name angular.forEach
* @function
*
* @description
* Invokes the `iterator` function once for each item in `obj` collection, which can be either an
* object or an array. The `iterator` function is invoked with `iterator(value, key)`, where `value`
* is the value of an object property or an array element and `key` is the object property key or
* array element index. Specifying a `context` for the function is optional.
*
* Note: this function was previously known as `angular.foreach`.
*
<pre>
var values = {name: 'misko', gender: 'male'};
var log = [];
angular.forEach(values, function(value, key){
this.push(key + ': ' + value);
}, log);
expect(log).toEqual(['name: misko', 'gender:male']);
</pre>
*
* @param {Object|Array} obj Object to iterate over.
* @param {Function} iterator Iterator function.
* @param {Object=} context Object to become context (`this`) for the iterator function.
* @returns {Object|Array} Reference to `obj`.
*/
function forEach(obj, iterator, context) {
var key;
if (obj) {
if (isFunction(obj)){
for (key in obj) {
if (key != 'prototype' && key != 'length' && key != 'name' && obj.hasOwnProperty(key)) {
iterator.call(context, obj[key], key);
}
}
} else if (obj.forEach && obj.forEach !== forEach) {
obj.forEach(iterator, context);
} else if (isArrayLike(obj)) {
for (key = 0; key < obj.length; key++)
iterator.call(context, obj[key], key);
} else {
for (key in obj) {
if (obj.hasOwnProperty(key)) {
iterator.call(context, obj[key], key);
}
}
}
}
return obj;
}
function sortedKeys(obj) {
var keys = [];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
keys.push(key);
}
}
return keys.sort();
}
function forEachSorted(obj, iterator, context) {
var keys = sortedKeys(obj);
for ( var i = 0; i < keys.length; i++) {
iterator.call(context, obj[keys[i]], keys[i]);
}
return keys;
}
/**
* when using forEach the params are value, key, but it is often useful to have key, value.
* @param {function(string, *)} iteratorFn
* @returns {function(*, string)}
*/
function reverseParams(iteratorFn) {
return function(value, key) { iteratorFn(key, value); };
}
/**
* A consistent way of creating unique IDs in angular. The ID is a sequence of alpha numeric
* characters such as '012ABC'. The reason why we are not using simply a number counter is that
* the number string gets longer over time, and it can also overflow, where as the nextId
* will grow much slower, it is a string, and it will never overflow.
*
* @returns an unique alpha-numeric string
*/
function nextUid() {
var index = uid.length;
var digit;
while(index) {
index--;
digit = uid[index].charCodeAt(0);
if (digit == 57 /*'9'*/) {
uid[index] = 'A';
return uid.join('');
}
if (digit == 90 /*'Z'*/) {
uid[index] = '0';
} else {
uid[index] = String.fromCharCode(digit + 1);
return uid.join('');
}
}
uid.unshift('0');
return uid.join('');
}
/**
* Set or clear the hashkey for an object.
* @param obj object
* @param h the hashkey (!truthy to delete the hashkey)
*/
function setHashKey(obj, h) {
if (h) {
obj.$$hashKey = h;
}
else {
delete obj.$$hashKey;
}
}
/**
* @ngdoc function
* @name angular.extend
* @function
*
* @description
* Extends the destination object `dst` by copying all of the properties from the `src` object(s)
* to `dst`. You can specify multiple `src` objects.
*
* @param {Object} dst Destination object.
* @param {...Object} src Source object(s).
* @returns {Object} Reference to `dst`.
*/
function extend(dst) {
var h = dst.$$hashKey;
forEach(arguments, function(obj){
if (obj !== dst) {
forEach(obj, function(value, key){
dst[key] = value;
});
}
});
setHashKey(dst,h);
return dst;
}
function int(str) {
return parseInt(str, 10);
}
function inherit(parent, extra) {
return extend(new (extend(function() {}, {prototype:parent}))(), extra);
}
/**
* @ngdoc function
* @name angular.noop
* @function
*
* @description
* A function that performs no operations. This function can be useful when writing code in the
* functional style.
<pre>
function foo(callback) {
var result = calculateResult();
(callback || angular.noop)(result);
}
</pre>
*/
function noop() {}
noop.$inject = [];
/**
* @ngdoc function
* @name angular.identity
* @function
*
* @description
* A function that returns its first argument. This function is useful when writing code in the
* functional style.
*
<pre>
function transformer(transformationFn, value) {
return (transformationFn || angular.identity)(value);
};
</pre>
*/
function identity($) {return $;}
identity.$inject = [];
function valueFn(value) {return function() {return value;};}
/**
* @ngdoc function
* @name angular.isUndefined
* @function
*
* @description
* Determines if a reference is undefined.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is undefined.
*/
function isUndefined(value){return typeof value == 'undefined';}
/**
* @ngdoc function
* @name angular.isDefined
* @function
*
* @description
* Determines if a reference is defined.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is defined.
*/
function isDefined(value){return typeof value != 'undefined';}
/**
* @ngdoc function
* @name angular.isObject
* @function
*
* @description
* Determines if a reference is an `Object`. Unlike `typeof` in JavaScript, `null`s are not
* considered to be objects.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is an `Object` but not `null`.
*/
function isObject(value){return value != null && typeof value == 'object';}
/**
* @ngdoc function
* @name angular.isString
* @function
*
* @description
* Determines if a reference is a `String`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `String`.
*/
function isString(value){return typeof value == 'string';}
/**
* @ngdoc function
* @name angular.isNumber
* @function
*
* @description
* Determines if a reference is a `Number`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Number`.
*/
function isNumber(value){return typeof value == 'number';}
/**
* @ngdoc function
* @name angular.isDate
* @function
*
* @description
* Determines if a value is a date.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Date`.
*/
function isDate(value){
return toString.apply(value) == '[object Date]';
}
/**
* @ngdoc function
* @name angular.isArray
* @function
*
* @description
* Determines if a reference is an `Array`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is an `Array`.
*/
function isArray(value) {
return toString.apply(value) == '[object Array]';
}
/**
* @ngdoc function
* @name angular.isFunction
* @function
*
* @description
* Determines if a reference is a `Function`.
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `Function`.
*/
function isFunction(value){return typeof value == 'function';}
/**
* Determines if a value is a regular expression object.
*
* @private
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a `RegExp`.
*/
function isRegExp(value) {
return toString.apply(value) == '[object RegExp]';
}
/**
* Checks if `obj` is a window object.
*
* @private
* @param {*} obj Object to check
* @returns {boolean} True if `obj` is a window obj.
*/
function isWindow(obj) {
return obj && obj.document && obj.location && obj.alert && obj.setInterval;
}
function isScope(obj) {
return obj && obj.$evalAsync && obj.$watch;
}
function isFile(obj) {
return toString.apply(obj) === '[object File]';
}
function isBoolean(value) {
return typeof value == 'boolean';
}
var trim = (function() {
// native trim is way faster: http://jsperf.com/angular-trim-test
// but IE doesn't have it... :-(
// TODO: we should move this into IE/ES5 polyfill
if (!String.prototype.trim) {
return function(value) {
return isString(value) ? value.replace(/^\s*/, '').replace(/\s*$/, '') : value;
};
}
return function(value) {
return isString(value) ? value.trim() : value;
};
})();
/**
* @ngdoc function
* @name angular.isElement
* @function
*
* @description
* Determines if a reference is a DOM element (or wrapped jQuery element).
*
* @param {*} value Reference to check.
* @returns {boolean} True if `value` is a DOM element (or wrapped jQuery element).
*/
function isElement(node) {
return node &&
(node.nodeName // we are a direct element
|| (node.on && node.find)); // we have an on and find method part of jQuery API
}
/**
* @param str 'key1,key2,...'
* @returns {object} in the form of {key1:true, key2:true, ...}
*/
function makeMap(str){
var obj = {}, items = str.split(","), i;
for ( i = 0; i < items.length; i++ )
obj[ items[i] ] = true;
return obj;
}
if (msie < 9) {
nodeName_ = function(element) {
element = element.nodeName ? element : element[0];
return (element.scopeName && element.scopeName != 'HTML')
? uppercase(element.scopeName + ':' + element.nodeName) : element.nodeName;
};
} else {
nodeName_ = function(element) {
return element.nodeName ? element.nodeName : element[0].nodeName;
};
}
function map(obj, iterator, context) {
var results = [];
forEach(obj, function(value, index, list) {
results.push(iterator.call(context, value, index, list));
});
return results;
}
/**
* @description
* Determines the number of elements in an array, the number of properties an object has, or
* the length of a string.
*
* Note: This function is used to augment the Object type in Angular expressions. See
* {@link angular.Object} for more information about Angular arrays.
*
* @param {Object|Array|string} obj Object, array, or string to inspect.
* @param {boolean} [ownPropsOnly=false] Count only "own" properties in an object
* @returns {number} The size of `obj` or `0` if `obj` is neither an object nor an array.
*/
function size(obj, ownPropsOnly) {
var count = 0, key;
if (isArray(obj) || isString(obj)) {
return obj.length;
} else if (isObject(obj)){
for (key in obj)
if (!ownPropsOnly || obj.hasOwnProperty(key))
count++;
}
return count;
}
function includes(array, obj) {
return indexOf(array, obj) != -1;
}
function indexOf(array, obj) {
if (array.indexOf) return array.indexOf(obj);
for ( var i = 0; i < array.length; i++) {
if (obj === array[i]) return i;
}
return -1;
}
function arrayRemove(array, value) {
var index = indexOf(array, value);
if (index >=0)
array.splice(index, 1);
return value;
}
function isLeafNode (node) {
if (node) {
switch (node.nodeName) {
case "OPTION":
case "PRE":
case "TITLE":
return true;
}
}
return false;
}
/**
* @ngdoc function
* @name angular.copy
* @function
*
* @description
* Creates a deep copy of `source`, which should be an object or an array.
*
* * If no destination is supplied, a copy of the object or array is created.
* * If a destination is provided, all of its elements (for array) or properties (for objects)
* are deleted and then all elements/properties from the source are copied to it.
* * If `source` is not an object or array (inc. `null` and `undefined`), `source` is returned.
* * If `source` is identical to 'destination' an exception will be thrown.
*
* @param {*} source The source that will be used to make a copy.
* Can be any type, including primitives, `null`, and `undefined`.
* @param {(Object|Array)=} destination Destination into which the source is copied. If
* provided, must be of the same type as `source`.
* @returns {*} The copy or updated `destination`, if `destination` was specified.
*
* @example
<doc:example>
<doc:source>
<div ng-controller="Controller">
<form novalidate class="simple-form">
Name: <input type="text" ng-model="user.name" /><br />
E-mail: <input type="email" ng-model="user.email" /><br />
Gender: <input type="radio" ng-model="user.gender" value="male" />male
<input type="radio" ng-model="user.gender" value="female" />female<br />
<button ng-click="reset()">RESET</button>
<button ng-click="update(user)">SAVE</button>
</form>
<pre>form = {{user | json}}</pre>
<pre>master = {{master | json}}</pre>
</div>
<script>
function Controller($scope) {
$scope.master= {};
$scope.update = function(user) {
// Example with 1 argument
$scope.master= angular.copy(user);
};
$scope.reset = function() {
// Example with 2 arguments
angular.copy($scope.master, $scope.user);
};
$scope.reset();
}
</script>
</doc:source>
</doc:example>
*/
function copy(source, destination){
if (isWindow(source) || isScope(source)) {
throw ngMinErr('cpws',
"Can't copy! Making copies of Window or Scope instances is not supported.");
}
if (!destination) {
destination = source;
if (source) {
if (isArray(source)) {
destination = copy(source, []);
} else if (isDate(source)) {
destination = new Date(source.getTime());
} else if (isRegExp(source)) {
destination = new RegExp(source.source);
} else if (isObject(source)) {
destination = copy(source, {});
}
}
} else {
if (source === destination) throw ngMinErr('cpi',
"Can't copy! Source and destination are identical.");
if (isArray(source)) {
destination.length = 0;
for ( var i = 0; i < source.length; i++) {
destination.push(copy(source[i]));
}
} else {
var h = destination.$$hashKey;
forEach(destination, function(value, key){
delete destination[key];
});
for ( var key in source) {
destination[key] = copy(source[key]);
}
setHashKey(destination,h);
}
}
return destination;
}
/**
* Create a shallow copy of an object
*/
function shallowCopy(src, dst) {
dst = dst || {};
for(var key in src) {
// shallowCopy is only ever called by $compile nodeLinkFn, which has control over src
// so we don't need to worry hasOwnProperty here
if (src.hasOwnProperty(key) && key.substr(0, 2) !== '$$') {
dst[key] = src[key];
}
}
return dst;
}
/**
* @ngdoc function
* @name angular.equals
* @function
*
* @description
* Determines if two objects or two values are equivalent. Supports value types, regular
* expressions, arrays and objects.
*
* Two objects or values are considered equivalent if at least one of the following is true:
*
* * Both objects or values pass `===` comparison.
* * Both objects or values are of the same type and all of their properties are equal by
* comparing them with `angular.equals`.
* * Both values are NaN. (In JavaScript, NaN == NaN => false. But we consider two NaN as equal)
* * Both values represent the same regular expression (In JavasScript,
* /abc/ == /abc/ => false. But we consider two regular expressions as equal when their textual
* representation matches).
*
* During a property comparison, properties of `function` type and properties with names
* that begin with `$` are ignored.
*
* Scope and DOMWindow objects are being compared only by identify (`===`).
*
* @param {*} o1 Object or value to compare.
* @param {*} o2 Object or value to compare.
* @returns {boolean} True if arguments are equal.
*/
function equals(o1, o2) {
if (o1 === o2) return true;
if (o1 === null || o2 === null) return false;
if (o1 !== o1 && o2 !== o2) return true; // NaN === NaN
var t1 = typeof o1, t2 = typeof o2, length, key, keySet;
if (t1 == t2) {
if (t1 == 'object') {
if (isArray(o1)) {
if (!isArray(o2)) return false;
if ((length = o1.length) == o2.length) {
for(key=0; key<length; key++) {
if (!equals(o1[key], o2[key])) return false;
}
return true;
}
} else if (isDate(o1)) {
return isDate(o2) && o1.getTime() == o2.getTime();
} else if (isRegExp(o1) && isRegExp(o2)) {
return o1.toString() == o2.toString();
} else {
if (isScope(o1) || isScope(o2) || isWindow(o1) || isWindow(o2) || isArray(o2)) return false;
keySet = {};
for(key in o1) {
if (key.charAt(0) === '$' || isFunction(o1[key])) continue;
if (!equals(o1[key], o2[key])) return false;
keySet[key] = true;
}
for(key in o2) {
if (!keySet.hasOwnProperty(key) &&
key.charAt(0) !== '$' &&
o2[key] !== undefined &&
!isFunction(o2[key])) return false;
}
return true;
}
}
}
return false;
}
function csp() {
return (document.securityPolicy && document.securityPolicy.isActive) ||
(document.querySelector &&
!!(document.querySelector('[ng-csp]') || document.querySelector('[data-ng-csp]')));
}
function concat(array1, array2, index) {
return array1.concat(slice.call(array2, index));
}
function sliceArgs(args, startIndex) {
return slice.call(args, startIndex || 0);
}
/* jshint -W101 */
/**
* @ngdoc function
* @name angular.bind
* @function
*
* @description
* Returns a function which calls function `fn` bound to `self` (`self` becomes the `this` for
* `fn`). You can supply optional `args` that are prebound to the function. This feature is also
* known as [partial application](http://en.wikipedia.org/wiki/Partial_application), as
* distinguished from [function currying](http://en.wikipedia.org/wiki/Currying#Contrast_with_partial_function_application).
*
* @param {Object} self Context which `fn` should be evaluated in.
* @param {function()} fn Function to be bound.
* @param {...*} args Optional arguments to be prebound to the `fn` function call.
* @returns {function()} Function that wraps the `fn` with all the specified bindings.
*/
/* jshint +W101 */
function bind(self, fn) {
var curryArgs = arguments.length > 2 ? sliceArgs(arguments, 2) : [];
if (isFunction(fn) && !(fn instanceof RegExp)) {
return curryArgs.length
? function() {
return arguments.length
? fn.apply(self, curryArgs.concat(slice.call(arguments, 0)))
: fn.apply(self, curryArgs);
}
: function() {
return arguments.length
? fn.apply(self, arguments)
: fn.call(self);
};
} else {
// in IE, native methods are not functions so they cannot be bound (note: they don't need to be)
return fn;
}
}
function toJsonReplacer(key, value) {
var val = value;
if (typeof key === 'string' && key.charAt(0) === '$') {
val = undefined;
} else if (isWindow(value)) {
val = '$WINDOW';
} else if (value && document === value) {
val = '$DOCUMENT';
} else if (isScope(value)) {
val = '$SCOPE';
}
return val;
}
/**
* @ngdoc function
* @name angular.toJson
* @function
*
* @description
* Serializes input into a JSON-formatted string. Properties with leading $ characters will be
* stripped since angular uses this notation internally.
*
* @param {Object|Array|Date|string|number} obj Input to be serialized into JSON.
* @param {boolean=} pretty If set to true, the JSON output will contain newlines and whitespace.
* @returns {string|undefined} JSON-ified string representing `obj`.
*/
function toJson(obj, pretty) {
if (typeof obj === 'undefined') return undefined;
return JSON.stringify(obj, toJsonReplacer, pretty ? ' ' : null);
}
/**
* @ngdoc function
* @name angular.fromJson
* @function
*
* @description
* Deserializes a JSON string.
*
* @param {string} json JSON string to deserialize.
* @returns {Object|Array|Date|string|number} Deserialized thingy.
*/
function fromJson(json) {
return isString(json)
? JSON.parse(json)
: json;
}
function toBoolean(value) {
if (value && value.length !== 0) {
var v = lowercase("" + value);
value = !(v == 'f' || v == '0' || v == 'false' || v == 'no' || v == 'n' || v == '[]');
} else {
value = false;
}
return value;
}
/**
* @returns {string} Returns the string representation of the element.
*/
function startingTag(element) {
element = jqLite(element).clone();
try {
// turns out IE does not let you set .html() on elements which
// are not allowed to have children. So we just ignore it.
element.html('');
} catch(e) {}
// As Per DOM Standards
var TEXT_NODE = 3;
var elemHtml = jqLite('<div>').append(element).html();
try {
return element[0].nodeType === TEXT_NODE ? lowercase(elemHtml) :
elemHtml.
match(/^(<[^>]+>)/)[1].
replace(/^<([\w\-]+)/, function(match, nodeName) { return '<' + lowercase(nodeName); });
} catch(e) {
return lowercase(elemHtml);
}
}
/////////////////////////////////////////////////
/**
* Tries to decode the URI component without throwing an exception.
*
* @private
* @param str value potential URI component to check.
* @returns {boolean} True if `value` can be decoded
* with the decodeURIComponent function.
*/
function tryDecodeURIComponent(value) {
try {
return decodeURIComponent(value);
} catch(e) {
// Ignore any invalid uri component
}
}
/**
* Parses an escaped url query string into key-value pairs.
* @returns Object.<(string|boolean)>
*/
function parseKeyValue(/**string*/keyValue) {
var obj = {}, key_value, key;
forEach((keyValue || "").split('&'), function(keyValue){
if ( keyValue ) {
key_value = keyValue.split('=');
key = tryDecodeURIComponent(key_value[0]);
if ( isDefined(key) ) {
var val = isDefined(key_value[1]) ? tryDecodeURIComponent(key_value[1]) : true;
if (!obj[key]) {
obj[key] = val;
} else if(isArray(obj[key])) {
obj[key].push(val);
} else {
obj[key] = [obj[key],val];
}
}
}
});
return obj;
}
function toKeyValue(obj) {
var parts = [];
forEach(obj, function(value, key) {
if (isArray(value)) {
forEach(value, function(arrayValue) {
parts.push(encodeUriQuery(key, true) +
(arrayValue === true ? '' : '=' + encodeUriQuery(arrayValue, true)));
});
} else {
parts.push(encodeUriQuery(key, true) +
(value === true ? '' : '=' + encodeUriQuery(value, true)));
}
});
return parts.length ? parts.join('&') : '';
}
/**
* We need our custom method because encodeURIComponent is too aggressive and doesn't follow
* http://www.ietf.org/rfc/rfc3986.txt with regards to the character set (pchar) allowed in path
* segments:
* segment = *pchar
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* pct-encoded = "%" HEXDIG HEXDIG
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*/
function encodeUriSegment(val) {
return encodeUriQuery(val, true).
replace(/%26/gi, '&').
replace(/%3D/gi, '=').
replace(/%2B/gi, '+');
}
/**
* This method is intended for encoding *key* or *value* parts of query component. We need a custom
* method because encodeURIComponent is too aggressive and encodes stuff that doesn't have to be
* encoded per http://tools.ietf.org/html/rfc3986:
* query = *( pchar / "/" / "?" )
* pchar = unreserved / pct-encoded / sub-delims / ":" / "@"
* unreserved = ALPHA / DIGIT / "-" / "." / "_" / "~"
* pct-encoded = "%" HEXDIG HEXDIG
* sub-delims = "!" / "$" / "&" / "'" / "(" / ")"
* / "*" / "+" / "," / ";" / "="
*/
function encodeUriQuery(val, pctEncodeSpaces) {
return encodeURIComponent(val).
replace(/%40/gi, '@').
replace(/%3A/gi, ':').
replace(/%24/g, '$').
replace(/%2C/gi, ',').
replace(/%20/g, (pctEncodeSpaces ? '%20' : '+'));
}
/**
* @ngdoc directive
* @name ng.directive:ngApp
*
* @element ANY
* @param {angular.Module} ngApp an optional application
* {@link angular.module module} name to load.
*
* @description
*
* Use this directive to auto-bootstrap an application. Only
* one ngApp directive can be used per HTML document. The directive
* designates the root of the application and is typically placed
* at the root of the page.
*
* The first ngApp found in the document will be auto-bootstrapped. To use multiple applications in
* an HTML document you must manually bootstrap them using {@link angular.bootstrap}.
* Applications cannot be nested.
*
* In the example below if the `ngApp` directive were not placed
* on the `html` element then the document would not be compiled
* and the `{{ 1+2 }}` would not be resolved to `3`.
*
* `ngApp` is the easiest way to bootstrap an application.
*
<doc:example>
<doc:source>
I can add: 1 + 2 = {{ 1+2 }}
</doc:source>
</doc:example>
*
*/
function angularInit(element, bootstrap) {
var elements = [element],
appElement,
module,
names = ['ng:app', 'ng-app', 'x-ng-app', 'data-ng-app'],
NG_APP_CLASS_REGEXP = /\sng[:\-]app(:\s*([\w\d_]+);?)?\s/;
function append(element) {
element && elements.push(element);
}
forEach(names, function(name) {
names[name] = true;
append(document.getElementById(name));
name = name.replace(':', '\\:');
if (element.querySelectorAll) {
forEach(element.querySelectorAll('.' + name), append);
forEach(element.querySelectorAll('.' + name + '\\:'), append);
forEach(element.querySelectorAll('[' + name + ']'), append);
}
});
forEach(elements, function(element) {
if (!appElement) {
var className = ' ' + element.className + ' ';
var match = NG_APP_CLASS_REGEXP.exec(className);
if (match) {
appElement = element;
module = (match[2] || '').replace(/\s+/g, ',');
} else {
forEach(element.attributes, function(attr) {
if (!appElement && names[attr.name]) {
appElement = element;
module = attr.value;
}
});
}
}
});
if (appElement) {
bootstrap(appElement, module ? [module] : []);
}
}
/**
* @ngdoc function
* @name angular.bootstrap
* @description
* Use this function to manually start up angular application.
*
* See: {@link guide/bootstrap Bootstrap}
*
* Note that ngScenario-based end-to-end tests cannot use this function to bootstrap manually.
* They must use {@link api/ng.directive:ngApp ngApp}.
*
* @param {Element} element DOM element which is the root of angular application.
* @param {Array<String|Function|Array>=} modules an array of modules to load into the application.
* Each item in the array should be the name of a predefined module or a (DI annotated)
* function that will be invoked by the injector as a run block.
* See: {@link angular.module modules}
* @returns {AUTO.$injector} Returns the newly created injector for this app.
*/
function bootstrap(element, modules) {
var doBootstrap = function() {
element = jqLite(element);
if (element.injector()) {
var tag = (element[0] === document) ? 'document' : startingTag(element);
throw ngMinErr('btstrpd', "App Already Bootstrapped with this Element '{0}'", tag);
}
modules = modules || [];
modules.unshift(['$provide', function($provide) {
$provide.value('$rootElement', element);
}]);
modules.unshift('ng');
var injector = createInjector(modules);
injector.invoke(['$rootScope', '$rootElement', '$compile', '$injector', '$animate',
function(scope, element, compile, injector, animate) {
scope.$apply(function() {
element.data('$injector', injector);
compile(element)(scope);
});
}]
);
return injector;
};
var NG_DEFER_BOOTSTRAP = /^NG_DEFER_BOOTSTRAP!/;
if (window && !NG_DEFER_BOOTSTRAP.test(window.name)) {
return doBootstrap();
}
window.name = window.name.replace(NG_DEFER_BOOTSTRAP, '');
angular.resumeBootstrap = function(extraModules) {
forEach(extraModules, function(module) {
modules.push(module);
});
doBootstrap();
};
}
var SNAKE_CASE_REGEXP = /[A-Z]/g;
function snake_case(name, separator){
separator = separator || '_';
return name.replace(SNAKE_CASE_REGEXP, function(letter, pos) {
return (pos ? separator : '') + letter.toLowerCase();
});
}
function bindJQuery() {
// bind to jQuery if present;
jQuery = window.jQuery;
// reset to jQuery or default to us.
if (jQuery) {
jqLite = jQuery;
extend(jQuery.fn, {
scope: JQLitePrototype.scope,
isolateScope: JQLitePrototype.isolateScope,
controller: JQLitePrototype.controller,
injector: JQLitePrototype.injector,
inheritedData: JQLitePrototype.inheritedData
});
// Method signature:
// jqLitePatchJQueryRemove(name, dispatchThis, filterElems, getterIfNoArguments)
jqLitePatchJQueryRemove('remove', true, true, false);
jqLitePatchJQueryRemove('empty', false, false, false);
jqLitePatchJQueryRemove('html', false, false, true);
} else {
jqLite = JQLite;
}
angular.element = jqLite;
}
/**
* throw error if the argument is falsy.
*/
function assertArg(arg, name, reason) {
if (!arg) {
throw ngMinErr('areq', "Argument '{0}' is {1}", (name || '?'), (reason || "required"));
}
return arg;
}
function assertArgFn(arg, name, acceptArrayAnnotation) {
if (acceptArrayAnnotation && isArray(arg)) {
arg = arg[arg.length - 1];
}
assertArg(isFunction(arg), name, 'not a function, got ' +
(arg && typeof arg == 'object' ? arg.constructor.name || 'Object' : typeof arg));
return arg;
}
/**
* throw error if the name given is hasOwnProperty
* @param {String} name the name to test
* @param {String} context the context in which the name is used, such as module or directive
*/
function assertNotHasOwnProperty(name, context) {
if (name === 'hasOwnProperty') {
throw ngMinErr('badname', "hasOwnProperty is not a valid {0} name", context);
}
}
/**
* Return the value accessible from the object by path. Any undefined traversals are ignored
* @param {Object} obj starting object
* @param {string} path path to traverse
* @param {boolean=true} bindFnToScope
* @returns value as accessible by path
*/
//TODO(misko): this function needs to be removed
function getter(obj, path, bindFnToScope) {
if (!path) return obj;
var keys = path.split('.');
var key;
var lastInstance = obj;
var len = keys.length;
for (var i = 0; i < len; i++) {
key = keys[i];
if (obj) {
obj = (lastInstance = obj)[key];
}
}
if (!bindFnToScope && isFunction(obj)) {
return bind(lastInstance, obj);
}
return obj;
}
/**
* Return the siblings between `startNode` and `endNode`, inclusive
* @param {Object} object with `startNode` and `endNode` properties
* @returns jQlite object containing the elements
*/
function getBlockElements(block) {
if (block.startNode === block.endNode) {
return jqLite(block.startNode);
}
var element = block.startNode;
var elements = [element];
do {
element = element.nextSibling;
if (!element) break;
elements.push(element);
} while (element !== block.endNode);
return jqLite(elements);
}
/**
* @ngdoc interface
* @name angular.Module
* @description
*
* Interface for configuring angular {@link angular.module modules}.
*/
function setupModuleLoader(window) {
var $injectorMinErr = minErr('$injector');
function ensure(obj, name, factory) {
return obj[name] || (obj[name] = factory());
}
return ensure(ensure(window, 'angular', Object), 'module', function() {
/** @type {Object.<string, angular.Module>} */
var modules = {};
/**
* @ngdoc function
* @name angular.module
* @description
*
* The `angular.module` is a global place for creating, registering and retrieving Angular
* modules.
* All modules (angular core or 3rd party) that should be available to an application must be
* registered using this mechanism.
*
* When passed two or more arguments, a new module is created. If passed only one argument, an
* existing module (the name passed as the first argument to `module`) is retrieved.
*
*
* # Module
*
* A module is a collection of services, directives, filters, and configuration information.
* `angular.module` is used to configure the {@link AUTO.$injector $injector}.
*
* <pre>
* // Create a new module
* var myModule = angular.module('myModule', []);
*
* // register a new service
* myModule.value('appName', 'MyCoolApp');
*
* // configure existing services inside initialization blocks.
* myModule.config(function($locationProvider) {
* // Configure existing providers
* $locationProvider.hashPrefix('!');
* });
* </pre>
*
* Then you can create an injector and load your modules like this:
*
* <pre>
* var injector = angular.injector(['ng', 'MyModule'])
* </pre>
*
* However it's more likely that you'll just use
* {@link ng.directive:ngApp ngApp} or
* {@link angular.bootstrap} to simplify this process for you.
*
* @param {!string} name The name of the module to create or retrieve.
* @param {Array.<string>=} requires If specified then new module is being created. If
* unspecified then the the module is being retrieved for further configuration.
* @param {Function} configFn Optional configuration function for the module. Same as
* {@link angular.Module#methods_config Module#config()}.
* @returns {module} new module with the {@link angular.Module} api.
*/
return function module(name, requires, configFn) {
assertNotHasOwnProperty(name, 'module');
if (requires && modules.hasOwnProperty(name)) {
modules[name] = null;
}
return ensure(modules, name, function() {
if (!requires) {
throw $injectorMinErr('nomod', "Module '{0}' is not available! You either misspelled " +
"the module name or forgot to load it. If registering a module ensure that you " +
"specify the dependencies as the second argument.", name);
}
/** @type {!Array.<Array.<*>>} */
var invokeQueue = [];
/** @type {!Array.<Function>} */
var runBlocks = [];
var config = invokeLater('$injector', 'invoke');
/** @type {angular.Module} */
var moduleInstance = {
// Private state
_invokeQueue: invokeQueue,
_runBlocks: runBlocks,
/**
* @ngdoc property
* @name angular.Module#requires
* @propertyOf angular.Module
* @returns {Array.<string>} List of module names which must be loaded before this module.
* @description
* Holds the list of modules which the injector will load before the current module is
* loaded.
*/
requires: requires,
/**
* @ngdoc property
* @name angular.Module#name
* @propertyOf angular.Module
* @returns {string} Name of the module.
* @description
*/
name: name,
/**
* @ngdoc method
* @name angular.Module#provider
* @methodOf angular.Module
* @param {string} name service name
* @param {Function} providerType Construction function for creating new instance of the
* service.
* @description
* See {@link AUTO.$provide#provider $provide.provider()}.
*/
provider: invokeLater('$provide', 'provider'),
/**
* @ngdoc method
* @name angular.Module#factory
* @methodOf angular.Module
* @param {string} name service name
* @param {Function} providerFunction Function for creating new instance of the service.
* @description
* See {@link AUTO.$provide#factory $provide.factory()}.
*/
factory: invokeLater('$provide', 'factory'),
/**
* @ngdoc method
* @name angular.Module#service
* @methodOf angular.Module
* @param {string} name service name
* @param {Function} constructor A constructor function that will be instantiated.
* @description
* See {@link AUTO.$provide#service $provide.service()}.
*/
service: invokeLater('$provide', 'service'),
/**
* @ngdoc method
* @name angular.Module#value
* @methodOf angular.Module
* @param {string} name service name
* @param {*} object Service instance object.
* @description
* See {@link AUTO.$provide#value $provide.value()}.
*/
value: invokeLater('$provide', 'value'),
/**
* @ngdoc method
* @name angular.Module#constant
* @methodOf angular.Module
* @param {string} name constant name
* @param {*} object Constant value.
* @description
* Because the constant are fixed, they get applied before other provide methods.
* See {@link AUTO.$provide#constant $provide.constant()}.
*/
constant: invokeLater('$provide', 'constant', 'unshift'),
/**
* @ngdoc method
* @name angular.Module#animation
* @methodOf angular.Module
* @param {string} name animation name
* @param {Function} animationFactory Factory function for creating new instance of an
* animation.
* @description
*
* **NOTE**: animations take effect only if the **ngAnimate** module is loaded.
*
*
* Defines an animation hook that can be later used with
* {@link ngAnimate.$animate $animate} service and directives that use this service.
*
* <pre>
* module.animation('.animation-name', function($inject1, $inject2) {
* return {
* eventName : function(element, done) {
* //code to run the animation
* //once complete, then run done()
* return function cancellationFunction(element) {
* //code to cancel the animation
* }
* }
* }
* })
* </pre>
*
* See {@link ngAnimate.$animateProvider#register $animateProvider.register()} and
* {@link ngAnimate ngAnimate module} for more information.
*/
animation: invokeLater('$animateProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#filter
* @methodOf angular.Module
* @param {string} name Filter name.
* @param {Function} filterFactory Factory function for creating new instance of filter.
* @description
* See {@link ng.$filterProvider#register $filterProvider.register()}.
*/
filter: invokeLater('$filterProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#controller
* @methodOf angular.Module
* @param {string|Object} name Controller name, or an object map of controllers where the
* keys are the names and the values are the constructors.
* @param {Function} constructor Controller constructor function.
* @description
* See {@link ng.$controllerProvider#register $controllerProvider.register()}.
*/
controller: invokeLater('$controllerProvider', 'register'),
/**
* @ngdoc method
* @name angular.Module#directive
* @methodOf angular.Module
* @param {string|Object} name Directive name, or an object map of directives where the
* keys are the names and the values are the factories.
* @param {Function} directiveFactory Factory function for creating new instance of
* directives.
* @description
* See {@link ng.$compileProvider#methods_directive $compileProvider.directive()}.
*/
directive: invokeLater('$compileProvider', 'directive'),
/**
* @ngdoc method
* @name angular.Module#config
* @methodOf angular.Module
* @param {Function} configFn Execute this function on module load. Useful for service
* configuration.
* @description
* Use this method to register work which needs to be performed on module loading.
*/
config: config,
/**
* @ngdoc method
* @name angular.Module#run
* @methodOf angular.Module
* @param {Function} initializationFn Execute this function after injector creation.
* Useful for application initialization.
* @description
* Use this method to register work which should be performed when the injector is done
* loading all modules.
*/
run: function(block) {
runBlocks.push(block);
return this;
}
};
if (configFn) {
config(configFn);
}
return moduleInstance;
/**
* @param {string} provider
* @param {string} method
* @param {String=} insertMethod
* @returns {angular.Module}
*/
function invokeLater(provider, method, insertMethod) {
return function() {
invokeQueue[insertMethod || 'push']([provider, method, arguments]);
return moduleInstance;
};
}
});
};
});
}
/* global
angularModule: true,
version: true,
$LocaleProvider,
$CompileProvider,
htmlAnchorDirective,
inputDirective,
inputDirective,
formDirective,
scriptDirective,
selectDirective,
styleDirective,
optionDirective,
ngBindDirective,
ngBindHtmlDirective,
ngBindTemplateDirective,
ngClassDirective,
ngClassEvenDirective,
ngClassOddDirective,
ngCspDirective,
ngCloakDirective,
ngControllerDirective,
ngFormDirective,
ngHideDirective,
ngIfDirective,
ngIncludeDirective,
ngInitDirective,
ngNonBindableDirective,
ngPluralizeDirective,
ngRepeatDirective,
ngShowDirective,
ngStyleDirective,
ngSwitchDirective,
ngSwitchWhenDirective,
ngSwitchDefaultDirective,
ngOptionsDirective,
ngTranscludeDirective,
ngModelDirective,
ngListDirective,
ngChangeDirective,
requiredDirective,
requiredDirective,
ngValueDirective,
ngAttributeAliasDirectives,
ngEventDirectives,
$AnchorScrollProvider,
$AnimateProvider,
$BrowserProvider,
$CacheFactoryProvider,
$ControllerProvider,
$DocumentProvider,
$ExceptionHandlerProvider,
$FilterProvider,
$InterpolateProvider,
$IntervalProvider,
$HttpProvider,
$HttpBackendProvider,
$LocationProvider,
$LogProvider,
$ParseProvider,
$RootScopeProvider,
$QProvider,
$SceProvider,
$SceDelegateProvider,
$SnifferProvider,
$TemplateCacheProvider,
$TimeoutProvider,
$WindowProvider
*/
/**
* @ngdoc property
* @name angular.version
* @description
* An object that contains information about the current AngularJS version. This object has the
* following properties:
*
* - `full` – `{string}` – Full version string, such as "0.9.18".
* - `major` – `{number}` – Major version number, such as "0".
* - `minor` – `{number}` – Minor version number, such as "9".
* - `dot` – `{number}` – Dot version number, such as "18".
* - `codeName` – `{string}` – Code name of the release, such as "jiggling-armfat".
*/
var version = {
full: '1.2.0', // all of these placeholder strings will be replaced by grunt's
major: 1, // package task
minor: "NG_VERSION_MINOR",
dot: 0,
codeName: 'timely-delivery'
};
function publishExternalAPI(angular){
extend(angular, {
'bootstrap': bootstrap,
'copy': copy,
'extend': extend,
'equals': equals,
'element': jqLite,
'forEach': forEach,
'injector': createInjector,
'noop':noop,
'bind':bind,
'toJson': toJson,
'fromJson': fromJson,
'identity':identity,
'isUndefined': isUndefined,
'isDefined': isDefined,
'isString': isString,
'isFunction': isFunction,
'isObject': isObject,
'isNumber': isNumber,
'isElement': isElement,
'isArray': isArray,
'version': version,
'isDate': isDate,
'lowercase': lowercase,
'uppercase': uppercase,
'callbacks': {counter: 0},
'$$minErr': minErr,
'$$csp': csp
});
angularModule = setupModuleLoader(window);
try {
angularModule('ngLocale');
} catch (e) {
angularModule('ngLocale', []).provider('$locale', $LocaleProvider);
}
angularModule('ng', ['ngLocale'], ['$provide',
function ngModule($provide) {
$provide.provider('$compile', $CompileProvider).
directive({
a: htmlAnchorDirective,
input: inputDirective,
textarea: inputDirective,
form: formDirective,
script: scriptDirective,
select: selectDirective,
style: styleDirective,
option: optionDirective,
ngBind: ngBindDirective,
ngBindHtml: ngBindHtmlDirective,
ngBindTemplate: ngBindTemplateDirective,
ngClass: ngClassDirective,
ngClassEven: ngClassEvenDirective,
ngClassOdd: ngClassOddDirective,
ngCloak: ngCloakDirective,
ngController: ngControllerDirective,
ngForm: ngFormDirective,
ngHide: ngHideDirective,
ngIf: ngIfDirective,
ngInclude: ngIncludeDirective,
ngInit: ngInitDirective,
ngNonBindable: ngNonBindableDirective,
ngPluralize: ngPluralizeDirective,
ngRepeat: ngRepeatDirective,
ngShow: ngShowDirective,
ngStyle: ngStyleDirective,
ngSwitch: ngSwitchDirective,
ngSwitchWhen: ngSwitchWhenDirective,
ngSwitchDefault: ngSwitchDefaultDirective,
ngOptions: ngOptionsDirective,
ngTransclude: ngTranscludeDirective,
ngModel: ngModelDirective,
ngList: ngListDirective,
ngChange: ngChangeDirective,
required: requiredDirective,
ngRequired: requiredDirective,
ngValue: ngValueDirective
}).
directive(ngAttributeAliasDirectives).
directive(ngEventDirectives);
$provide.provider({
$anchorScroll: $AnchorScrollProvider,
$animate: $AnimateProvider,
$browser: $BrowserProvider,
$cacheFactory: $CacheFactoryProvider,
$controller: $ControllerProvider,
$document: $DocumentProvider,
$exceptionHandler: $ExceptionHandlerProvider,
$filter: $FilterProvider,
$interpolate: $InterpolateProvider,
$interval: $IntervalProvider,
$http: $HttpProvider,
$httpBackend: $HttpBackendProvider,
$location: $LocationProvider,
$log: $LogProvider,
$parse: $ParseProvider,
$rootScope: $RootScopeProvider,
$q: $QProvider,
$sce: $SceProvider,
$sceDelegate: $SceDelegateProvider,
$sniffer: $SnifferProvider,
$templateCache: $TemplateCacheProvider,
$timeout: $TimeoutProvider,
$window: $WindowProvider
});
}
]);
}
/* global
-JQLitePrototype,
-addEventListenerFn,
-removeEventListenerFn,
-BOOLEAN_ATTR
*/
//////////////////////////////////
//JQLite
//////////////////////////////////
/**
* @ngdoc function
* @name angular.element
* @function
*
* @description
* Wraps a raw DOM element or HTML string as a [jQuery](http://jquery.com) element.
*
* If jQuery is available, `angular.element` is an alias for the
* [jQuery](http://api.jquery.com/jQuery/) function. If jQuery is not available, `angular.element`
* delegates to Angular's built-in subset of jQuery, called "jQuery lite" or "jqLite."
*
* <div class="alert alert-success">jqLite is a tiny, API-compatible subset of jQuery that allows
* Angular to manipulate the DOM in a cross-browser compatible way. **jqLite** implements only the most
* commonly needed functionality with the goal of having a very small footprint.</div>
*
* To use jQuery, simply load it before `DOMContentLoaded` event fired.
*
* <div class="alert">**Note:** all element references in Angular are always wrapped with jQuery or
* jqLite; they are never raw DOM references.</div>
*
* ## Angular's jqLite
* jqLite provides only the following jQuery methods:
*
* - [`addClass()`](http://api.jquery.com/addClass/)
* - [`after()`](http://api.jquery.com/after/)
* - [`append()`](http://api.jquery.com/append/)
* - [`attr()`](http://api.jquery.com/attr/)
* - [`bind()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
* - [`children()`](http://api.jquery.com/children/) - Does not support selectors
* - [`clone()`](http://api.jquery.com/clone/)
* - [`contents()`](http://api.jquery.com/contents/)
* - [`css()`](http://api.jquery.com/css/)
* - [`data()`](http://api.jquery.com/data/)
* - [`eq()`](http://api.jquery.com/eq/)
* - [`find()`](http://api.jquery.com/find/) - Limited to lookups by tag name
* - [`hasClass()`](http://api.jquery.com/hasClass/)
* - [`html()`](http://api.jquery.com/html/)
* - [`next()`](http://api.jquery.com/next/) - Does not support selectors
* - [`on()`](http://api.jquery.com/on/) - Does not support namespaces, selectors or eventData
* - [`off()`](http://api.jquery.com/off/) - Does not support namespaces or selectors
* - [`parent()`](http://api.jquery.com/parent/) - Does not support selectors
* - [`prepend()`](http://api.jquery.com/prepend/)
* - [`prop()`](http://api.jquery.com/prop/)
* - [`ready()`](http://api.jquery.com/ready/)
* - [`remove()`](http://api.jquery.com/remove/)
* - [`removeAttr()`](http://api.jquery.com/removeAttr/)
* - [`removeClass()`](http://api.jquery.com/removeClass/)
* - [`removeData()`](http://api.jquery.com/removeData/)
* - [`replaceWith()`](http://api.jquery.com/replaceWith/)
* - [`text()`](http://api.jquery.com/text/)
* - [`toggleClass()`](http://api.jquery.com/toggleClass/)
* - [`triggerHandler()`](http://api.jquery.com/triggerHandler/) - Passes a dummy event object to handlers.
* - [`unbind()`](http://api.jquery.com/off/) - Does not support namespaces
* - [`val()`](http://api.jquery.com/val/)
* - [`wrap()`](http://api.jquery.com/wrap/)
*
* ## jQuery/jqLite Extras
* Angular also provides the following additional methods and events to both jQuery and jqLite:
*
* ### Events
* - `$destroy` - AngularJS intercepts all jqLite/jQuery's DOM destruction apis and fires this event
* on all DOM nodes being removed. This can be used to clean up any 3rd party bindings to the DOM
* element before it is removed.
*
* ### Methods
* - `controller(name)` - retrieves the controller of the current element or its parent. By default
* retrieves controller associated with the `ngController` directive. If `name` is provided as
* camelCase directive name, then the controller for this directive will be retrieved (e.g.
* `'ngModel'`).
* - `injector()` - retrieves the injector of the current element or its parent.
* - `scope()` - retrieves the {@link api/ng.$rootScope.Scope scope} of the current
* element or its parent.
* - `isolateScope()` - retrieves an isolate {@link api/ng.$rootScope.Scope scope} if one is attached directly to the
* current element. This getter should be used only on elements that contain a directive which starts a new isolate
* scope. Calling `scope()` on this element always returns the original non-isolate scope.
* - `inheritedData()` - same as `data()`, but walks up the DOM until a value is found or the top
* parent element is reached.
*
* @param {string|DOMElement} element HTML string or DOMElement to be wrapped into jQuery.
* @returns {Object} jQuery object.
*/
var jqCache = JQLite.cache = {},
jqName = JQLite.expando = 'ng-' + new Date().getTime(),
jqId = 1,
addEventListenerFn = (window.document.addEventListener
? function(element, type, fn) {element.addEventListener(type, fn, false);}
: function(element, type, fn) {element.attachEvent('on' + type, fn);}),
removeEventListenerFn = (window.document.removeEventListener
? function(element, type, fn) {element.removeEventListener(type, fn, false); }
: function(element, type, fn) {element.detachEvent('on' + type, fn); });
function jqNextId() { return ++jqId; }
var SPECIAL_CHARS_REGEXP = /([\:\-\_]+(.))/g;
var MOZ_HACK_REGEXP = /^moz([A-Z])/;
var jqLiteMinErr = minErr('jqLite');
/**
* Converts snake_case to camelCase.
* Also there is special case for Moz prefix starting with upper case letter.
* @param name Name to normalize
*/
function camelCase(name) {
return name.
replace(SPECIAL_CHARS_REGEXP, function(_, separator, letter, offset) {
return offset ? letter.toUpperCase() : letter;
}).
replace(MOZ_HACK_REGEXP, 'Moz$1');
}
/////////////////////////////////////////////
// jQuery mutation patch
//
// In conjunction with bindJQuery intercepts all jQuery's DOM destruction apis and fires a
// $destroy event on all DOM nodes being removed.
//
/////////////////////////////////////////////
function jqLitePatchJQueryRemove(name, dispatchThis, filterElems, getterIfNoArguments) {
var originalJqFn = jQuery.fn[name];
originalJqFn = originalJqFn.$original || originalJqFn;
removePatch.$original = originalJqFn;
jQuery.fn[name] = removePatch;
function removePatch(param) {
// jshint -W040
var list = filterElems && param ? [this.filter(param)] : [this],
fireEvent = dispatchThis,
set, setIndex, setLength,
element, childIndex, childLength, children;
if (!getterIfNoArguments || param != null) {
while(list.length) {
set = list.shift();
for(setIndex = 0, setLength = set.length; setIndex < setLength; setIndex++) {
element = jqLite(set[setIndex]);
if (fireEvent) {
element.triggerHandler('$destroy');
} else {
fireEvent = !fireEvent;
}
for(childIndex = 0, childLength = (children = element.children()).length;
childIndex < childLength;
childIndex++) {
list.push(jQuery(children[childIndex]));
}
}
}
}
return originalJqFn.apply(this, arguments);
}
}
/////////////////////////////////////////////
function JQLite(element) {
if (element instanceof JQLite) {
return element;
}
if (!(this instanceof JQLite)) {
if (isString(element) && element.charAt(0) != '<') {
throw jqLiteMinErr('nosel', 'Looking up elements via selectors is not supported by jqLite! See: http://docs.angularjs.org/api/angular.element');
}
return new JQLite(element);
}
if (isString(element)) {
var div = document.createElement('div');
// Read about the NoScope elements here:
// http://msdn.microsoft.com/en-us/library/ms533897(VS.85).aspx
div.innerHTML = '<div> </div>' + element; // IE insanity to make NoScope elements work!
div.removeChild(div.firstChild); // remove the superfluous div
jqLiteAddNodes(this, div.childNodes);
var fragment = jqLite(document.createDocumentFragment());
fragment.append(this); // detach the elements from the temporary DOM div.
} else {
jqLiteAddNodes(this, element);
}
}
function jqLiteClone(element) {
return element.cloneNode(true);
}
function jqLiteDealoc(element){
jqLiteRemoveData(element);
for ( var i = 0, children = element.childNodes || []; i < children.length; i++) {
jqLiteDealoc(children[i]);
}
}
function jqLiteOff(element, type, fn, unsupported) {
if (isDefined(unsupported)) throw jqLiteMinErr('offargs', 'jqLite#off() does not support the `selector` argument');
var events = jqLiteExpandoStore(element, 'events'),
handle = jqLiteExpandoStore(element, 'handle');
if (!handle) return; //no listeners registered
if (isUndefined(type)) {
forEach(events, function(eventHandler, type) {
removeEventListenerFn(element, type, eventHandler);
delete events[type];
});
} else {
forEach(type.split(' '), function(type) {
if (isUndefined(fn)) {
removeEventListenerFn(element, type, events[type]);
delete events[type];
} else {
arrayRemove(events[type] || [], fn);
}
});
}
}
function jqLiteRemoveData(element, name) {
var expandoId = element[jqName],
expandoStore = jqCache[expandoId];
if (expandoStore) {
if (name) {
delete jqCache[expandoId].data[name];
return;
}
if (expandoStore.handle) {
expandoStore.events.$destroy && expandoStore.handle({}, '$destroy');
jqLiteOff(element);
}
delete jqCache[expandoId];
element[jqName] = undefined; // ie does not allow deletion of attributes on elements.
}
}
function jqLiteExpandoStore(element, key, value) {
var expandoId = element[jqName],
expandoStore = jqCache[expandoId || -1];
if (isDefined(value)) {
if (!expandoStore) {
element[jqName] = expandoId = jqNextId();
expandoStore = jqCache[expandoId] = {};
}
expandoStore[key] = value;
} else {
return expandoStore && expandoStore[key];
}
}
function jqLiteData(element, key, value) {
var data = jqLiteExpandoStore(element, 'data'),
isSetter = isDefined(value),
keyDefined = !isSetter && isDefined(key),
isSimpleGetter = keyDefined && !isObject(key);
if (!data && !isSimpleGetter) {
jqLiteExpandoStore(element, 'data', data = {});
}
if (isSetter) {
data[key] = value;
} else {
if (keyDefined) {
if (isSimpleGetter) {
// don't create data in this case.
return data && data[key];
} else {
extend(data, key);
}
} else {
return data;
}
}
}
function jqLiteHasClass(element, selector) {
if (!element.getAttribute) return false;
return ((" " + (element.getAttribute('class') || '') + " ").replace(/[\n\t]/g, " ").
indexOf( " " + selector + " " ) > -1);
}
function jqLiteRemoveClass(element, cssClasses) {
if (cssClasses && element.setAttribute) {
forEach(cssClasses.split(' '), function(cssClass) {
element.setAttribute('class', trim(
(" " + (element.getAttribute('class') || '') + " ")
.replace(/[\n\t]/g, " ")
.replace(" " + trim(cssClass) + " ", " "))
);
});
}
}
function jqLiteAddClass(element, cssClasses) {
if (cssClasses && element.setAttribute) {
var existingClasses = (' ' + (element.getAttribute('class') || '') + ' ')
.replace(/[\n\t]/g, " ");
forEach(cssClasses.split(' '), function(cssClass) {
cssClass = trim(cssClass);
if (existingClasses.indexOf(' ' + cssClass + ' ') === -1) {
existingClasses += cssClass + ' ';
}
});
element.setAttribute('class', trim(existingClasses));
}
}
function jqLiteAddNodes(root, elements) {
if (elements) {
elements = (!elements.nodeName && isDefined(elements.length) && !isWindow(elements))
? elements
: [ elements ];
for(var i=0; i < elements.length; i++) {
root.push(elements[i]);
}
}
}
function jqLiteController(element, name) {
return jqLiteInheritedData(element, '$' + (name || 'ngController' ) + 'Controller');
}
function jqLiteInheritedData(element, name, value) {
element = jqLite(element);
// if element is the document object work with the html element instead
// this makes $(document).scope() possible
if(element[0].nodeType == 9) {
element = element.find('html');
}
var names = isArray(name) ? name : [name];
while (element.length) {
for (var i = 0, ii = names.length; i < ii; i++) {
if ((value = element.data(names[i])) !== undefined) return value;
}
element = element.parent();
}
}
//////////////////////////////////////////
// Functions which are declared directly.
//////////////////////////////////////////
var JQLitePrototype = JQLite.prototype = {
ready: function(fn) {
var fired = false;
function trigger() {
if (fired) return;
fired = true;
fn();
}
// check if document already is loaded
if (document.readyState === 'complete'){
setTimeout(trigger);
} else {
this.on('DOMContentLoaded', trigger); // works for modern browsers and IE9
// we can not use jqLite since we are not done loading and jQuery could be loaded later.
// jshint -W064
JQLite(window).on('load', trigger); // fallback to window.onload for others
// jshint +W064
}
},
toString: function() {
var value = [];
forEach(this, function(e){ value.push('' + e);});
return '[' + value.join(', ') + ']';
},
eq: function(index) {
return (index >= 0) ? jqLite(this[index]) : jqLite(this[this.length + index]);
},
length: 0,
push: push,
sort: [].sort,
splice: [].splice
};
//////////////////////////////////////////
// Functions iterating getter/setters.
// these functions return self on setter and
// value on get.
//////////////////////////////////////////
var BOOLEAN_ATTR = {};
forEach('multiple,selected,checked,disabled,readOnly,required,open'.split(','), function(value) {
BOOLEAN_ATTR[lowercase(value)] = value;
});
var BOOLEAN_ELEMENTS = {};
forEach('input,select,option,textarea,button,form,details'.split(','), function(value) {
BOOLEAN_ELEMENTS[uppercase(value)] = true;
});
function getBooleanAttrName(element, name) {
// check dom last since we will most likely fail on name
var booleanAttr = BOOLEAN_ATTR[name.toLowerCase()];
// booleanAttr is here twice to minimize DOM access
return booleanAttr && BOOLEAN_ELEMENTS[element.nodeName] && booleanAttr;
}
forEach({
data: jqLiteData,
inheritedData: jqLiteInheritedData,
scope: function(element) {
// Can't use jqLiteData here directly so we stay compatible with jQuery!
return jqLite(element).data('$scope') || jqLiteInheritedData(element.parentNode || element, ['$isolateScope', '$scope']);
},
isolateScope: function(element) {
// Can't use jqLiteData here directly so we stay compatible with jQuery!
return jqLite(element).data('$isolateScope') || jqLite(element).data('$isolateScopeNoTemplate');
},
controller: jqLiteController ,
injector: function(element) {
return jqLiteInheritedData(element, '$injector');
},
removeAttr: function(element,name) {
element.removeAttribute(name);
},
hasClass: jqLiteHasClass,
css: function(element, name, value) {
name = camelCase(name);
if (isDefined(value)) {
element.style[name] = value;
} else {
var val;
if (msie <= 8) {
// this is some IE specific weirdness that jQuery 1.6.4 does not sure why
val = element.currentStyle && element.currentStyle[name];
if (val === '') val = 'auto';
}
val = val || element.style[name];
if (msie <= 8) {
// jquery weirdness :-/
val = (val === '') ? undefined : val;
}
return val;
}
},
attr: function(element, name, value){
var lowercasedName = lowercase(name);
if (BOOLEAN_ATTR[lowercasedName]) {
if (isDefined(value)) {
if (!!value) {
element[name] = true;
element.setAttribute(name, lowercasedName);
} else {
element[name] = false;
element.removeAttribute(lowercasedName);
}
} else {
return (element[name] ||
(element.attributes.getNamedItem(name)|| noop).specified)
? lowercasedName
: undefined;
}
} else if (isDefined(value)) {
element.setAttribute(name, value);
} else if (element.getAttribute) {
// the extra argument "2" is to get the right thing for a.href in IE, see jQuery code
// some elements (e.g. Document) don't have get attribute, so return undefined
var ret = element.getAttribute(name, 2);
// normalize non-existing attributes to undefined (as jQuery)
return ret === null ? undefined : ret;
}
},
prop: function(element, name, value) {
if (isDefined(value)) {
element[name] = value;
} else {
return element[name];
}
},
text: (function() {
var NODE_TYPE_TEXT_PROPERTY = [];
if (msie < 9) {
NODE_TYPE_TEXT_PROPERTY[1] = 'innerText'; /** Element **/
NODE_TYPE_TEXT_PROPERTY[3] = 'nodeValue'; /** Text **/
} else {
NODE_TYPE_TEXT_PROPERTY[1] = /** Element **/
NODE_TYPE_TEXT_PROPERTY[3] = 'textContent'; /** Text **/
}
getText.$dv = '';
return getText;
function getText(element, value) {
var textProp = NODE_TYPE_TEXT_PROPERTY[element.nodeType];
if (isUndefined(value)) {
return textProp ? element[textProp] : '';
}
element[textProp] = value;
}
})(),
val: function(element, value) {
if (isUndefined(value)) {
if (nodeName_(element) === 'SELECT' && element.multiple) {
var result = [];
forEach(element.options, function (option) {
if (option.selected) {
result.push(option.value || option.text);
}
});
return result.length === 0 ? null : result;
}
return element.value;
}
element.value = value;
},
html: function(element, value) {
if (isUndefined(value)) {
return element.innerHTML;
}
for (var i = 0, childNodes = element.childNodes; i < childNodes.length; i++) {
jqLiteDealoc(childNodes[i]);
}
element.innerHTML = value;
}
}, function(fn, name){
/**
* Properties: writes return selection, reads return first value
*/
JQLite.prototype[name] = function(arg1, arg2) {
var i, key;
// jqLiteHasClass has only two arguments, but is a getter-only fn, so we need to special-case it
// in a way that survives minification.
if (((fn.length == 2 && (fn !== jqLiteHasClass && fn !== jqLiteController)) ? arg1 : arg2) === undefined) {
if (isObject(arg1)) {
// we are a write, but the object properties are the key/values
for(i=0; i < this.length; i++) {
if (fn === jqLiteData) {
// data() takes the whole object in jQuery
fn(this[i], arg1);
} else {
for (key in arg1) {
fn(this[i], key, arg1[key]);
}
}
}
// return self for chaining
return this;
} else {
// we are a read, so read the first child.
var value = fn.$dv;
// Only if we have $dv do we iterate over all, otherwise it is just the first element.
var jj = (value === undefined) ? Math.min(this.length, 1) : this.length;
for (var j = 0; j < jj; j++) {
var nodeValue = fn(this[j], arg1, arg2);
value = value ? value + nodeValue : nodeValue;
}
return value;
}
} else {
// we are a write, so apply to all children
for(i=0; i < this.length; i++) {
fn(this[i], arg1, arg2);
}
// return self for chaining
return this;
}
};
});
function createEventHandler(element, events) {
var eventHandler = function (event, type) {
if (!event.preventDefault) {
event.preventDefault = function() {
event.returnValue = false; //ie
};
}
if (!event.stopPropagation) {
event.stopPropagation = function() {
event.cancelBubble = true; //ie
};
}
if (!event.target) {
event.target = event.srcElement || document;
}
if (isUndefined(event.defaultPrevented)) {
var prevent = event.preventDefault;
event.preventDefault = function() {
event.defaultPrevented = true;
prevent.call(event);
};
event.defaultPrevented = false;
}
event.isDefaultPrevented = function() {
return event.defaultPrevented || event.returnValue === false;
};
forEach(events[type || event.type], function(fn) {
fn.call(element, event);
});
// Remove monkey-patched methods (IE),
// as they would cause memory leaks in IE8.
if (msie <= 8) {
// IE7/8 does not allow to delete property on native object
event.preventDefault = null;
event.stopPropagation = null;
event.isDefaultPrevented = null;
} else {
// It shouldn't affect normal browsers (native methods are defined on prototype).
delete event.preventDefault;
delete event.stopPropagation;
delete event.isDefaultPrevented;
}
};
eventHandler.elem = element;
return eventHandler;
}
//////////////////////////////////////////
// Functions iterating traversal.
// These functions chain results into a single
// selector.
//////////////////////////////////////////
forEach({
removeData: jqLiteRemoveData,
dealoc: jqLiteDealoc,
on: function onFn(element, type, fn, unsupported){
if (isDefined(unsupported)) throw jqLiteMinErr('onargs', 'jqLite#on() does not support the `selector` or `eventData` parameters');
var events = jqLiteExpandoStore(element, 'events'),
handle = jqLiteExpandoStore(element, 'handle');
if (!events) jqLiteExpandoStore(element, 'events', events = {});
if (!handle) jqLiteExpandoStore(element, 'handle', handle = createEventHandler(element, events));
forEach(type.split(' '), function(type){
var eventFns = events[type];
if (!eventFns) {
if (type == 'mouseenter' || type == 'mouseleave') {
var contains = document.body.contains || document.body.compareDocumentPosition ?
function( a, b ) {
// jshint bitwise: false
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;
};
events[type] = [];
// Refer to jQuery's implementation of mouseenter & mouseleave
// Read about mouseenter and mouseleave:
// http://www.quirksmode.org/js/events_mouse.html#link8
var eventmap = { mouseleave : "mouseout", mouseenter : "mouseover"};
onFn(element, eventmap[type], function(event) {
var target = this, related = event.relatedTarget;
// 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 && !contains(target, related)) ){
handle(event, type);
}
});
} else {
addEventListenerFn(element, type, handle);
events[type] = [];
}
eventFns = events[type];
}
eventFns.push(fn);
});
},
off: jqLiteOff,
replaceWith: function(element, replaceNode) {
var index, parent = element.parentNode;
jqLiteDealoc(element);
forEach(new JQLite(replaceNode), function(node){
if (index) {
parent.insertBefore(node, index.nextSibling);
} else {
parent.replaceChild(node, element);
}
index = node;
});
},
children: function(element) {
var children = [];
forEach(element.childNodes, function(element){
if (element.nodeType === 1)
children.push(element);
});
return children;
},
contents: function(element) {
return element.childNodes || [];
},
append: function(element, node) {
forEach(new JQLite(node), function(child){
if (element.nodeType === 1 || element.nodeType === 11) {
element.appendChild(child);
}
});
},
prepend: function(element, node) {
if (element.nodeType === 1) {
var index = element.firstChild;
forEach(new JQLite(node), function(child){
element.insertBefore(child, index);
});
}
},
wrap: function(element, wrapNode) {
wrapNode = jqLite(wrapNode)[0];
var parent = element.parentNode;
if (parent) {
parent.replaceChild(wrapNode, element);
}
wrapNode.appendChild(element);
},
remove: function(element) {
jqLiteDealoc(element);
var parent = element.parentNode;
if (parent) parent.removeChild(element);
},
after: function(element, newElement) {
var index = element, parent = element.parentNode;
forEach(new JQLite(newElement), function(node){
parent.insertBefore(node, index.nextSibling);
index = node;
});
},
addClass: jqLiteAddClass,
removeClass: jqLiteRemoveClass,
toggleClass: function(element, selector, condition) {
if (isUndefined(condition)) {
condition = !jqLiteHasClass(element, selector);
}
(condition ? jqLiteAddClass : jqLiteRemoveClass)(element, selector);
},
parent: function(element) {
var parent = element.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
next: function(element) {
if (element.nextElementSibling) {
return element.nextElementSibling;
}
// IE8 doesn't have nextElementSibling
var elm = element.nextSibling;
while (elm != null && elm.nodeType !== 1) {
elm = elm.nextSibling;
}
return elm;
},
find: function(element, selector) {
return element.getElementsByTagName(selector);
},
clone: jqLiteClone,
triggerHandler: function(element, eventName, eventData) {
var eventFns = (jqLiteExpandoStore(element, 'events') || {})[eventName];
eventData = eventData || [];
var event = [{
preventDefault: noop,
stopPropagation: noop
}];
forEach(eventFns, function(fn) {
fn.apply(element, event.concat(eventData));
});
}
}, function(fn, name){
/**
* chaining functions
*/
JQLite.prototype[name] = function(arg1, arg2, arg3) {
var value;
for(var i=0; i < this.length; i++) {
if (isUndefined(value)) {
value = fn(this[i], arg1, arg2, arg3);
if (isDefined(value)) {
// any function which returns a value needs to be wrapped
value = jqLite(value);
}
} else {
jqLiteAddNodes(value, fn(this[i], arg1, arg2, arg3));
}
}
return isDefined(value) ? value : this;
};
// bind legacy bind/unbind to on/off
JQLite.prototype.bind = JQLite.prototype.on;
JQLite.prototype.unbind = JQLite.prototype.off;
});
/**
* Computes a hash of an 'obj'.
* Hash of a:
* string is string
* number is number as string
* object is either result of calling $$hashKey function on the object or uniquely generated id,
* that is also assigned to the $$hashKey property of the object.
*
* @param obj
* @returns {string} hash string such that the same input will have the same hash string.
* The resulting string key is in 'type:hashKey' format.
*/
function hashKey(obj) {
var objType = typeof obj,
key;
if (objType == 'object' && obj !== null) {
if (typeof (key = obj.$$hashKey) == 'function') {
// must invoke on object to keep the right this
key = obj.$$hashKey();
} else if (key === undefined) {
key = obj.$$hashKey = nextUid();
}
} else {
key = obj;
}
return objType + ':' + key;
}
/**
* HashMap which can use objects as keys
*/
function HashMap(array){
forEach(array, this.put, this);
}
HashMap.prototype = {
/**
* Store key value pair
* @param key key to store can be any type
* @param value value to store can be any type
*/
put: function(key, value) {
this[hashKey(key)] = value;
},
/**
* @param key
* @returns the value for the key
*/
get: function(key) {
return this[hashKey(key)];
},
/**
* Remove the key/value pair
* @param key
*/
remove: function(key) {
var value = this[key = hashKey(key)];
delete this[key];
return value;
}
};
/**
* @ngdoc function
* @name angular.injector
* @function
*
* @description
* Creates an injector function that can be used for retrieving services as well as for
* dependency injection (see {@link guide/di dependency injection}).
*
* @param {Array.<string|Function>} modules A list of module functions or their aliases. See
* {@link angular.module}. The `ng` module must be explicitly added.
* @returns {function()} Injector function. See {@link AUTO.$injector $injector}.
*
* @example
* Typical usage
* <pre>
* // create an injector
* var $injector = angular.injector(['ng']);
*
* // use the injector to kick off your application
* // use the type inference to auto inject arguments, or use implicit injection
* $injector.invoke(function($rootScope, $compile, $document){
* $compile($document)($rootScope);
* $rootScope.$digest();
* });
* </pre>
*/
/**
* @ngdoc overview
* @name AUTO
* @description
*
* Implicit module which gets automatically added to each {@link AUTO.$injector $injector}.
*/
var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m;
var FN_ARG_SPLIT = /,/;
var FN_ARG = /^\s*(_?)(\S+?)\1\s*$/;
var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg;
var $injectorMinErr = minErr('$injector');
function annotate(fn) {
var $inject,
fnText,
argDecl,
last;
if (typeof fn == 'function') {
if (!($inject = fn.$inject)) {
$inject = [];
if (fn.length) {
fnText = fn.toString().replace(STRIP_COMMENTS, '');
argDecl = fnText.match(FN_ARGS);
forEach(argDecl[1].split(FN_ARG_SPLIT), function(arg){
arg.replace(FN_ARG, function(all, underscore, name){
$inject.push(name);
});
});
}
fn.$inject = $inject;
}
} else if (isArray(fn)) {
last = fn.length - 1;
assertArgFn(fn[last], 'fn');
$inject = fn.slice(0, last);
} else {
assertArgFn(fn, 'fn', true);
}
return $inject;
}
///////////////////////////////////////
/**
* @ngdoc object
* @name AUTO.$injector
* @function
*
* @description
*
* `$injector` is used to retrieve object instances as defined by
* {@link AUTO.$provide provider}, instantiate types, invoke methods,
* and load modules.
*
* The following always holds true:
*
* <pre>
* var $injector = angular.injector();
* expect($injector.get('$injector')).toBe($injector);
* expect($injector.invoke(function($injector){
* return $injector;
* }).toBe($injector);
* </pre>
*
* # Injection Function Annotation
*
* JavaScript does not have annotations, and annotations are needed for dependency injection. The
* following are all valid ways of annotating function with injection arguments and are equivalent.
*
* <pre>
* // inferred (only works if code not minified/obfuscated)
* $injector.invoke(function(serviceA){});
*
* // annotated
* function explicit(serviceA) {};
* explicit.$inject = ['serviceA'];
* $injector.invoke(explicit);
*
* // inline
* $injector.invoke(['serviceA', function(serviceA){}]);
* </pre>
*
* ## Inference
*
* In JavaScript calling `toString()` on a function returns the function definition. The definition
* can then be parsed and the function arguments can be extracted. *NOTE:* This does not work with
* minification, and obfuscation tools since these tools change the argument names.
*
* ## `$inject` Annotation
* By adding a `$inject` property onto a function the injection parameters can be specified.
*
* ## Inline
* As an array of injection names, where the last item in the array is the function to call.
*/
/**
* @ngdoc method
* @name AUTO.$injector#get
* @methodOf AUTO.$injector
*
* @description
* Return an instance of the service.
*
* @param {string} name The name of the instance to retrieve.
* @return {*} The instance.
*/
/**
* @ngdoc method
* @name AUTO.$injector#invoke
* @methodOf AUTO.$injector
*
* @description
* Invoke the method and supply the method arguments from the `$injector`.
*
* @param {!function} fn The function to invoke. Function parameters are injected according to the
* {@link guide/di $inject Annotation} rules.
* @param {Object=} self The `this` for the invoked method.
* @param {Object=} locals Optional object. If preset then any argument names are read from this
* object first, before the `$injector` is consulted.
* @returns {*} the value returned by the invoked `fn` function.
*/
/**
* @ngdoc method
* @name AUTO.$injector#has
* @methodOf AUTO.$injector
*
* @description
* Allows the user to query if the particular service exist.
*
* @param {string} Name of the service to query.
* @returns {boolean} returns true if injector has given service.
*/
/**
* @ngdoc method
* @name AUTO.$injector#instantiate
* @methodOf AUTO.$injector
* @description
* Create a new instance of JS type. The method takes a constructor function invokes the new
* operator and supplies all of the arguments to the constructor function as specified by the
* constructor annotation.
*
* @param {function} Type Annotated constructor function.
* @param {Object=} locals Optional object. If preset then any argument names are read from this
* object first, before the `$injector` is consulted.
* @returns {Object} new instance of `Type`.
*/
/**
* @ngdoc method
* @name AUTO.$injector#annotate
* @methodOf AUTO.$injector
*
* @description
* Returns an array of service names which the function is requesting for injection. This API is
* used by the injector to determine which services need to be injected into the function when the
* function is invoked. There are three ways in which the function can be annotated with the needed
* dependencies.
*
* # Argument names
*
* The simplest form is to extract the dependencies from the arguments of the function. This is done
* by converting the function into a string using `toString()` method and extracting the argument
* names.
* <pre>
* // Given
* function MyController($scope, $route) {
* // ...
* }
*
* // Then
* expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
* </pre>
*
* This method does not work with code minification / obfuscation. For this reason the following
* annotation strategies are supported.
*
* # The `$inject` property
*
* If a function has an `$inject` property and its value is an array of strings, then the strings
* represent names of services to be injected into the function.
* <pre>
* // Given
* var MyController = function(obfuscatedScope, obfuscatedRoute) {
* // ...
* }
* // Define function dependencies
* MyController.$inject = ['$scope', '$route'];
*
* // Then
* expect(injector.annotate(MyController)).toEqual(['$scope', '$route']);
* </pre>
*
* # The array notation
*
* It is often desirable to inline Injected functions and that's when setting the `$inject` property
* is very inconvenient. In these situations using the array notation to specify the dependencies in
* a way that survives minification is a better choice:
*
* <pre>
* // We wish to write this (not minification / obfuscation safe)
* injector.invoke(function($compile, $rootScope) {
* // ...
* });
*
* // We are forced to write break inlining
* var tmpFn = function(obfuscatedCompile, obfuscatedRootScope) {
* // ...
* };
* tmpFn.$inject = ['$compile', '$rootScope'];
* injector.invoke(tmpFn);
*
* // To better support inline function the inline annotation is supported
* injector.invoke(['$compile', '$rootScope', function(obfCompile, obfRootScope) {
* // ...
* }]);
*
* // Therefore
* expect(injector.annotate(
* ['$compile', '$rootScope', function(obfus_$compile, obfus_$rootScope) {}])
* ).toEqual(['$compile', '$rootScope']);
* </pre>
*
* @param {function|Array.<string|Function>} fn Function for which dependent service names need to
* be retrieved as described above.
*
* @returns {Array.<string>} The names of the services which the function requires.
*/
/**
* @ngdoc object
* @name AUTO.$provide
*
* @description
*
* The {@link AUTO.$provide $provide} service has a number of methods for registering components
* with the {@link AUTO.$injector $injector}. Many of these functions are also exposed on
* {@link angular.Module}.
*
* An Angular **service** is a singleton object created by a **service factory**. These **service
* factories** are functions which, in turn, are created by a **service provider**.
* The **service providers** are constructor functions. When instantiated they must contain a
* property called `$get`, which holds the **service factory** function.
*
* When you request a service, the {@link AUTO.$injector $injector} is responsible for finding the
* correct **service provider**, instantiating it and then calling its `$get` **service factory**
* function to get the instance of the **service**.
*
* Often services have no configuration options and there is no need to add methods to the service
* provider. The provider will be no more than a constructor function with a `$get` property. For
* these cases the {@link AUTO.$provide $provide} service has additional helper methods to register
* services without specifying a provider.
*
* * {@link AUTO.$provide#methods_provider provider(provider)} - registers a **service provider** with the
* {@link AUTO.$injector $injector}
* * {@link AUTO.$provide#methods_constant constant(obj)} - registers a value/object that can be accessed by
* providers and services.
* * {@link AUTO.$provide#methods_value value(obj)} - registers a value/object that can only be accessed by
* services, not providers.
* * {@link AUTO.$provide#methods_factory factory(fn)} - registers a service **factory function**, `fn`,
* that will be wrapped in a **service provider** object, whose `$get` property will contain the
* given factory function.
* * {@link AUTO.$provide#methods_service service(class)} - registers a **constructor function**, `class` that
* that will be wrapped in a **service provider** object, whose `$get` property will instantiate
* a new object using the given constructor function.
*
* See the individual methods for more information and examples.
*/
/**
* @ngdoc method
* @name AUTO.$provide#provider
* @methodOf AUTO.$provide
* @description
*
* Register a **provider function** with the {@link AUTO.$injector $injector}. Provider functions
* are constructor functions, whose instances are responsible for "providing" a factory for a
* service.
*
* Service provider names start with the name of the service they provide followed by `Provider`.
* For example, the {@link ng.$log $log} service has a provider called
* {@link ng.$logProvider $logProvider}.
*
* Service provider objects can have additional methods which allow configuration of the provider
* and its service. Importantly, you can configure what kind of service is created by the `$get`
* method, or how that service will act. For example, the {@link ng.$logProvider $logProvider} has a
* method {@link ng.$logProvider#debugEnabled debugEnabled}
* which lets you specify whether the {@link ng.$log $log} service will log debug messages to the
* console or not.
*
* @param {string} name The name of the instance. NOTE: the provider will be available under `name +
'Provider'` key.
* @param {(Object|function())} provider If the provider is:
*
* - `Object`: then it should have a `$get` method. The `$get` method will be invoked using
* {@link AUTO.$injector#invoke $injector.invoke()} when an instance needs to be
* created.
* - `Constructor`: a new instance of the provider will be created using
* {@link AUTO.$injector#instantiate $injector.instantiate()}, then treated as
* `object`.
*
* @returns {Object} registered provider instance
* @example
*
* The following example shows how to create a simple event tracking service and register it using
* {@link AUTO.$provide#methods_provider $provide.provider()}.
*
* <pre>
* // Define the eventTracker provider
* function EventTrackerProvider() {
* var trackingUrl = '/track';
*
* // A provider method for configuring where the tracked events should been saved
* this.setTrackingUrl = function(url) {
* trackingUrl = url;
* };
*
* // The service factory function
* this.$get = ['$http', function($http) {
* var trackedEvents = {};
* return {
* // Call this to track an event
* event: function(event) {
* var count = trackedEvents[event] || 0;
* count += 1;
* trackedEvents[event] = count;
* return count;
* },
* // Call this to save the tracked events to the trackingUrl
* save: function() {
* $http.post(trackingUrl, trackedEvents);
* }
* };
* }];
* }
*
* describe('eventTracker', function() {
* var postSpy;
*
* beforeEach(module(function($provide) {
* // Register the eventTracker provider
* $provide.provider('eventTracker', EventTrackerProvider);
* }));
*
* beforeEach(module(function(eventTrackerProvider) {
* // Configure eventTracker provider
* eventTrackerProvider.setTrackingUrl('/custom-track');
* }));
*
* it('tracks events', inject(function(eventTracker) {
* expect(eventTracker.event('login')).toEqual(1);
* expect(eventTracker.event('login')).toEqual(2);
* }));
*
* it('saves to the tracking url', inject(function(eventTracker, $http) {
* postSpy = spyOn($http, 'post');
* eventTracker.event('login');
* eventTracker.save();
* expect(postSpy).toHaveBeenCalled();
* expect(postSpy.mostRecentCall.args[0]).not.toEqual('/track');
* expect(postSpy.mostRecentCall.args[0]).toEqual('/custom-track');
* expect(postSpy.mostRecentCall.args[1]).toEqual({ 'login': 1 });
* }));
* });
* </pre>
*/
/**
* @ngdoc method
* @name AUTO.$provide#factory
* @methodOf AUTO.$provide
* @description
*
* Register a **service factory**, which will be called to return the service instance.
* This is short for registering a service where its provider consists of only a `$get` property,
* which is the given service factory function.
* You should use {@link AUTO.$provide#factory $provide.factory(getFn)} if you do not need to
* configure your service in a provider.
*
* @param {string} name The name of the instance.
* @param {function()} $getFn The $getFn for the instance creation. Internally this is a short hand
* for `$provide.provider(name, {$get: $getFn})`.
* @returns {Object} registered provider instance
*
* @example
* Here is an example of registering a service
* <pre>
* $provide.factory('ping', ['$http', function($http) {
* return function ping() {
* return $http.send('/ping');
* };
* }]);
* </pre>
* You would then inject and use this service like this:
* <pre>
* someModule.controller('Ctrl', ['ping', function(ping) {
* ping();
* }]);
* </pre>
*/
/**
* @ngdoc method
* @name AUTO.$provide#service
* @methodOf AUTO.$provide
* @description
*
* Register a **service constructor**, which will be invoked with `new` to create the service
* instance.
* This is short for registering a service where its provider's `$get` property is the service
* constructor function that will be used to instantiate the service instance.
*
* You should use {@link AUTO.$provide#methods_service $provide.service(class)} if you define your service
* as a type/class. This is common when using {@link http://coffeescript.org CoffeeScript}.
*
* @param {string} name The name of the instance.
* @param {Function} constructor A class (constructor function) that will be instantiated.
* @returns {Object} registered provider instance
*
* @example
* Here is an example of registering a service using
* {@link AUTO.$provide#methods_service $provide.service(class)} that is defined as a CoffeeScript class.
* <pre>
* class Ping
* constructor: (@$http)->
* send: ()=>
* @$http.get('/ping')
*
* $provide.service('ping', ['$http', Ping])
* </pre>
* You would then inject and use this service like this:
* <pre>
* someModule.controller 'Ctrl', ['ping', (ping)->
* ping.send()
* ]
* </pre>
*/
/**
* @ngdoc method
* @name AUTO.$provide#value
* @methodOf AUTO.$provide
* @description
*
* Register a **value service** with the {@link AUTO.$injector $injector}, such as a string, a
* number, an array, an object or a function. This is short for registering a service where its
* provider's `$get` property is a factory function that takes no arguments and returns the **value
* service**.
*
* Value services are similar to constant services, except that they cannot be injected into a
* module configuration function (see {@link angular.Module#config}) but they can be overridden by
* an Angular
* {@link AUTO.$provide#decorator decorator}.
*
* @param {string} name The name of the instance.
* @param {*} value The value.
* @returns {Object} registered provider instance
*
* @example
* Here are some examples of creating value services.
* <pre>
* $provide.constant('ADMIN_USER', 'admin');
*
* $provide.constant('RoleLookup', { admin: 0, writer: 1, reader: 2 });
*
* $provide.constant('halfOf', function(value) {
* return value / 2;
* });
* </pre>
*/
/**
* @ngdoc method
* @name AUTO.$provide#constant
* @methodOf AUTO.$provide
* @description
*
* Register a **constant service**, such as a string, a number, an array, an object or a function,
* with the {@link AUTO.$injector $injector}. Unlike {@link AUTO.$provide#value value} it can be
* injected into a module configuration function (see {@link angular.Module#config}) and it cannot
* be overridden by an Angular {@link AUTO.$provide#decorator decorator}.
*
* @param {string} name The name of the constant.
* @param {*} value The constant value.
* @returns {Object} registered instance
*
* @example
* Here a some examples of creating constants:
* <pre>
* $provide.constant('SHARD_HEIGHT', 306);
*
* $provide.constant('MY_COLOURS', ['red', 'blue', 'grey']);
*
* $provide.constant('double', function(value) {
* return value * 2;
* });
* </pre>
*/
/**
* @ngdoc method
* @name AUTO.$provide#decorator
* @methodOf AUTO.$provide
* @description
*
* Register a **service decorator** with the {@link AUTO.$injector $injector}. A service decorator
* intercepts the creation of a service, allowing it to override or modify the behaviour of the
* service. The object returned by the decorator may be the original service, or a new service
* object which replaces or wraps and delegates to the original service.
*
* @param {string} name The name of the service to decorate.
* @param {function()} decorator This function will be invoked when the service needs to be
* instantiated and should return the decorated service instance. The function is called using
* the {@link AUTO.$injector#invoke injector.invoke} method and is therefore fully injectable.
* Local injection arguments:
*
* * `$delegate` - The original service instance, which can be monkey patched, configured,
* decorated or delegated to.
*
* @example
* Here we decorate the {@link ng.$log $log} service to convert warnings to errors by intercepting
* calls to {@link ng.$log#error $log.warn()}.
* <pre>
* $provider.decorator('$log', ['$delegate', function($delegate) {
* $delegate.warn = $delegate.error;
* return $delegate;
* }]);
* </pre>
*/
function createInjector(modulesToLoad) {
var INSTANTIATING = {},
providerSuffix = 'Provider',
path = [],
loadedModules = new HashMap(),
providerCache = {
$provide: {
provider: supportObject(provider),
factory: supportObject(factory),
service: supportObject(service),
value: supportObject(value),
constant: supportObject(constant),
decorator: decorator
}
},
providerInjector = (providerCache.$injector =
createInternalInjector(providerCache, function() {
throw $injectorMinErr('unpr', "Unknown provider: {0}", path.join(' <- '));
})),
instanceCache = {},
instanceInjector = (instanceCache.$injector =
createInternalInjector(instanceCache, function(servicename) {
var provider = providerInjector.get(servicename + providerSuffix);
return instanceInjector.invoke(provider.$get, provider);
}));
forEach(loadModules(modulesToLoad), function(fn) { instanceInjector.invoke(fn || noop); });
return instanceInjector;
////////////////////////////////////
// $provider
////////////////////////////////////
function supportObject(delegate) {
return function(key, value) {
if (isObject(key)) {
forEach(key, reverseParams(delegate));
} else {
return delegate(key, value);
}
};
}
function provider(name, provider_) {
assertNotHasOwnProperty(name, 'service');
if (isFunction(provider_) || isArray(provider_)) {
provider_ = providerInjector.instantiate(provider_);
}
if (!provider_.$get) {
throw $injectorMinErr('pget', "Provider '{0}' must define $get factory method.", name);
}
return providerCache[name + providerSuffix] = provider_;
}
function factory(name, factoryFn) { return provider(name, { $get: factoryFn }); }
function service(name, constructor) {
return factory(name, ['$injector', function($injector) {
return $injector.instantiate(constructor);
}]);
}
function value(name, val) { return factory(name, valueFn(val)); }
function constant(name, value) {
assertNotHasOwnProperty(name, 'constant');
providerCache[name] = value;
instanceCache[name] = value;
}
function decorator(serviceName, decorFn) {
var origProvider = providerInjector.get(serviceName + providerSuffix),
orig$get = origProvider.$get;
origProvider.$get = function() {
var origInstance = instanceInjector.invoke(orig$get, origProvider);
return instanceInjector.invoke(decorFn, null, {$delegate: origInstance});
};
}
////////////////////////////////////
// Module Loading
////////////////////////////////////
function loadModules(modulesToLoad){
var runBlocks = [], moduleFn, invokeQueue, i, ii;
forEach(modulesToLoad, function(module) {
if (loadedModules.get(module)) return;
loadedModules.put(module, true);
try {
if (isString(module)) {
moduleFn = angularModule(module);
runBlocks = runBlocks.concat(loadModules(moduleFn.requires)).concat(moduleFn._runBlocks);
for(invokeQueue = moduleFn._invokeQueue, i = 0, ii = invokeQueue.length; i < ii; i++) {
var invokeArgs = invokeQueue[i],
provider = providerInjector.get(invokeArgs[0]);
provider[invokeArgs[1]].apply(provider, invokeArgs[2]);
}
} else if (isFunction(module)) {
runBlocks.push(providerInjector.invoke(module));
} else if (isArray(module)) {
runBlocks.push(providerInjector.invoke(module));
} else {
assertArgFn(module, 'module');
}
} catch (e) {
if (isArray(module)) {
module = module[module.length - 1];
}
if (e.message && e.stack && e.stack.indexOf(e.message) == -1) {
// Safari & FF's stack traces don't contain error.message content
// unlike those of Chrome and IE
// So if stack doesn't contain message, we create a new string that contains both.
// Since error.stack is read-only in Safari, I'm overriding e and not e.stack here.
/* jshint -W022 */
e = e.message + '\n' + e.stack;
}
throw $injectorMinErr('modulerr', "Failed to instantiate module {0} due to:\n{1}",
module, e.stack || e.message || e);
}
});
return runBlocks;
}
////////////////////////////////////
// internal Injector
////////////////////////////////////
function createInternalInjector(cache, factory) {
function getService(serviceName) {
if (cache.hasOwnProperty(serviceName)) {
if (cache[serviceName] === INSTANTIATING) {
throw $injectorMinErr('cdep', 'Circular dependency found: {0}', path.join(' <- '));
}
return cache[serviceName];
} else {
try {
path.unshift(serviceName);
cache[serviceName] = INSTANTIATING;
return cache[serviceName] = factory(serviceName);
} finally {
path.shift();
}
}
}
function invoke(fn, self, locals){
var args = [],
$inject = annotate(fn),
length, i,
key;
for(i = 0, length = $inject.length; i < length; i++) {
key = $inject[i];
if (typeof key !== 'string') {
throw $injectorMinErr('itkn',
'Incorrect injection token! Expected service name as string, got {0}', key);
}
args.push(
locals && locals.hasOwnProperty(key)
? locals[key]
: getService(key)
);
}
if (!fn.$inject) {
// this means that we must be an array.
fn = fn[length];
}
// Performance optimization: http://jsperf.com/apply-vs-call-vs-invoke
switch (self ? -1 : args.length) {
case 0: return fn();
case 1: return fn(args[0]);
case 2: return fn(args[0], args[1]);
case 3: return fn(args[0], args[1], args[2]);
case 4: return fn(args[0], args[1], args[2], args[3]);
case 5: return fn(args[0], args[1], args[2], args[3], args[4]);
case 6: return fn(args[0], args[1], args[2], args[3], args[4], args[5]);
case 7: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6]);
case 8: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7]);
case 9: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7],
args[8]);
case 10: return fn(args[0], args[1], args[2], args[3], args[4], args[5], args[6], args[7],
args[8], args[9]);
default: return fn.apply(self, args);
}
}
function instantiate(Type, locals) {
var Constructor = function() {},
instance, returnedValue;
// Check if Type is annotated and use just the given function at n-1 as parameter
// e.g. someModule.factory('greeter', ['$window', function(renamed$window) {}]);
Constructor.prototype = (isArray(Type) ? Type[Type.length - 1] : Type).prototype;
instance = new Constructor();
returnedValue = invoke(Type, instance, locals);
return isObject(returnedValue) || isFunction(returnedValue) ? returnedValue : instance;
}
return {
invoke: invoke,
instantiate: instantiate,
get: getService,
annotate: annotate,
has: function(name) {
return providerCache.hasOwnProperty(name + providerSuffix) || cache.hasOwnProperty(name);
}
};
}
}
/**
* @ngdoc function
* @name ng.$anchorScroll
* @requires $window
* @requires $location
* @requires $rootScope
*
* @description
* When called, it checks current value of `$location.hash()` and scroll to related element,
* according to rules specified in
* {@link http://dev.w3.org/html5/spec/Overview.html#the-indicated-part-of-the-document Html5 spec}.
*
* It also watches the `$location.hash()` and scrolls whenever it changes to match any anchor.
* This can be disabled by calling `$anchorScrollProvider.disableAutoScrolling()`.
*
* @example
<example>
<file name="index.html">
<div id="scrollArea" ng-controller="ScrollCtrl">
<a ng-click="gotoBottom()">Go to bottom</a>
<a id="bottom"></a> You're at the bottom!
</div>
</file>
<file name="script.js">
function ScrollCtrl($scope, $location, $anchorScroll) {
$scope.gotoBottom = function (){
// set the location.hash to the id of
// the element you wish to scroll to.
$location.hash('bottom');
// call $anchorScroll()
$anchorScroll();
}
}
</file>
<file name="style.css">
#scrollArea {
height: 350px;
overflow: auto;
}
#bottom {
display: block;
margin-top: 2000px;
}
</file>
</example>
*/
function $AnchorScrollProvider() {
var autoScrollingEnabled = true;
this.disableAutoScrolling = function() {
autoScrollingEnabled = false;
};
this.$get = ['$window', '$location', '$rootScope', function($window, $location, $rootScope) {
var document = $window.document;
// helper function to get first anchor from a NodeList
// can't use filter.filter, as it accepts only instances of Array
// and IE can't convert NodeList to an array using [].slice
// TODO(vojta): use filter if we change it to accept lists as well
function getFirstAnchor(list) {
var result = null;
forEach(list, function(element) {
if (!result && lowercase(element.nodeName) === 'a') result = element;
});
return result;
}
function scroll() {
var hash = $location.hash(), elm;
// empty hash, scroll to the top of the page
if (!hash) $window.scrollTo(0, 0);
// element with given id
else if ((elm = document.getElementById(hash))) elm.scrollIntoView();
// first anchor with given name :-D
else if ((elm = getFirstAnchor(document.getElementsByName(hash)))) elm.scrollIntoView();
// no element and hash == 'top', scroll to the top of the page
else if (hash === 'top') $window.scrollTo(0, 0);
}
// does not scroll when user clicks on anchor link that is currently on
// (no url change, no $location.hash() change), browser native does scroll
if (autoScrollingEnabled) {
$rootScope.$watch(function autoScrollWatch() {return $location.hash();},
function autoScrollWatchAction() {
$rootScope.$evalAsync(scroll);
});
}
return scroll;
}];
}
var $animateMinErr = minErr('$animate');
/**
* @ngdoc object
* @name ng.$animateProvider
*
* @description
* Default implementation of $animate that doesn't perform any animations, instead just
* synchronously performs DOM
* updates and calls done() callbacks.
*
* In order to enable animations the ngAnimate module has to be loaded.
*
* To see the functional implementation check out src/ngAnimate/animate.js
*/
var $AnimateProvider = ['$provide', function($provide) {
this.$$selectors = {};
/**
* @ngdoc function
* @name ng.$animateProvider#register
* @methodOf ng.$animateProvider
*
* @description
* Registers a new injectable animation factory function. The factory function produces the
* animation object which contains callback functions for each event that is expected to be
* animated.
*
* * `eventFn`: `function(Element, doneFunction)` The element to animate, the `doneFunction`
* must be called once the element animation is complete. If a function is returned then the
* animation service will use this function to cancel the animation whenever a cancel event is
* triggered.
*
*
*<pre>
* return {
* eventFn : function(element, done) {
* //code to run the animation
* //once complete, then run done()
* return function cancellationFunction() {
* //code to cancel the animation
* }
* }
* }
*</pre>
*
* @param {string} name The name of the animation.
* @param {function} factory The factory function that will be executed to return the animation
* object.
*/
this.register = function(name, factory) {
var key = name + '-animation';
if (name && name.charAt(0) != '.') throw $animateMinErr('notcsel',
"Expecting class selector starting with '.' got '{0}'.", name);
this.$$selectors[name.substr(1)] = key;
$provide.factory(key, factory);
};
this.$get = ['$timeout', function($timeout) {
/**
*
* @ngdoc object
* @name ng.$animate
* @description The $animate service provides rudimentary DOM manipulation functions to
* insert, remove and move elements within the DOM, as well as adding and removing classes.
* This service is the core service used by the ngAnimate $animator service which provides
* high-level animation hooks for CSS and JavaScript.
*
* $animate is available in the AngularJS core, however, the ngAnimate module must be included
* to enable full out animation support. Otherwise, $animate will only perform simple DOM
* manipulation operations.
*
* To learn more about enabling animation support, click here to visit the {@link ngAnimate
* ngAnimate module page} as well as the {@link ngAnimate.$animate ngAnimate $animate service
* page}.
*/
return {
/**
*
* @ngdoc function
* @name ng.$animate#enter
* @methodOf ng.$animate
* @function
* @description Inserts the element into the DOM either after the `after` element or within
* the `parent` element. Once complete, the done() callback will be fired (if provided).
* @param {jQuery/jqLite element} element the element which will be inserted into the DOM
* @param {jQuery/jqLite element} parent the parent element which will append the element as
* a child (if the after element is not present)
* @param {jQuery/jqLite element} after the sibling element which will append the element
* after itself
* @param {function=} done callback function that will be called after the element has been
* inserted into the DOM
*/
enter : function(element, parent, after, done) {
var afterNode = after && after[after.length - 1];
var parentNode = parent && parent[0] || afterNode && afterNode.parentNode;
// IE does not like undefined so we have to pass null.
var afterNextSibling = (afterNode && afterNode.nextSibling) || null;
forEach(element, function(node) {
parentNode.insertBefore(node, afterNextSibling);
});
done && $timeout(done, 0, false);
},
/**
*
* @ngdoc function
* @name ng.$animate#leave
* @methodOf ng.$animate
* @function
* @description Removes the element from the DOM. Once complete, the done() callback will be
* fired (if provided).
* @param {jQuery/jqLite element} element the element which will be removed from the DOM
* @param {function=} done callback function that will be called after the element has been
* removed from the DOM
*/
leave : function(element, done) {
element.remove();
done && $timeout(done, 0, false);
},
/**
*
* @ngdoc function
* @name ng.$animate#move
* @methodOf ng.$animate
* @function
* @description Moves the position of the provided element within the DOM to be placed
* either after the `after` element or inside of the `parent` element. Once complete, the
* done() callback will be fired (if provided).
*
* @param {jQuery/jqLite element} element the element which will be moved around within the
* DOM
* @param {jQuery/jqLite element} parent the parent element where the element will be
* inserted into (if the after element is not present)
* @param {jQuery/jqLite element} after the sibling element where the element will be
* positioned next to
* @param {function=} done the callback function (if provided) that will be fired after the
* element has been moved to its new position
*/
move : function(element, parent, after, done) {
// Do not remove element before insert. Removing will cause data associated with the
// element to be dropped. Insert will implicitly do the remove.
this.enter(element, parent, after, done);
},
/**
*
* @ngdoc function
* @name ng.$animate#addClass
* @methodOf ng.$animate
* @function
* @description Adds the provided className CSS class value to the provided element. Once
* complete, the done() callback will be fired (if provided).
* @param {jQuery/jqLite element} element the element which will have the className value
* added to it
* @param {string} className the CSS class which will be added to the element
* @param {function=} done the callback function (if provided) that will be fired after the
* className value has been added to the element
*/
addClass : function(element, className, done) {
className = isString(className) ?
className :
isArray(className) ? className.join(' ') : '';
forEach(element, function (element) {
jqLiteAddClass(element, className);
});
done && $timeout(done, 0, false);
},
/**
*
* @ngdoc function
* @name ng.$animate#removeClass
* @methodOf ng.$animate
* @function
* @description Removes the provided className CSS class value from the provided element.
* Once complete, the done() callback will be fired (if provided).
* @param {jQuery/jqLite element} element the element which will have the className value
* removed from it
* @param {string} className the CSS class which will be removed from the element
* @param {function=} done the callback function (if provided) that will be fired after the
* className value has been removed from the element
*/
removeClass : function(element, className, done) {
className = isString(className) ?
className :
isArray(className) ? className.join(' ') : '';
forEach(element, function (element) {
jqLiteRemoveClass(element, className);
});
done && $timeout(done, 0, false);
},
enabled : noop
};
}];
}];
/**
* ! This is a private undocumented service !
*
* @name ng.$browser
* @requires $log
* @description
* This object has two goals:
*
* - hide all the global state in the browser caused by the window object
* - abstract away all the browser specific features and inconsistencies
*
* For tests we provide {@link ngMock.$browser mock implementation} of the `$browser`
* service, which can be used for convenient testing of the application without the interaction with
* the real browser apis.
*/
/**
* @param {object} window The global window object.
* @param {object} document jQuery wrapped document.
* @param {function()} XHR XMLHttpRequest constructor.
* @param {object} $log console.log or an object with the same interface.
* @param {object} $sniffer $sniffer service
*/
function Browser(window, document, $log, $sniffer) {
var self = this,
rawDocument = document[0],
location = window.location,
history = window.history,
setTimeout = window.setTimeout,
clearTimeout = window.clearTimeout,
pendingDeferIds = {};
self.isMock = false;
var outstandingRequestCount = 0;
var outstandingRequestCallbacks = [];
// TODO(vojta): remove this temporary api
self.$$completeOutstandingRequest = completeOutstandingRequest;
self.$$incOutstandingRequestCount = function() { outstandingRequestCount++; };
/**
* Executes the `fn` function(supports currying) and decrements the `outstandingRequestCallbacks`
* counter. If the counter reaches 0, all the `outstandingRequestCallbacks` are executed.
*/
function completeOutstandingRequest(fn) {
try {
fn.apply(null, sliceArgs(arguments, 1));
} finally {
outstandingRequestCount--;
if (outstandingRequestCount === 0) {
while(outstandingRequestCallbacks.length) {
try {
outstandingRequestCallbacks.pop()();
} catch (e) {
$log.error(e);
}
}
}
}
}
/**
* @private
* Note: this method is used only by scenario runner
* TODO(vojta): prefix this method with $$ ?
* @param {function()} callback Function that will be called when no outstanding request
*/
self.notifyWhenNoOutstandingRequests = function(callback) {
// force browser to execute all pollFns - this is needed so that cookies and other pollers fire
// at some deterministic time in respect to the test runner's actions. Leaving things up to the
// regular poller would result in flaky tests.
forEach(pollFns, function(pollFn){ pollFn(); });
if (outstandingRequestCount === 0) {
callback();
} else {
outstandingRequestCallbacks.push(callback);
}
};
//////////////////////////////////////////////////////////////
// Poll Watcher API
//////////////////////////////////////////////////////////////
var pollFns = [],
pollTimeout;
/**
* @name ng.$browser#addPollFn
* @methodOf ng.$browser
*
* @param {function()} fn Poll function to add
*
* @description
* Adds a function to the list of functions that poller periodically executes,
* and starts polling if not started yet.
*
* @returns {function()} the added function
*/
self.addPollFn = function(fn) {
if (isUndefined(pollTimeout)) startPoller(100, setTimeout);
pollFns.push(fn);
return fn;
};
/**
* @param {number} interval How often should browser call poll functions (ms)
* @param {function()} setTimeout Reference to a real or fake `setTimeout` function.
*
* @description
* Configures the poller to run in the specified intervals, using the specified
* setTimeout fn and kicks it off.
*/
function startPoller(interval, setTimeout) {
(function check() {
forEach(pollFns, function(pollFn){ pollFn(); });
pollTimeout = setTimeout(check, interval);
})();
}
//////////////////////////////////////////////////////////////
// URL API
//////////////////////////////////////////////////////////////
var lastBrowserUrl = location.href,
baseElement = document.find('base'),
newLocation = null;
/**
* @name ng.$browser#url
* @methodOf ng.$browser
*
* @description
* GETTER:
* Without any argument, this method just returns current value of location.href.
*
* SETTER:
* With at least one argument, this method sets url to new value.
* If html5 history api supported, pushState/replaceState is used, otherwise
* location.href/location.replace is used.
* Returns its own instance to allow chaining
*
* NOTE: this api is intended for use only by the $location service. Please use the
* {@link ng.$location $location service} to change url.
*
* @param {string} url New url (when used as setter)
* @param {boolean=} replace Should new url replace current history record ?
*/
self.url = function(url, replace) {
// Android Browser BFCache causes location reference to become stale.
if (location !== window.location) location = window.location;
// setter
if (url) {
if (lastBrowserUrl == url) return;
lastBrowserUrl = url;
if ($sniffer.history) {
if (replace) history.replaceState(null, '', url);
else {
history.pushState(null, '', url);
// Crazy Opera Bug: http://my.opera.com/community/forums/topic.dml?id=1185462
baseElement.attr('href', baseElement.attr('href'));
}
} else {
newLocation = url;
if (replace) {
location.replace(url);
} else {
location.href = url;
}
}
return self;
// getter
} else {
// - newLocation is a workaround for an IE7-9 issue with location.replace and location.href
// methods not updating location.href synchronously.
// - the replacement is a workaround for https://bugzilla.mozilla.org/show_bug.cgi?id=407172
return newLocation || location.href.replace(/%27/g,"'");
}
};
var urlChangeListeners = [],
urlChangeInit = false;
function fireUrlChange() {
newLocation = null;
if (lastBrowserUrl == self.url()) return;
lastBrowserUrl = self.url();
forEach(urlChangeListeners, function(listener) {
listener(self.url());
});
}
/**
* @name ng.$browser#onUrlChange
* @methodOf ng.$browser
* @TODO(vojta): refactor to use node's syntax for events
*
* @description
* Register callback function that will be called, when url changes.
*
* It's only called when the url is changed by outside of angular:
* - user types different url into address bar
* - user clicks on history (forward/back) button
* - user clicks on a link
*
* It's not called when url is changed by $browser.url() method
*
* The listener gets called with new url as parameter.
*
* NOTE: this api is intended for use only by the $location service. Please use the
* {@link ng.$location $location service} to monitor url changes in angular apps.
*
* @param {function(string)} listener Listener function to be called when url changes.
* @return {function(string)} Returns the registered listener fn - handy if the fn is anonymous.
*/
self.onUrlChange = function(callback) {
if (!urlChangeInit) {
// We listen on both (hashchange/popstate) when available, as some browsers (e.g. Opera)
// don't fire popstate when user change the address bar and don't fire hashchange when url
// changed by push/replaceState
// html5 history api - popstate event
if ($sniffer.history) jqLite(window).on('popstate', fireUrlChange);
// hashchange event
if ($sniffer.hashchange) jqLite(window).on('hashchange', fireUrlChange);
// polling
else self.addPollFn(fireUrlChange);
urlChangeInit = true;
}
urlChangeListeners.push(callback);
return callback;
};
//////////////////////////////////////////////////////////////
// Misc API
//////////////////////////////////////////////////////////////
/**
* @name ng.$browser#baseHref
* @methodOf ng.$browser
*
* @description
* Returns current <base href>
* (always relative - without domain)
*
* @returns {string=} current <base href>
*/
self.baseHref = function() {
var href = baseElement.attr('href');
return href ? href.replace(/^https?\:\/\/[^\/]*/, '') : '';
};
//////////////////////////////////////////////////////////////
// Cookies API
//////////////////////////////////////////////////////////////
var lastCookies = {};
var lastCookieString = '';
var cookiePath = self.baseHref();
/**
* @name ng.$browser#cookies
* @methodOf ng.$browser
*
* @param {string=} name Cookie name
* @param {string=} value Cookie value
*
* @description
* The cookies method provides a 'private' low level access to browser cookies.
* It is not meant to be used directly, use the $cookie service instead.
*
* The return values vary depending on the arguments that the method was called with as follows:
*
* - cookies() -> hash of all cookies, this is NOT a copy of the internal state, so do not modify
* it
* - cookies(name, value) -> set name to value, if value is undefined delete the cookie
* - cookies(name) -> the same as (name, undefined) == DELETES (no one calls it right now that
* way)
*
* @returns {Object} Hash of all cookies (if called without any parameter)
*/
self.cookies = function(name, value) {
/* global escape: false, unescape: false */
var cookieLength, cookieArray, cookie, i, index;
if (name) {
if (value === undefined) {
rawDocument.cookie = escape(name) + "=;path=" + cookiePath +
";expires=Thu, 01 Jan 1970 00:00:00 GMT";
} else {
if (isString(value)) {
cookieLength = (rawDocument.cookie = escape(name) + '=' + escape(value) +
';path=' + cookiePath).length + 1;
// per http://www.ietf.org/rfc/rfc2109.txt browser must allow at minimum:
// - 300 cookies
// - 20 cookies per unique domain
// - 4096 bytes per cookie
if (cookieLength > 4096) {
$log.warn("Cookie '"+ name +
"' possibly not set or overflowed because it was too large ("+
cookieLength + " > 4096 bytes)!");
}
}
}
} else {
if (rawDocument.cookie !== lastCookieString) {
lastCookieString = rawDocument.cookie;
cookieArray = lastCookieString.split("; ");
lastCookies = {};
for (i = 0; i < cookieArray.length; i++) {
cookie = cookieArray[i];
index = cookie.indexOf('=');
if (index > 0) { //ignore nameless cookies
name = unescape(cookie.substring(0, index));
// the first value that is seen for a cookie is the most
// specific one. values for the same cookie name that
// follow are for less specific paths.
if (lastCookies[name] === undefined) {
lastCookies[name] = unescape(cookie.substring(index + 1));
}
}
}
}
return lastCookies;
}
};
/**
* @name ng.$browser#defer
* @methodOf ng.$browser
* @param {function()} fn A function, who's execution should be deferred.
* @param {number=} [delay=0] of milliseconds to defer the function execution.
* @returns {*} DeferId that can be used to cancel the task via `$browser.defer.cancel()`.
*
* @description
* Executes a fn asynchronously via `setTimeout(fn, delay)`.
*
* Unlike when calling `setTimeout` directly, in test this function is mocked and instead of using
* `setTimeout` in tests, the fns are queued in an array, which can be programmatically flushed
* via `$browser.defer.flush()`.
*
*/
self.defer = function(fn, delay) {
var timeoutId;
outstandingRequestCount++;
timeoutId = setTimeout(function() {
delete pendingDeferIds[timeoutId];
completeOutstandingRequest(fn);
}, delay || 0);
pendingDeferIds[timeoutId] = true;
return timeoutId;
};
/**
* @name ng.$browser#defer.cancel
* @methodOf ng.$browser.defer
*
* @description
* Cancels a deferred task identified with `deferId`.
*
* @param {*} deferId Token returned by the `$browser.defer` function.
* @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
* canceled.
*/
self.defer.cancel = function(deferId) {
if (pendingDeferIds[deferId]) {
delete pendingDeferIds[deferId];
clearTimeout(deferId);
completeOutstandingRequest(noop);
return true;
}
return false;
};
}
function $BrowserProvider(){
this.$get = ['$window', '$log', '$sniffer', '$document',
function( $window, $log, $sniffer, $document){
return new Browser($window, $document, $log, $sniffer);
}];
}
/**
* @ngdoc object
* @name ng.$cacheFactory
*
* @description
* Factory that constructs cache objects and gives access to them.
*
* <pre>
*
* var cache = $cacheFactory('cacheId');
* expect($cacheFactory.get('cacheId')).toBe(cache);
* expect($cacheFactory.get('noSuchCacheId')).not.toBeDefined();
*
* cache.put("key", "value");
* cache.put("another key", "another value");
*
* // We've specified no options on creation
* expect(cache.info()).toEqual({id: 'cacheId', size: 2});
*
* </pre>
*
*
* @param {string} cacheId Name or id of the newly created cache.
* @param {object=} options Options object that specifies the cache behavior. Properties:
*
* - `{number=}` `capacity` — turns the cache into LRU cache.
*
* @returns {object} Newly created cache object with the following set of methods:
*
* - `{object}` `info()` — Returns id, size, and options of cache.
* - `{{*}}` `put({string} key, {*} value)` — Puts a new key-value pair into the cache and returns
* it.
* - `{{*}}` `get({string} key)` — Returns cached value for `key` or undefined for cache miss.
* - `{void}` `remove({string} key)` — Removes a key-value pair from the cache.
* - `{void}` `removeAll()` — Removes all cached values.
* - `{void}` `destroy()` — Removes references to this cache from $cacheFactory.
*
*/
function $CacheFactoryProvider() {
this.$get = function() {
var caches = {};
function cacheFactory(cacheId, options) {
if (cacheId in caches) {
throw minErr('$cacheFactory')('iid', "CacheId '{0}' is already taken!", cacheId);
}
var size = 0,
stats = extend({}, options, {id: cacheId}),
data = {},
capacity = (options && options.capacity) || Number.MAX_VALUE,
lruHash = {},
freshEnd = null,
staleEnd = null;
return caches[cacheId] = {
put: function(key, value) {
var lruEntry = lruHash[key] || (lruHash[key] = {key: key});
refresh(lruEntry);
if (isUndefined(value)) return;
if (!(key in data)) size++;
data[key] = value;
if (size > capacity) {
this.remove(staleEnd.key);
}
return value;
},
get: function(key) {
var lruEntry = lruHash[key];
if (!lruEntry) return;
refresh(lruEntry);
return data[key];
},
remove: function(key) {
var lruEntry = lruHash[key];
if (!lruEntry) return;
if (lruEntry == freshEnd) freshEnd = lruEntry.p;
if (lruEntry == staleEnd) staleEnd = lruEntry.n;
link(lruEntry.n,lruEntry.p);
delete lruHash[key];
delete data[key];
size--;
},
removeAll: function() {
data = {};
size = 0;
lruHash = {};
freshEnd = staleEnd = null;
},
destroy: function() {
data = null;
stats = null;
lruHash = null;
delete caches[cacheId];
},
info: function() {
return extend({}, stats, {size: size});
}
};
/**
* makes the `entry` the freshEnd of the LRU linked list
*/
function refresh(entry) {
if (entry != freshEnd) {
if (!staleEnd) {
staleEnd = entry;
} else if (staleEnd == entry) {
staleEnd = entry.n;
}
link(entry.n, entry.p);
link(entry, freshEnd);
freshEnd = entry;
freshEnd.n = null;
}
}
/**
* bidirectionally links two entries of the LRU linked list
*/
function link(nextEntry, prevEntry) {
if (nextEntry != prevEntry) {
if (nextEntry) nextEntry.p = prevEntry; //p stands for previous, 'prev' didn't minify
if (prevEntry) prevEntry.n = nextEntry; //n stands for next, 'next' didn't minify
}
}
}
/**
* @ngdoc method
* @name ng.$cacheFactory#info
* @methodOf ng.$cacheFactory
*
* @description
* Get information about all the of the caches that have been created
*
* @returns {Object} - key-value map of `cacheId` to the result of calling `cache#info`
*/
cacheFactory.info = function() {
var info = {};
forEach(caches, function(cache, cacheId) {
info[cacheId] = cache.info();
});
return info;
};
/**
* @ngdoc method
* @name ng.$cacheFactory#get
* @methodOf ng.$cacheFactory
*
* @description
* Get access to a cache object by the `cacheId` used when it was created.
*
* @param {string} cacheId Name or id of a cache to access.
* @returns {object} Cache object identified by the cacheId or undefined if no such cache.
*/
cacheFactory.get = function(cacheId) {
return caches[cacheId];
};
return cacheFactory;
};
}
/**
* @ngdoc object
* @name ng.$templateCache
*
* @description
* The first time a template is used, it is loaded in the template cache for quick retrieval. You
* can load templates directly into the cache in a `script` tag, or by consuming the
* `$templateCache` service directly.
*
* Adding via the `script` tag:
* <pre>
* <html ng-app>
* <head>
* <script type="text/ng-template" id="templateId.html">
* This is the content of the template
* </script>
* </head>
* ...
* </html>
* </pre>
*
* **Note:** the `script` tag containing the template does not need to be included in the `head` of
* the document, but it must be below the `ng-app` definition.
*
* Adding via the $templateCache service:
*
* <pre>
* var myApp = angular.module('myApp', []);
* myApp.run(function($templateCache) {
* $templateCache.put('templateId.html', 'This is the content of the template');
* });
* </pre>
*
* To retrieve the template later, simply use it in your HTML:
* <pre>
* <div ng-include=" 'templateId.html' "></div>
* </pre>
*
* or get it via Javascript:
* <pre>
* $templateCache.get('templateId.html')
* </pre>
*
* See {@link ng.$cacheFactory $cacheFactory}.
*
*/
function $TemplateCacheProvider() {
this.$get = ['$cacheFactory', function($cacheFactory) {
return $cacheFactory('templates');
}];
}
/* ! VARIABLE/FUNCTION NAMING CONVENTIONS THAT APPLY TO THIS FILE!
*
* DOM-related variables:
*
* - "node" - DOM Node
* - "element" - DOM Element or Node
* - "$node" or "$element" - jqLite-wrapped node or element
*
*
* Compiler related stuff:
*
* - "linkFn" - linking fn of a single directive
* - "nodeLinkFn" - function that aggregates all linking fns for a particular node
* - "childLinkFn" - function that aggregates all linking fns for child nodes of a particular node
* - "compositeLinkFn" - function that aggregates all linking fns for a compilation root (nodeList)
*/
/**
* @ngdoc function
* @name ng.$compile
* @function
*
* @description
* Compiles a piece of HTML string or DOM into a template and produces a template function, which
* can then be used to link {@link ng.$rootScope.Scope `scope`} and the template together.
*
* The compilation is a process of walking the DOM tree and matching DOM elements to
* {@link ng.$compileProvider#methods_directive directives}.
*
* <div class="alert alert-warning">
* **Note:** This document is an in-depth reference of all directive options.
* For a gentle introduction to directives with examples of common use cases,
* see the {@link guide/directive directive guide}.
* </div>
*
* ## Comprehensive Directive API
*
* There are many different options for a directive.
*
* The difference resides in the return value of the factory function.
* You can either return a "Directive Definition Object" (see below) that defines the directive properties,
* or just the `postLink` function (all other properties will have the default values).
*
* <div class="alert alert-success">
* **Best Practice:** It's recommended to use the "directive definition object" form.
* </div>
*
* Here's an example directive declared with a Directive Definition Object:
*
* <pre>
* var myModule = angular.module(...);
*
* myModule.directive('directiveName', function factory(injectables) {
* var directiveDefinitionObject = {
* priority: 0,
* template: '<div></div>', // or // function(tElement, tAttrs) { ... },
* // or
* // templateUrl: 'directive.html', // or // function(tElement, tAttrs) { ... },
* replace: false,
* transclude: false,
* restrict: 'A',
* scope: false,
* controller: function($scope, $element, $attrs, $transclude, otherInjectables) { ... },
* require: 'siblingDirectiveName', // or // ['^parentDirectiveName', '?optionalDirectiveName', '?^optionalParent'],
* compile: function compile(tElement, tAttrs, transclude) {
* return {
* pre: function preLink(scope, iElement, iAttrs, controller) { ... },
* post: function postLink(scope, iElement, iAttrs, controller) { ... }
* }
* // or
* // return function postLink( ... ) { ... }
* },
* // or
* // link: {
* // pre: function preLink(scope, iElement, iAttrs, controller) { ... },
* // post: function postLink(scope, iElement, iAttrs, controller) { ... }
* // }
* // or
* // link: function postLink( ... ) { ... }
* };
* return directiveDefinitionObject;
* });
* </pre>
*
* <div class="alert alert-warning">
* **Note:** Any unspecified options will use the default value. You can see the default values below.
* </div>
*
* Therefore the above can be simplified as:
*
* <pre>
* var myModule = angular.module(...);
*
* myModule.directive('directiveName', function factory(injectables) {
* var directiveDefinitionObject = {
* link: function postLink(scope, iElement, iAttrs) { ... }
* };
* return directiveDefinitionObject;
* // or
* // return function postLink(scope, iElement, iAttrs) { ... }
* });
* </pre>
*
*
*
* ### Directive Definition Object
*
* The directive definition object provides instructions to the {@link api/ng.$compile
* compiler}. The attributes are:
*
* #### `priority`
* When there are multiple directives defined on a single DOM element, sometimes it
* is necessary to specify the order in which the directives are applied. The `priority` is used
* to sort the directives before their `compile` functions get called. Priority is defined as a
* number. Directives with greater numerical `priority` are compiled first. The order of directives with
* the same priority is undefined. The default priority is `0`.
*
* #### `terminal`
* If set to true then the current `priority` will be the last set of directives
* which will execute (any directives at the current priority will still execute
* as the order of execution on same `priority` is undefined).
*
* #### `scope`
* **If set to `true`,** then a new scope will be created for this directive. If multiple directives on the
* same element request a new scope, only one new scope is created. The new scope rule does not
* apply for the root of the template since the root of the template always gets a new scope.
*
* **If set to `{}` (object hash),** then a new "isolate" scope is created. The 'isolate' scope differs from
* normal scope in that it does not prototypically inherit from the parent scope. This is useful
* when creating reusable components, which should not accidentally read or modify data in the
* parent scope.
*
* The 'isolate' scope takes an object hash which defines a set of local scope properties
* derived from the parent scope. These local properties are useful for aliasing values for
* templates. Locals definition is a hash of local scope property to its source:
*
* * `@` or `@attr` - bind a local scope property to the value of DOM attribute. The result is
* always a string since DOM attributes are strings. If no `attr` name is specified then the
* attribute name is assumed to be the same as the local name.
* Given `<widget my-attr="hello {{name}}">` and widget definition
* of `scope: { localName:'@myAttr' }`, then widget scope property `localName` will reflect
* the interpolated value of `hello {{name}}`. As the `name` attribute changes so will the
* `localName` property on the widget scope. The `name` is read from the parent scope (not
* component scope).
*
* * `=` or `=attr` - set up bi-directional binding between a local scope property and the
* parent scope property of name defined via the value of the `attr` attribute. If no `attr`
* name is specified then the attribute name is assumed to be the same as the local name.
* Given `<widget my-attr="parentModel">` and widget definition of
* `scope: { localModel:'=myAttr' }`, then widget scope property `localModel` will reflect the
* value of `parentModel` on the parent scope. Any changes to `parentModel` will be reflected
* in `localModel` and any changes in `localModel` will reflect in `parentModel`. If the parent
* scope property doesn't exist, it will throw a NON_ASSIGNABLE_MODEL_EXPRESSION exception. You
* can avoid this behavior using `=?` or `=?attr` in order to flag the property as optional.
*
* * `&` or `&attr` - provides a way to execute an expression in the context of the parent scope.
* If no `attr` name is specified then the attribute name is assumed to be the same as the
* local name. Given `<widget my-attr="count = count + value">` and widget definition of
* `scope: { localFn:'&myAttr' }`, then isolate scope property `localFn` will point to
* a function wrapper for the `count = count + value` expression. Often it's desirable to
* pass data from the isolated scope via an expression and to the parent scope, this can be
* done by passing a map of local variable names and values into the expression wrapper fn.
* For example, if the expression is `increment(amount)` then we can specify the amount value
* by calling the `localFn` as `localFn({amount: 22})`.
*
*
*
* #### `controller`
* Controller constructor function. The controller is instantiated before the
* pre-linking phase and it is shared with other directives (see
* `require` attribute). This allows the directives to communicate with each other and augment
* each other's behavior. The controller is injectable (and supports bracket notation) with the following locals:
*
* * `$scope` - Current scope associated with the element
* * `$element` - Current element
* * `$attrs` - Current attributes object for the element
* * `$transclude` - A transclude linking function pre-bound to the correct transclusion scope:
* `function(cloneLinkingFn)`.
*
*
* #### `require`
* Require another directive and inject its controller as the fourth argument to the linking function. The
* `require` takes a string name (or array of strings) of the directive(s) to pass in. If an array is used, the
* injected argument will be an array in corresponding order. If no such directive can be
* found, or if the directive does not have a controller, then an error is raised. The name can be prefixed with:
*
* * (no prefix) - Locate the required controller on the current element. Throw an error if not found.
* * `?` - Attempt to locate the required controller or pass `null` to the `link` fn if not found.
* * `^` - Locate the required controller by searching the element's parents. Throw an error if not found.
* * `?^` - Attempt to locate the required controller by searching the element's parentsor pass `null` to the
* `link` fn if not found.
*
*
* #### `controllerAs`
* Controller alias at the directive scope. An alias for the controller so it
* can be referenced at the directive template. The directive needs to define a scope for this
* configuration to be used. Useful in the case when directive is used as component.
*
*
* #### `restrict`
* String of subset of `EACM` which restricts the directive to a specific directive
* declaration style. If omitted, the default (attributes only) is used.
*
* * `E` - Element name: `<my-directive></my-directive>`
* * `A` - Attribute (default): `<div my-directive="exp"></div>`
* * `C` - Class: `<div class="my-directive: exp;"></div>`
* * `M` - Comment: `<!-- directive: my-directive exp -->`
*
*
* #### `template`
* replace the current element with the contents of the HTML. The replacement process
* migrates all of the attributes / classes from the old element to the new one. See the
* {@link guide/directive#creating-custom-directives_creating-directives_template-expanding-directive
* Directives Guide} for an example.
*
* You can specify `template` as a string representing the template or as a function which takes
* two arguments `tElement` and `tAttrs` (described in the `compile` function api below) and
* returns a string value representing the template.
*
*
* #### `templateUrl`
* Same as `template` but the template is loaded from the specified URL. Because
* the template loading is asynchronous the compilation/linking is suspended until the template
* is loaded.
*
* You can specify `templateUrl` as a string representing the URL or as a function which takes two
* arguments `tElement` and `tAttrs` (described in the `compile` function api below) and returns
* a string value representing the url. In either case, the template URL is passed through {@link
* api/ng.$sce#methods_getTrustedResourceUrl $sce.getTrustedResourceUrl}.
*
*
* #### `replace`
* specify where the template should be inserted. Defaults to `false`.
*
* * `true` - the template will replace the current element.
* * `false` - the template will replace the contents of the current element.
*
*
* #### `transclude`
* compile the content of the element and make it available to the directive.
* Typically used with {@link api/ng.directive:ngTransclude
* ngTransclude}. The advantage of transclusion is that the linking function receives a
* transclusion function which is pre-bound to the correct scope. In a typical setup the widget
* creates an `isolate` scope, but the transclusion is not a child, but a sibling of the `isolate`
* scope. This makes it possible for the widget to have private state, and the transclusion to
* be bound to the parent (pre-`isolate`) scope.
*
* * `true` - transclude the content of the directive.
* * `'element'` - transclude the whole element including any directives defined at lower priority.
*
*
* #### `compile`
*
* <pre>
* function compile(tElement, tAttrs, transclude) { ... }
* </pre>
*
* The compile function deals with transforming the template DOM. Since most directives do not do
* template transformation, it is not used often. Examples that require compile functions are
* directives that transform template DOM, such as {@link
* api/ng.directive:ngRepeat ngRepeat}, or load the contents
* asynchronously, such as {@link api/ngRoute.directive:ngView ngView}. The
* compile function takes the following arguments.
*
* * `tElement` - template element - The element where the directive has been declared. It is
* safe to do template transformation on the element and child elements only.
*
* * `tAttrs` - template attributes - Normalized list of attributes declared on this element shared
* between all directive compile functions.
*
* * `transclude` - A transclude linking function: `function(scope, cloneLinkingFn)`.
*
* <div class="alert alert-warning">
* **Note:** The template instance and the link instance may be different objects if the template has
* been cloned. For this reason it is **not** safe to do anything other than DOM transformations that
* apply to all cloned DOM nodes within the compile function. Specifically, DOM listener registration
* should be done in a linking function rather than in a compile function.
* </div>
*
* A compile function can have a return value which can be either a function or an object.
*
* * returning a (post-link) function - is equivalent to registering the linking function via the
* `link` property of the config object when the compile function is empty.
*
* * returning an object with function(s) registered via `pre` and `post` properties - allows you to
* control when a linking function should be called during the linking phase. See info about
* pre-linking and post-linking functions below.
*
*
* #### `link`
* This property is used only if the `compile` property is not defined.
*
* <pre>
* function link(scope, iElement, iAttrs, controller) { ... }
* </pre>
*
* The link function is responsible for registering DOM listeners as well as updating the DOM. It is
* executed after the template has been cloned. This is where most of the directive logic will be
* put.
*
* * `scope` - {@link api/ng.$rootScope.Scope Scope} - The scope to be used by the
* directive for registering {@link api/ng.$rootScope.Scope#methods_$watch watches}.
*
* * `iElement` - instance element - The element where the directive is to be used. It is safe to
* manipulate the children of the element only in `postLink` function since the children have
* already been linked.
*
* * `iAttrs` - instance attributes - Normalized list of attributes declared on this element shared
* between all directive linking functions.
*
* * `controller` - a controller instance - A controller instance if at least one directive on the
* element defines a controller. The controller is shared among all the directives, which allows
* the directives to use the controllers as a communication channel.
*
*
*
* #### Pre-linking function
*
* Executed before the child elements are linked. Not safe to do DOM transformation since the
* compiler linking function will fail to locate the correct elements for linking.
*
* #### Post-linking function
*
* Executed after the child elements are linked. It is safe to do DOM transformation in the post-linking function.
*
* <a name="Attributes"></a>
* ### Attributes
*
* The {@link api/ng.$compile.directive.Attributes Attributes} object - passed as a parameter in the
* `link()` or `compile()` functions. It has a variety of uses.
*
* accessing *Normalized attribute names:*
* Directives like 'ngBind' can be expressed in many ways: 'ng:bind', `data-ng-bind`, or 'x-ng-bind'.
* the attributes object allows for normalized access to
* the attributes.
*
* * *Directive inter-communication:* All directives share the same instance of the attributes
* object which allows the directives to use the attributes object as inter directive
* communication.
*
* * *Supports interpolation:* Interpolation attributes are assigned to the attribute object
* allowing other directives to read the interpolated value.
*
* * *Observing interpolated attributes:* Use `$observe` to observe the value changes of attributes
* that contain interpolation (e.g. `src="{{bar}}"`). Not only is this very efficient but it's also
* the only way to easily get the actual value because during the linking phase the interpolation
* hasn't been evaluated yet and so the value is at this time set to `undefined`.
*
* <pre>
* function linkingFn(scope, elm, attrs, ctrl) {
* // get the attribute value
* console.log(attrs.ngModel);
*
* // change the attribute
* attrs.$set('ngModel', 'new value');
*
* // observe changes to interpolated attribute
* attrs.$observe('ngModel', function(value) {
* console.log('ngModel has changed value to ' + value);
* });
* }
* </pre>
*
* Below is an example using `$compileProvider`.
*
* <div class="alert alert-warning">
* **Note**: Typically directives are registered with `module.directive`. The example below is
* to illustrate how `$compile` works.
* </div>
*
<doc:example module="compile">
<doc:source>
<script>
angular.module('compile', [], function($compileProvider) {
// configure new 'compile' directive by passing a directive
// factory function. The factory function injects the '$compile'
$compileProvider.directive('compile', function($compile) {
// directive factory creates a link function
return function(scope, element, attrs) {
scope.$watch(
function(scope) {
// watch the 'compile' expression for changes
return scope.$eval(attrs.compile);
},
function(value) {
// when the 'compile' expression changes
// assign it into the current DOM
element.html(value);
// compile the new DOM and link it to the current
// scope.
// NOTE: we only compile .childNodes so that
// we don't get into infinite loop compiling ourselves
$compile(element.contents())(scope);
}
);
};
})
});
function Ctrl($scope) {
$scope.name = 'Angular';
$scope.html = 'Hello {{name}}';
}
</script>
<div ng-controller="Ctrl">
<input ng-model="name"> <br>
<textarea ng-model="html"></textarea> <br>
<div compile="html"></div>
</div>
</doc:source>
<doc:scenario>
it('should auto compile', function() {
expect(element('div[compile]').text()).toBe('Hello Angular');
input('html').enter('{{name}}!');
expect(element('div[compile]').text()).toBe('Angular!');
});
</doc:scenario>
</doc:example>
*
*
* @param {string|DOMElement} element Element or HTML string to compile into a template function.
* @param {function(angular.Scope[, cloneAttachFn]} transclude function available to directives.
* @param {number} maxPriority only apply directives lower then given priority (Only effects the
* root element(s), not their children)
* @returns {function(scope[, cloneAttachFn])} a link function which is used to bind template
* (a DOM element/tree) to a scope. Where:
*
* * `scope` - A {@link ng.$rootScope.Scope Scope} to bind to.
* * `cloneAttachFn` - If `cloneAttachFn` is provided, then the link function will clone the
* `template` and call the `cloneAttachFn` function allowing the caller to attach the
* cloned elements to the DOM document at the appropriate place. The `cloneAttachFn` is
* called as: <br> `cloneAttachFn(clonedElement, scope)` where:
*
* * `clonedElement` - is a clone of the original `element` passed into the compiler.
* * `scope` - is the current scope with which the linking function is working with.
*
* Calling the linking function returns the element of the template. It is either the original
* element passed in, or the clone of the element if the `cloneAttachFn` is provided.
*
* After linking the view is not updated until after a call to $digest which typically is done by
* Angular automatically.
*
* If you need access to the bound view, there are two ways to do it:
*
* - If you are not asking the linking function to clone the template, create the DOM element(s)
* before you send them to the compiler and keep this reference around.
* <pre>
* var element = $compile('<p>{{total}}</p>')(scope);
* </pre>
*
* - if on the other hand, you need the element to be cloned, the view reference from the original
* example would not point to the clone, but rather to the original template that was cloned. In
* this case, you can access the clone via the cloneAttachFn:
* <pre>
* var templateHTML = angular.element('<p>{{total}}</p>'),
* scope = ....;
*
* var clonedElement = $compile(templateHTML)(scope, function(clonedElement, scope) {
* //attach the clone to DOM document at the right place
* });
*
* //now we have reference to the cloned DOM via `clone`
* </pre>
*
*
* For information on how the compiler works, see the
* {@link guide/compiler Angular HTML Compiler} section of the Developer Guide.
*/
var $compileMinErr = minErr('$compile');
/**
* @ngdoc service
* @name ng.$compileProvider
* @function
*
* @description
*/
$CompileProvider.$inject = ['$provide'];
function $CompileProvider($provide) {
var hasDirectives = {},
Suffix = 'Directive',
COMMENT_DIRECTIVE_REGEXP = /^\s*directive\:\s*([\d\w\-_]+)\s+(.*)$/,
CLASS_DIRECTIVE_REGEXP = /(([\d\w\-_]+)(?:\:([^;]+))?;?)/,
aHrefSanitizationWhitelist = /^\s*(https?|ftp|mailto|tel|file):/,
imgSrcSanitizationWhitelist = /^\s*(https?|ftp|file):|data:image\//;
// Ref: http://developers.whatwg.org/webappapis.html#event-handler-idl-attributes
// The assumption is that future DOM event attribute names will begin with
// 'on' and be composed of only English letters.
var EVENT_HANDLER_ATTR_REGEXP = /^(on[a-z]+|formaction)$/;
/**
* @ngdoc function
* @name ng.$compileProvider#directive
* @methodOf ng.$compileProvider
* @function
*
* @description
* Register a new directive with the compiler.
*
* @param {string|Object} name Name of the directive in camel-case (i.e. <code>ngBind</code> which
* will match as <code>ng-bind</code>), or an object map of directives where the keys are the
* names and the values are the factories.
* @param {function|Array} directiveFactory An injectable directive factory function. See
* {@link guide/directive} for more info.
* @returns {ng.$compileProvider} Self for chaining.
*/
this.directive = function registerDirective(name, directiveFactory) {
assertNotHasOwnProperty(name, 'directive');
if (isString(name)) {
assertArg(directiveFactory, 'directiveFactory');
if (!hasDirectives.hasOwnProperty(name)) {
hasDirectives[name] = [];
$provide.factory(name + Suffix, ['$injector', '$exceptionHandler',
function($injector, $exceptionHandler) {
var directives = [];
forEach(hasDirectives[name], function(directiveFactory, index) {
try {
var directive = $injector.invoke(directiveFactory);
if (isFunction(directive)) {
directive = { compile: valueFn(directive) };
} else if (!directive.compile && directive.link) {
directive.compile = valueFn(directive.link);
}
directive.priority = directive.priority || 0;
directive.index = index;
directive.name = directive.name || name;
directive.require = directive.require || (directive.controller && directive.name);
directive.restrict = directive.restrict || 'A';
directives.push(directive);
} catch (e) {
$exceptionHandler(e);
}
});
return directives;
}]);
}
hasDirectives[name].push(directiveFactory);
} else {
forEach(name, reverseParams(registerDirective));
}
return this;
};
/**
* @ngdoc function
* @name ng.$compileProvider#aHrefSanitizationWhitelist
* @methodOf ng.$compileProvider
* @function
*
* @description
* Retrieves or overrides the default regular expression that is used for whitelisting of safe
* urls during a[href] sanitization.
*
* The sanitization is a security measure aimed at prevent XSS attacks via html links.
*
* Any url about to be assigned to a[href] via data-binding is first normalized and turned into
* an absolute url. Afterwards, the url is matched against the `aHrefSanitizationWhitelist`
* regular expression. If a match is found, the original url is written into the dom. Otherwise,
* the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
*
* @param {RegExp=} regexp New regexp to whitelist urls with.
* @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
* chaining otherwise.
*/
this.aHrefSanitizationWhitelist = function(regexp) {
if (isDefined(regexp)) {
aHrefSanitizationWhitelist = regexp;
return this;
}
return aHrefSanitizationWhitelist;
};
/**
* @ngdoc function
* @name ng.$compileProvider#imgSrcSanitizationWhitelist
* @methodOf ng.$compileProvider
* @function
*
* @description
* Retrieves or overrides the default regular expression that is used for whitelisting of safe
* urls during img[src] sanitization.
*
* The sanitization is a security measure aimed at prevent XSS attacks via html links.
*
* Any url about to be assigned to img[src] via data-binding is first normalized and turned into
* an absolute url. Afterwards, the url is matched against the `imgSrcSanitizationWhitelist`
* regular expression. If a match is found, the original url is written into the dom. Otherwise,
* the absolute url is prefixed with `'unsafe:'` string and only then is it written into the DOM.
*
* @param {RegExp=} regexp New regexp to whitelist urls with.
* @returns {RegExp|ng.$compileProvider} Current RegExp if called without value or self for
* chaining otherwise.
*/
this.imgSrcSanitizationWhitelist = function(regexp) {
if (isDefined(regexp)) {
imgSrcSanitizationWhitelist = regexp;
return this;
}
return imgSrcSanitizationWhitelist;
};
this.$get = [
'$injector', '$interpolate', '$exceptionHandler', '$http', '$templateCache', '$parse',
'$controller', '$rootScope', '$document', '$sce', '$animate',
function($injector, $interpolate, $exceptionHandler, $http, $templateCache, $parse,
$controller, $rootScope, $document, $sce, $animate) {
var Attributes = function(element, attr) {
this.$$element = element;
this.$attr = attr || {};
};
Attributes.prototype = {
$normalize: directiveNormalize,
/**
* @ngdoc function
* @name ng.$compile.directive.Attributes#$addClass
* @methodOf ng.$compile.directive.Attributes
* @function
*
* @description
* Adds the CSS class value specified by the classVal parameter to the element. If animations
* are enabled then an animation will be triggered for the class addition.
*
* @param {string} classVal The className value that will be added to the element
*/
$addClass : function(classVal) {
if(classVal && classVal.length > 0) {
$animate.addClass(this.$$element, classVal);
}
},
/**
* @ngdoc function
* @name ng.$compile.directive.Attributes#$removeClass
* @methodOf ng.$compile.directive.Attributes
* @function
*
* @description
* Removes the CSS class value specified by the classVal parameter from the element. If
* animations are enabled then an animation will be triggered for the class removal.
*
* @param {string} classVal The className value that will be removed from the element
*/
$removeClass : function(classVal) {
if(classVal && classVal.length > 0) {
$animate.removeClass(this.$$element, classVal);
}
},
/**
* Set a normalized attribute on the element in a way such that all directives
* can share the attribute. This function properly handles boolean attributes.
* @param {string} key Normalized key. (ie ngAttribute)
* @param {string|boolean} value The value to set. If `null` attribute will be deleted.
* @param {boolean=} writeAttr If false, does not write the value to DOM element attribute.
* Defaults to true.
* @param {string=} attrName Optional none normalized name. Defaults to key.
*/
$set: function(key, value, writeAttr, attrName) {
//special case for class attribute addition + removal
//so that class changes can tap into the animation
//hooks provided by the $animate service
if(key == 'class') {
value = value || '';
var current = this.$$element.attr('class') || '';
this.$removeClass(tokenDifference(current, value).join(' '));
this.$addClass(tokenDifference(value, current).join(' '));
} else {
var booleanKey = getBooleanAttrName(this.$$element[0], key),
normalizedVal,
nodeName;
if (booleanKey) {
this.$$element.prop(key, value);
attrName = booleanKey;
}
this[key] = value;
// translate normalized key to actual key
if (attrName) {
this.$attr[key] = attrName;
} else {
attrName = this.$attr[key];
if (!attrName) {
this.$attr[key] = attrName = snake_case(key, '-');
}
}
nodeName = nodeName_(this.$$element);
// sanitize a[href] and img[src] values
if ((nodeName === 'A' && key === 'href') ||
(nodeName === 'IMG' && key === 'src')) {
// NOTE: urlResolve() doesn't support IE < 8 so we don't sanitize for that case.
if (!msie || msie >= 8 ) {
normalizedVal = urlResolve(value).href;
if (normalizedVal !== '') {
if ((key === 'href' && !normalizedVal.match(aHrefSanitizationWhitelist)) ||
(key === 'src' && !normalizedVal.match(imgSrcSanitizationWhitelist))) {
this[key] = value = 'unsafe:' + normalizedVal;
}
}
}
}
if (writeAttr !== false) {
if (value === null || value === undefined) {
this.$$element.removeAttr(attrName);
} else {
this.$$element.attr(attrName, value);
}
}
}
// fire observers
var $$observers = this.$$observers;
$$observers && forEach($$observers[key], function(fn) {
try {
fn(value);
} catch (e) {
$exceptionHandler(e);
}
});
function tokenDifference(str1, str2) {
var values = [],
tokens1 = str1.split(/\s+/),
tokens2 = str2.split(/\s+/);
outer:
for(var i=0;i<tokens1.length;i++) {
var token = tokens1[i];
for(var j=0;j<tokens2.length;j++) {
if(token == tokens2[j]) continue outer;
}
values.push(token);
}
return values;
}
},
/**
* @ngdoc function
* @name ng.$compile.directive.Attributes#$observe
* @methodOf ng.$compile.directive.Attributes
* @function
*
* @description
* Observes an interpolated attribute.
*
* The observer function will be invoked once during the next `$digest` following
* compilation. The observer is then invoked whenever the interpolated value
* changes.
*
* @param {string} key Normalized key. (ie ngAttribute) .
* @param {function(interpolatedValue)} fn Function that will be called whenever
the interpolated value of the attribute changes.
* See the {@link guide/directive#Attributes Directives} guide for more info.
* @returns {function()} the `fn` parameter.
*/
$observe: function(key, fn) {
var attrs = this,
$$observers = (attrs.$$observers || (attrs.$$observers = {})),
listeners = ($$observers[key] || ($$observers[key] = []));
listeners.push(fn);
$rootScope.$evalAsync(function() {
if (!listeners.$$inter) {
// no one registered attribute interpolation function, so lets call it manually
fn(attrs[key]);
}
});
return fn;
}
};
var startSymbol = $interpolate.startSymbol(),
endSymbol = $interpolate.endSymbol(),
denormalizeTemplate = (startSymbol == '{{' || endSymbol == '}}')
? identity
: function denormalizeTemplate(template) {
return template.replace(/\{\{/g, startSymbol).replace(/}}/g, endSymbol);
},
NG_ATTR_BINDING = /^ngAttr[A-Z]/;
return compile;
//================================
function compile($compileNodes, transcludeFn, maxPriority, ignoreDirective,
previousCompileContext) {
if (!($compileNodes instanceof jqLite)) {
// jquery always rewraps, whereas we need to preserve the original selector so that we can
// modify it.
$compileNodes = jqLite($compileNodes);
}
// We can not compile top level text elements since text nodes can be merged and we will
// not be able to attach scope data to them, so we will wrap them in <span>
forEach($compileNodes, function(node, index){
if (node.nodeType == 3 /* text node */ && node.nodeValue.match(/\S+/) /* non-empty */ ) {
$compileNodes[index] = node = jqLite(node).wrap('<span></span>').parent()[0];
}
});
var compositeLinkFn =
compileNodes($compileNodes, transcludeFn, $compileNodes,
maxPriority, ignoreDirective, previousCompileContext);
return function publicLinkFn(scope, cloneConnectFn){
assertArg(scope, 'scope');
// important!!: we must call our jqLite.clone() since the jQuery one is trying to be smart
// and sometimes changes the structure of the DOM.
var $linkNode = cloneConnectFn
? JQLitePrototype.clone.call($compileNodes) // IMPORTANT!!!
: $compileNodes;
// Attach scope only to non-text nodes.
for(var i = 0, ii = $linkNode.length; i<ii; i++) {
var node = $linkNode[i];
if (node.nodeType == 1 /* element */ || node.nodeType == 9 /* document */) {
$linkNode.eq(i).data('$scope', scope);
}
}
safeAddClass($linkNode, 'ng-scope');
if (cloneConnectFn) cloneConnectFn($linkNode, scope);
if (compositeLinkFn) compositeLinkFn(scope, $linkNode, $linkNode);
return $linkNode;
};
}
function safeAddClass($element, className) {
try {
$element.addClass(className);
} catch(e) {
// ignore, since it means that we are trying to set class on
// SVG element, where class name is read-only.
}
}
/**
* Compile function matches each node in nodeList against the directives. Once all directives
* for a particular node are collected their compile functions are executed. The compile
* functions return values - the linking functions - are combined into a composite linking
* function, which is the a linking function for the node.
*
* @param {NodeList} nodeList an array of nodes or NodeList to compile
* @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the
* scope argument is auto-generated to the new child of the transcluded parent scope.
* @param {DOMElement=} $rootElement If the nodeList is the root of the compilation tree then
* the rootElement must be set the jqLite collection of the compile root. This is
* needed so that the jqLite collection items can be replaced with widgets.
* @param {number=} max directive priority
* @returns {?function} A composite linking function of all of the matched directives or null.
*/
function compileNodes(nodeList, transcludeFn, $rootElement, maxPriority, ignoreDirective,
previousCompileContext) {
var linkFns = [],
nodeLinkFn, childLinkFn, directives, attrs, linkFnFound;
for(var i = 0; i < nodeList.length; i++) {
attrs = new Attributes();
// we must always refer to nodeList[i] since the nodes can be replaced underneath us.
directives = collectDirectives(nodeList[i], [], attrs, i === 0 ? maxPriority : undefined,
ignoreDirective);
nodeLinkFn = (directives.length)
? applyDirectivesToNode(directives, nodeList[i], attrs, transcludeFn, $rootElement,
null, [], [], previousCompileContext)
: null;
childLinkFn = (nodeLinkFn && nodeLinkFn.terminal ||
!nodeList[i].childNodes ||
!nodeList[i].childNodes.length)
? null
: compileNodes(nodeList[i].childNodes,
nodeLinkFn ? nodeLinkFn.transclude : transcludeFn);
linkFns.push(nodeLinkFn);
linkFns.push(childLinkFn);
linkFnFound = (linkFnFound || nodeLinkFn || childLinkFn);
//use the previous context only for the first element in the virtual group
previousCompileContext = null;
}
// return a linking function if we have found anything, null otherwise
return linkFnFound ? compositeLinkFn : null;
function compositeLinkFn(scope, nodeList, $rootElement, boundTranscludeFn) {
var nodeLinkFn, childLinkFn, node, $node, childScope, childTranscludeFn, i, ii, n;
// copy nodeList so that linking doesn't break due to live list updates.
var stableNodeList = [];
for (i = 0, ii = nodeList.length; i < ii; i++) {
stableNodeList.push(nodeList[i]);
}
for(i = 0, n = 0, ii = linkFns.length; i < ii; n++) {
node = stableNodeList[n];
nodeLinkFn = linkFns[i++];
childLinkFn = linkFns[i++];
$node = jqLite(node);
if (nodeLinkFn) {
if (nodeLinkFn.scope) {
childScope = scope.$new();
$node.data('$scope', childScope);
safeAddClass($node, 'ng-scope');
} else {
childScope = scope;
}
childTranscludeFn = nodeLinkFn.transclude;
if (childTranscludeFn || (!boundTranscludeFn && transcludeFn)) {
nodeLinkFn(childLinkFn, childScope, node, $rootElement,
(function(transcludeFn) {
return function(cloneFn) {
var transcludeScope = scope.$new();
transcludeScope.$$transcluded = true;
return transcludeFn(transcludeScope, cloneFn).
on('$destroy', bind(transcludeScope, transcludeScope.$destroy));
};
})(childTranscludeFn || transcludeFn)
);
} else {
nodeLinkFn(childLinkFn, childScope, node, undefined, boundTranscludeFn);
}
} else if (childLinkFn) {
childLinkFn(scope, node.childNodes, undefined, boundTranscludeFn);
}
}
}
}
/**
* Looks for directives on the given node and adds them to the directive collection which is
* sorted.
*
* @param node Node to search.
* @param directives An array to which the directives are added to. This array is sorted before
* the function returns.
* @param attrs The shared attrs object which is used to populate the normalized attributes.
* @param {number=} maxPriority Max directive priority.
*/
function collectDirectives(node, directives, attrs, maxPriority, ignoreDirective) {
var nodeType = node.nodeType,
attrsMap = attrs.$attr,
match,
className;
switch(nodeType) {
case 1: /* Element */
// use the node name: <directive>
addDirective(directives,
directiveNormalize(nodeName_(node).toLowerCase()), 'E', maxPriority, ignoreDirective);
// iterate over the attributes
for (var attr, name, nName, ngAttrName, value, nAttrs = node.attributes,
j = 0, jj = nAttrs && nAttrs.length; j < jj; j++) {
var attrStartName = false;
var attrEndName = false;
attr = nAttrs[j];
if (!msie || msie >= 8 || attr.specified) {
name = attr.name;
// support ngAttr attribute binding
ngAttrName = directiveNormalize(name);
if (NG_ATTR_BINDING.test(ngAttrName)) {
name = snake_case(ngAttrName.substr(6), '-');
}
var directiveNName = ngAttrName.replace(/(Start|End)$/, '');
if (ngAttrName === directiveNName + 'Start') {
attrStartName = name;
attrEndName = name.substr(0, name.length - 5) + 'end';
name = name.substr(0, name.length - 6);
}
nName = directiveNormalize(name.toLowerCase());
attrsMap[nName] = name;
attrs[nName] = value = trim((msie && name == 'href')
? decodeURIComponent(node.getAttribute(name, 2))
: attr.value);
if (getBooleanAttrName(node, nName)) {
attrs[nName] = true; // presence means true
}
addAttrInterpolateDirective(node, directives, value, nName);
addDirective(directives, nName, 'A', maxPriority, ignoreDirective, attrStartName,
attrEndName);
}
}
// use class as directive
className = node.className;
if (isString(className) && className !== '') {
while (match = CLASS_DIRECTIVE_REGEXP.exec(className)) {
nName = directiveNormalize(match[2]);
if (addDirective(directives, nName, 'C', maxPriority, ignoreDirective)) {
attrs[nName] = trim(match[3]);
}
className = className.substr(match.index + match[0].length);
}
}
break;
case 3: /* Text Node */
addTextInterpolateDirective(directives, node.nodeValue);
break;
case 8: /* Comment */
try {
match = COMMENT_DIRECTIVE_REGEXP.exec(node.nodeValue);
if (match) {
nName = directiveNormalize(match[1]);
if (addDirective(directives, nName, 'M', maxPriority, ignoreDirective)) {
attrs[nName] = trim(match[2]);
}
}
} catch (e) {
// turns out that under some circumstances IE9 throws errors when one attempts to read
// comment's node value.
// Just ignore it and continue. (Can't seem to reproduce in test case.)
}
break;
}
directives.sort(byPriority);
return directives;
}
/**
* Given a node with an directive-start it collects all of the siblings until it finds
* directive-end.
* @param node
* @param attrStart
* @param attrEnd
* @returns {*}
*/
function groupScan(node, attrStart, attrEnd) {
var nodes = [];
var depth = 0;
if (attrStart && node.hasAttribute && node.hasAttribute(attrStart)) {
var startNode = node;
do {
if (!node) {
throw $compileMinErr('uterdir',
"Unterminated attribute, found '{0}' but no matching '{1}' found.",
attrStart, attrEnd);
}
if (node.nodeType == 1 /** Element **/) {
if (node.hasAttribute(attrStart)) depth++;
if (node.hasAttribute(attrEnd)) depth--;
}
nodes.push(node);
node = node.nextSibling;
} while (depth > 0);
} else {
nodes.push(node);
}
return jqLite(nodes);
}
/**
* Wrapper for linking function which converts normal linking function into a grouped
* linking function.
* @param linkFn
* @param attrStart
* @param attrEnd
* @returns {Function}
*/
function groupElementsLinkFnWrapper(linkFn, attrStart, attrEnd) {
return function(scope, element, attrs, controllers) {
element = groupScan(element[0], attrStart, attrEnd);
return linkFn(scope, element, attrs, controllers);
};
}
/**
* Once the directives have been collected, their compile functions are executed. This method
* is responsible for inlining directive templates as well as terminating the application
* of the directives if the terminal directive has been reached.
*
* @param {Array} directives Array of collected directives to execute their compile function.
* this needs to be pre-sorted by priority order.
* @param {Node} compileNode The raw DOM node to apply the compile functions to
* @param {Object} templateAttrs The shared attribute function
* @param {function(angular.Scope[, cloneAttachFn]} transcludeFn A linking function, where the
* scope argument is auto-generated to the new
* child of the transcluded parent scope.
* @param {JQLite} jqCollection If we are working on the root of the compile tree then this
* argument has the root jqLite array so that we can replace nodes
* on it.
* @param {Object=} originalReplaceDirective An optional directive that will be ignored when
* compiling the transclusion.
* @param {Array.<Function>} preLinkFns
* @param {Array.<Function>} postLinkFns
* @param {Object} previousCompileContext Context used for previous compilation of the current
* node
* @returns linkFn
*/
function applyDirectivesToNode(directives, compileNode, templateAttrs, transcludeFn,
jqCollection, originalReplaceDirective, preLinkFns, postLinkFns,
previousCompileContext) {
previousCompileContext = previousCompileContext || {};
var terminalPriority = -Number.MAX_VALUE,
newScopeDirective,
controllerDirectives = previousCompileContext.controllerDirectives,
newIsolateScopeDirective = previousCompileContext.newIsolateScopeDirective,
templateDirective = previousCompileContext.templateDirective,
transcludeDirective = previousCompileContext.transcludeDirective,
$compileNode = templateAttrs.$$element = jqLite(compileNode),
directive,
directiveName,
$template,
replaceDirective = originalReplaceDirective,
childTranscludeFn = transcludeFn,
linkFn,
directiveValue;
// executes all directives on the current element
for(var i = 0, ii = directives.length; i < ii; i++) {
directive = directives[i];
var attrStart = directive.$$start;
var attrEnd = directive.$$end;
// collect multiblock sections
if (attrStart) {
$compileNode = groupScan(compileNode, attrStart, attrEnd);
}
$template = undefined;
if (terminalPriority > directive.priority) {
break; // prevent further processing of directives
}
if (directiveValue = directive.scope) {
newScopeDirective = newScopeDirective || directive;
// skip the check for directives with async templates, we'll check the derived sync
// directive when the template arrives
if (!directive.templateUrl) {
assertNoDuplicate('new/isolated scope', newIsolateScopeDirective, directive,
$compileNode);
if (isObject(directiveValue)) {
newIsolateScopeDirective = directive;
}
}
}
directiveName = directive.name;
if (!directive.templateUrl && directive.controller) {
directiveValue = directive.controller;
controllerDirectives = controllerDirectives || {};
assertNoDuplicate("'" + directiveName + "' controller",
controllerDirectives[directiveName], directive, $compileNode);
controllerDirectives[directiveName] = directive;
}
if (directiveValue = directive.transclude) {
// Special case ngIf and ngRepeat so that we don't complain about duplicate transclusion.
// This option should only be used by directives that know how to how to safely handle element transclusion,
// where the transcluded nodes are added or replaced after linking.
if (!directive.$$tlb) {
assertNoDuplicate('transclusion', transcludeDirective, directive, $compileNode);
transcludeDirective = directive;
}
if (directiveValue == 'element') {
terminalPriority = directive.priority;
$template = groupScan(compileNode, attrStart, attrEnd);
$compileNode = templateAttrs.$$element =
jqLite(document.createComment(' ' + directiveName + ': ' +
templateAttrs[directiveName] + ' '));
compileNode = $compileNode[0];
replaceWith(jqCollection, jqLite(sliceArgs($template)), compileNode);
childTranscludeFn = compile($template, transcludeFn, terminalPriority,
replaceDirective && replaceDirective.name, {
// Don't pass in:
// - controllerDirectives - otherwise we'll create duplicates controllers
// - newIsolateScopeDirective or templateDirective - combining templates with
// element transclusion doesn't make sense.
//
// We need only transcludeDirective so that we prevent putting transclusion
// on the same element more than once.
transcludeDirective: transcludeDirective
});
} else {
$template = jqLite(jqLiteClone(compileNode)).contents();
$compileNode.html(''); // clear contents
childTranscludeFn = compile($template, transcludeFn);
}
}
if (directive.template) {
assertNoDuplicate('template', templateDirective, directive, $compileNode);
templateDirective = directive;
directiveValue = (isFunction(directive.template))
? directive.template($compileNode, templateAttrs)
: directive.template;
directiveValue = denormalizeTemplate(directiveValue);
if (directive.replace) {
replaceDirective = directive;
$template = jqLite('<div>' +
trim(directiveValue) +
'</div>').contents();
compileNode = $template[0];
if ($template.length != 1 || compileNode.nodeType !== 1) {
throw $compileMinErr('tplrt',
"Template for directive '{0}' must have exactly one root element. {1}",
directiveName, '');
}
replaceWith(jqCollection, $compileNode, compileNode);
var newTemplateAttrs = {$attr: {}};
// combine directives from the original node and from the template:
// - take the array of directives for this element
// - split it into two parts, those that already applied (processed) and those that weren't (unprocessed)
// - collect directives from the template and sort them by priority
// - combine directives as: processed + template + unprocessed
var templateDirectives = collectDirectives(compileNode, [], newTemplateAttrs);
var unprocessedDirectives = directives.splice(i + 1, directives.length - (i + 1));
if (newIsolateScopeDirective) {
markDirectivesAsIsolate(templateDirectives);
}
directives = directives.concat(templateDirectives).concat(unprocessedDirectives);
mergeTemplateAttributes(templateAttrs, newTemplateAttrs);
ii = directives.length;
} else {
$compileNode.html(directiveValue);
}
}
if (directive.templateUrl) {
assertNoDuplicate('template', templateDirective, directive, $compileNode);
templateDirective = directive;
if (directive.replace) {
replaceDirective = directive;
}
nodeLinkFn = compileTemplateUrl(directives.splice(i, directives.length - i), $compileNode,
templateAttrs, jqCollection, childTranscludeFn, preLinkFns, postLinkFns, {
controllerDirectives: controllerDirectives,
newIsolateScopeDirective: newIsolateScopeDirective,
templateDirective: templateDirective,
transcludeDirective: transcludeDirective
});
ii = directives.length;
} else if (directive.compile) {
try {
linkFn = directive.compile($compileNode, templateAttrs, childTranscludeFn);
if (isFunction(linkFn)) {
addLinkFns(null, linkFn, attrStart, attrEnd);
} else if (linkFn) {
addLinkFns(linkFn.pre, linkFn.post, attrStart, attrEnd);
}
} catch (e) {
$exceptionHandler(e, startingTag($compileNode));
}
}
if (directive.terminal) {
nodeLinkFn.terminal = true;
terminalPriority = Math.max(terminalPriority, directive.priority);
}
}
nodeLinkFn.scope = newScopeDirective && newScopeDirective.scope === true;
nodeLinkFn.transclude = transcludeDirective && childTranscludeFn;
// might be normal or delayed nodeLinkFn depending on if templateUrl is present
return nodeLinkFn;
////////////////////
function addLinkFns(pre, post, attrStart, attrEnd) {
if (pre) {
if (attrStart) pre = groupElementsLinkFnWrapper(pre, attrStart, attrEnd);
pre.require = directive.require;
if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
pre = cloneAndAnnotateFn(pre, {isolateScope: true});
}
preLinkFns.push(pre);
}
if (post) {
if (attrStart) post = groupElementsLinkFnWrapper(post, attrStart, attrEnd);
post.require = directive.require;
if (newIsolateScopeDirective === directive || directive.$$isolateScope) {
post = cloneAndAnnotateFn(post, {isolateScope: true});
}
postLinkFns.push(post);
}
}
function getControllers(require, $element) {
var value, retrievalMethod = 'data', optional = false;
if (isString(require)) {
while((value = require.charAt(0)) == '^' || value == '?') {
require = require.substr(1);
if (value == '^') {
retrievalMethod = 'inheritedData';
}
optional = optional || value == '?';
}
value = $element[retrievalMethod]('$' + require + 'Controller');
if ($element[0].nodeType == 8 && $element[0].$$controller) { // Transclusion comment node
value = value || $element[0].$$controller;
$element[0].$$controller = null;
}
if (!value && !optional) {
throw $compileMinErr('ctreq',
"Controller '{0}', required by directive '{1}', can't be found!",
require, directiveName);
}
return value;
} else if (isArray(require)) {
value = [];
forEach(require, function(require) {
value.push(getControllers(require, $element));
});
}
return value;
}
function nodeLinkFn(childLinkFn, scope, linkNode, $rootElement, boundTranscludeFn) {
var attrs, $element, i, ii, linkFn, controller, isolateScope;
if (compileNode === linkNode) {
attrs = templateAttrs;
} else {
attrs = shallowCopy(templateAttrs, new Attributes(jqLite(linkNode), templateAttrs.$attr));
}
$element = attrs.$$element;
if (newIsolateScopeDirective) {
var LOCAL_REGEXP = /^\s*([@=&])(\??)\s*(\w*)\s*$/;
var $linkNode = jqLite(linkNode);
isolateScope = scope.$new(true);
if (templateDirective && (templateDirective === newIsolateScopeDirective.$$originalDirective)) {
$linkNode.data('$isolateScope', isolateScope) ;
} else {
$linkNode.data('$isolateScopeNoTemplate', isolateScope);
}
safeAddClass($linkNode, 'ng-isolate-scope');
forEach(newIsolateScopeDirective.scope, function(definition, scopeName) {
var match = definition.match(LOCAL_REGEXP) || [],
attrName = match[3] || scopeName,
optional = (match[2] == '?'),
mode = match[1], // @, =, or &
lastValue,
parentGet, parentSet;
isolateScope.$$isolateBindings[scopeName] = mode + attrName;
switch (mode) {
case '@':
attrs.$observe(attrName, function(value) {
isolateScope[scopeName] = value;
});
attrs.$$observers[attrName].$$scope = scope;
if( attrs[attrName] ) {
// If the attribute has been provided then we trigger an interpolation to ensure
// the value is there for use in the link fn
isolateScope[scopeName] = $interpolate(attrs[attrName])(scope);
}
break;
case '=':
if (optional && !attrs[attrName]) {
return;
}
parentGet = $parse(attrs[attrName]);
parentSet = parentGet.assign || function() {
// reset the change, or we will throw this exception on every $digest
lastValue = isolateScope[scopeName] = parentGet(scope);
throw $compileMinErr('nonassign',
"Expression '{0}' used with directive '{1}' is non-assignable!",
attrs[attrName], newIsolateScopeDirective.name);
};
lastValue = isolateScope[scopeName] = parentGet(scope);
isolateScope.$watch(function parentValueWatch() {
var parentValue = parentGet(scope);
if (parentValue !== isolateScope[scopeName]) {
// we are out of sync and need to copy
if (parentValue !== lastValue) {
// parent changed and it has precedence
lastValue = isolateScope[scopeName] = parentValue;
} else {
// if the parent can be assigned then do so
parentSet(scope, parentValue = lastValue = isolateScope[scopeName]);
}
}
return parentValue;
});
break;
case '&':
parentGet = $parse(attrs[attrName]);
isolateScope[scopeName] = function(locals) {
return parentGet(scope, locals);
};
break;
default:
throw $compileMinErr('iscp',
"Invalid isolate scope definition for directive '{0}'." +
" Definition: {... {1}: '{2}' ...}",
newIsolateScopeDirective.name, scopeName, definition);
}
});
}
if (controllerDirectives) {
forEach(controllerDirectives, function(directive) {
var locals = {
$scope: directive === newIsolateScopeDirective || directive.$$isolateScope ? isolateScope : scope,
$element: $element,
$attrs: attrs,
$transclude: boundTranscludeFn
}, controllerInstance;
controller = directive.controller;
if (controller == '@') {
controller = attrs[directive.name];
}
controllerInstance = $controller(controller, locals);
// Directives with element transclusion and a controller need to attach controller
// to the comment node created by the compiler, but jQuery .data doesn't support
// attaching data to comment nodes so instead we set it directly on the element and
// remove it after we read it later.
if ($element[0].nodeType == 8) { // Transclusion comment node
$element[0].$$controller = controllerInstance;
} else {
$element.data('$' + directive.name + 'Controller', controllerInstance);
}
if (directive.controllerAs) {
locals.$scope[directive.controllerAs] = controllerInstance;
}
});
}
// PRELINKING
for(i = 0, ii = preLinkFns.length; i < ii; i++) {
try {
linkFn = preLinkFns[i];
linkFn(linkFn.isolateScope ? isolateScope : scope, $element, attrs,
linkFn.require && getControllers(linkFn.require, $element));
} catch (e) {
$exceptionHandler(e, startingTag($element));
}
}
// RECURSION
// We only pass the isolate scope, if the isolate directive has a template,
// otherwise the child elements do not belong to the isolate directive.
var scopeToChild = scope;
if (newIsolateScopeDirective && (newIsolateScopeDirective.template || newIsolateScopeDirective.templateUrl === null)) {
scopeToChild = isolateScope;
}
childLinkFn && childLinkFn(scopeToChild, linkNode.childNodes, undefined, boundTranscludeFn);
// POSTLINKING
for(i = postLinkFns.length - 1; i >= 0; i--) {
try {
linkFn = postLinkFns[i];
linkFn(linkFn.isolateScope ? isolateScope : scope, $element, attrs,
linkFn.require && getControllers(linkFn.require, $element));
} catch (e) {
$exceptionHandler(e, startingTag($element));
}
}
}
}
function markDirectivesAsIsolate(directives) {
// mark all directives as needing isolate scope.
for (var j = 0, jj = directives.length; j < jj; j++) {
directives[j] = inherit(directives[j], {$$isolateScope: true});
}
}
/**
* looks up the directive and decorates it with exception handling and proper parameters. We
* call this the boundDirective.
*
* @param {string} name name of the directive to look up.
* @param {string} location The directive must be found in specific format.
* String containing any of theses characters:
*
* * `E`: element name
* * `A': attribute
* * `C`: class
* * `M`: comment
* @returns true if directive was added.
*/
function addDirective(tDirectives, name, location, maxPriority, ignoreDirective, startAttrName,
endAttrName) {
if (name === ignoreDirective) return null;
var match = null;
if (hasDirectives.hasOwnProperty(name)) {
for(var directive, directives = $injector.get(name + Suffix),
i = 0, ii = directives.length; i<ii; i++) {
try {
directive = directives[i];
if ( (maxPriority === undefined || maxPriority > directive.priority) &&
directive.restrict.indexOf(location) != -1) {
if (startAttrName) {
directive = inherit(directive, {$$start: startAttrName, $$end: endAttrName});
}
tDirectives.push(directive);
match = directive;
}
} catch(e) { $exceptionHandler(e); }
}
}
return match;
}
/**
* When the element is replaced with HTML template then the new attributes
* on the template need to be merged with the existing attributes in the DOM.
* The desired effect is to have both of the attributes present.
*
* @param {object} dst destination attributes (original DOM)
* @param {object} src source attributes (from the directive template)
*/
function mergeTemplateAttributes(dst, src) {
var srcAttr = src.$attr,
dstAttr = dst.$attr,
$element = dst.$$element;
// reapply the old attributes to the new element
forEach(dst, function(value, key) {
if (key.charAt(0) != '$') {
if (src[key]) {
value += (key === 'style' ? ';' : ' ') + src[key];
}
dst.$set(key, value, true, srcAttr[key]);
}
});
// copy the new attributes on the old attrs object
forEach(src, function(value, key) {
if (key == 'class') {
safeAddClass($element, value);
dst['class'] = (dst['class'] ? dst['class'] + ' ' : '') + value;
} else if (key == 'style') {
$element.attr('style', $element.attr('style') + ';' + value);
// `dst` will never contain hasOwnProperty as DOM parser won't let it.
// You will get an "InvalidCharacterError: DOM Exception 5" error if you
// have an attribute like "has-own-property" or "data-has-own-property", etc.
} else if (key.charAt(0) != '$' && !dst.hasOwnProperty(key)) {
dst[key] = value;
dstAttr[key] = srcAttr[key];
}
});
}
function compileTemplateUrl(directives, $compileNode, tAttrs,
$rootElement, childTranscludeFn, preLinkFns, postLinkFns, previousCompileContext) {
var linkQueue = [],
afterTemplateNodeLinkFn,
afterTemplateChildLinkFn,
beforeTemplateCompileNode = $compileNode[0],
origAsyncDirective = directives.shift(),
// The fact that we have to copy and patch the directive seems wrong!
derivedSyncDirective = extend({}, origAsyncDirective, {
templateUrl: null, transclude: null, replace: null, $$originalDirective: origAsyncDirective
}),
templateUrl = (isFunction(origAsyncDirective.templateUrl))
? origAsyncDirective.templateUrl($compileNode, tAttrs)
: origAsyncDirective.templateUrl;
$compileNode.html('');
$http.get($sce.getTrustedResourceUrl(templateUrl), {cache: $templateCache}).
success(function(content) {
var compileNode, tempTemplateAttrs, $template;
content = denormalizeTemplate(content);
if (origAsyncDirective.replace) {
$template = jqLite('<div>' + trim(content) + '</div>').contents();
compileNode = $template[0];
if ($template.length != 1 || compileNode.nodeType !== 1) {
throw $compileMinErr('tplrt',
"Template for directive '{0}' must have exactly one root element. {1}",
origAsyncDirective.name, templateUrl);
}
tempTemplateAttrs = {$attr: {}};
replaceWith($rootElement, $compileNode, compileNode);
var templateDirectives = collectDirectives(compileNode, [], tempTemplateAttrs);
if (isObject(origAsyncDirective.scope)) {
markDirectivesAsIsolate(templateDirectives);
}
directives = templateDirectives.concat(directives);
mergeTemplateAttributes(tAttrs, tempTemplateAttrs);
} else {
compileNode = beforeTemplateCompileNode;
$compileNode.html(content);
}
directives.unshift(derivedSyncDirective);
afterTemplateNodeLinkFn = applyDirectivesToNode(directives, compileNode, tAttrs,
childTranscludeFn, $compileNode, origAsyncDirective, preLinkFns, postLinkFns,
previousCompileContext);
forEach($rootElement, function(node, i) {
if (node == compileNode) {
$rootElement[i] = $compileNode[0];
}
});
afterTemplateChildLinkFn = compileNodes($compileNode[0].childNodes, childTranscludeFn);
while(linkQueue.length) {
var scope = linkQueue.shift(),
beforeTemplateLinkNode = linkQueue.shift(),
linkRootElement = linkQueue.shift(),
controller = linkQueue.shift(),
linkNode = $compileNode[0];
if (beforeTemplateLinkNode !== beforeTemplateCompileNode) {
// it was cloned therefore we have to clone as well.
linkNode = jqLiteClone(compileNode);
replaceWith(linkRootElement, jqLite(beforeTemplateLinkNode), linkNode);
}
afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, linkNode, $rootElement,
controller);
}
linkQueue = null;
}).
error(function(response, code, headers, config) {
throw $compileMinErr('tpload', 'Failed to load template: {0}', config.url);
});
return function delayedNodeLinkFn(ignoreChildLinkFn, scope, node, rootElement, controller) {
if (linkQueue) {
linkQueue.push(scope);
linkQueue.push(node);
linkQueue.push(rootElement);
linkQueue.push(controller);
} else {
afterTemplateNodeLinkFn(afterTemplateChildLinkFn, scope, node, rootElement, controller);
}
};
}
/**
* Sorting function for bound directives.
*/
function byPriority(a, b) {
var diff = b.priority - a.priority;
if (diff !== 0) return diff;
if (a.name !== b.name) return (a.name < b.name) ? -1 : 1;
return a.index - b.index;
}
function assertNoDuplicate(what, previousDirective, directive, element) {
if (previousDirective) {
throw $compileMinErr('multidir', 'Multiple directives [{0}, {1}] asking for {2} on: {3}',
previousDirective.name, directive.name, what, startingTag(element));
}
}
function addTextInterpolateDirective(directives, text) {
var interpolateFn = $interpolate(text, true);
if (interpolateFn) {
directives.push({
priority: 0,
compile: valueFn(function textInterpolateLinkFn(scope, node) {
var parent = node.parent(),
bindings = parent.data('$binding') || [];
bindings.push(interpolateFn);
safeAddClass(parent.data('$binding', bindings), 'ng-binding');
scope.$watch(interpolateFn, function interpolateFnWatchAction(value) {
node[0].nodeValue = value;
});
})
});
}
}
function getTrustedContext(node, attrNormalizedName) {
// maction[xlink:href] can source SVG. It's not limited to <maction>.
if (attrNormalizedName == "xlinkHref" ||
(nodeName_(node) != "IMG" && (attrNormalizedName == "src" ||
attrNormalizedName == "ngSrc"))) {
return $sce.RESOURCE_URL;
}
}
function addAttrInterpolateDirective(node, directives, value, name) {
var interpolateFn = $interpolate(value, true);
// no interpolation found -> ignore
if (!interpolateFn) return;
if (name === "multiple" && nodeName_(node) === "SELECT") {
throw $compileMinErr("selmulti",
"Binding to the 'multiple' attribute is not supported. Element: {0}",
startingTag(node));
}
directives.push({
priority: 100,
compile: function() {
return {
pre: function attrInterpolatePreLinkFn(scope, element, attr) {
var $$observers = (attr.$$observers || (attr.$$observers = {}));
if (EVENT_HANDLER_ATTR_REGEXP.test(name)) {
throw $compileMinErr('nodomevents',
"Interpolations for HTML DOM event attributes are disallowed. Please use the " +
"ng- versions (such as ng-click instead of onclick) instead.");
}
// we need to interpolate again, in case the attribute value has been updated
// (e.g. by another directive's compile function)
interpolateFn = $interpolate(attr[name], true, getTrustedContext(node, name));
// if attribute was updated so that there is no interpolation going on we don't want to
// register any observers
if (!interpolateFn) return;
// TODO(i): this should likely be attr.$set(name, iterpolateFn(scope) so that we reset the
// actual attr value
attr[name] = interpolateFn(scope);
($$observers[name] || ($$observers[name] = [])).$$inter = true;
(attr.$$observers && attr.$$observers[name].$$scope || scope).
$watch(interpolateFn, function interpolateFnWatchAction(value) {
attr.$set(name, value);
});
}
};
}
});
}
/**
* This is a special jqLite.replaceWith, which can replace items which
* have no parents, provided that the containing jqLite collection is provided.
*
* @param {JqLite=} $rootElement The root of the compile tree. Used so that we can replace nodes
* in the root of the tree.
* @param {JqLite} elementsToRemove The jqLite element which we are going to replace. We keep
* the shell, but replace its DOM node reference.
* @param {Node} newNode The new DOM node.
*/
function replaceWith($rootElement, elementsToRemove, newNode) {
var firstElementToRemove = elementsToRemove[0],
removeCount = elementsToRemove.length,
parent = firstElementToRemove.parentNode,
i, ii;
if ($rootElement) {
for(i = 0, ii = $rootElement.length; i < ii; i++) {
if ($rootElement[i] == firstElementToRemove) {
$rootElement[i++] = newNode;
for (var j = i, j2 = j + removeCount - 1,
jj = $rootElement.length;
j < jj; j++, j2++) {
if (j2 < jj) {
$rootElement[j] = $rootElement[j2];
} else {
delete $rootElement[j];
}
}
$rootElement.length -= removeCount - 1;
break;
}
}
}
if (parent) {
parent.replaceChild(newNode, firstElementToRemove);
}
var fragment = document.createDocumentFragment();
fragment.appendChild(firstElementToRemove);
newNode[jqLite.expando] = firstElementToRemove[jqLite.expando];
for (var k = 1, kk = elementsToRemove.length; k < kk; k++) {
var element = elementsToRemove[k];
jqLite(element).remove(); // must do this way to clean up expando
fragment.appendChild(element);
delete elementsToRemove[k];
}
elementsToRemove[0] = newNode;
elementsToRemove.length = 1;
}
function cloneAndAnnotateFn(fn, annotation) {
return extend(function() { return fn.apply(null, arguments); }, fn, annotation);
}
}];
}
var PREFIX_REGEXP = /^(x[\:\-_]|data[\:\-_])/i;
/**
* Converts all accepted directives format into proper directive name.
* All of these will become 'myDirective':
* my:Directive
* my-directive
* x-my-directive
* data-my:directive
*
* Also there is special case for Moz prefix starting with upper case letter.
* @param name Name to normalize
*/
function directiveNormalize(name) {
return camelCase(name.replace(PREFIX_REGEXP, ''));
}
/**
* @ngdoc object
* @name ng.$compile.directive.Attributes
*
* @description
* A shared object between directive compile / linking functions which contains normalized DOM
* element attributes. The values reflect current binding state `{{ }}`. The normalization is
* needed since all of these are treated as equivalent in Angular:
*
* <span ng:bind="a" ng-bind="a" data-ng-bind="a" x-ng-bind="a">
*/
/**
* @ngdoc property
* @name ng.$compile.directive.Attributes#$attr
* @propertyOf ng.$compile.directive.Attributes
* @returns {object} A map of DOM element attribute names to the normalized name. This is
* needed to do reverse lookup from normalized name back to actual name.
*/
/**
* @ngdoc function
* @name ng.$compile.directive.Attributes#$set
* @methodOf ng.$compile.directive.Attributes
* @function
*
* @description
* Set DOM element attribute value.
*
*
* @param {string} name Normalized element attribute name of the property to modify. The name is
* revers translated using the {@link ng.$compile.directive.Attributes#$attr $attr}
* property to the original name.
* @param {string} value Value to set the attribute to. The value can be an interpolated string.
*/
/**
* Closure compiler type information
*/
function nodesetLinkingFn(
/* angular.Scope */ scope,
/* NodeList */ nodeList,
/* Element */ rootElement,
/* function(Function) */ boundTranscludeFn
){}
function directiveLinkingFn(
/* nodesetLinkingFn */ nodesetLinkingFn,
/* angular.Scope */ scope,
/* Node */ node,
/* Element */ rootElement,
/* function(Function) */ boundTranscludeFn
){}
/**
* @ngdoc object
* @name ng.$controllerProvider
* @description
* The {@link ng.$controller $controller service} is used by Angular to create new
* controllers.
*
* This provider allows controller registration via the
* {@link ng.$controllerProvider#methods_register register} method.
*/
function $ControllerProvider() {
var controllers = {},
CNTRL_REG = /^(\S+)(\s+as\s+(\w+))?$/;
/**
* @ngdoc function
* @name ng.$controllerProvider#register
* @methodOf ng.$controllerProvider
* @param {string|Object} name Controller name, or an object map of controllers where the keys are
* the names and the values are the constructors.
* @param {Function|Array} constructor Controller constructor fn (optionally decorated with DI
* annotations in the array notation).
*/
this.register = function(name, constructor) {
assertNotHasOwnProperty(name, 'controller');
if (isObject(name)) {
extend(controllers, name);
} else {
controllers[name] = constructor;
}
};
this.$get = ['$injector', '$window', function($injector, $window) {
/**
* @ngdoc function
* @name ng.$controller
* @requires $injector
*
* @param {Function|string} constructor If called with a function then it's considered to be the
* controller constructor function. Otherwise it's considered to be a string which is used
* to retrieve the controller constructor using the following steps:
*
* * check if a controller with given name is registered via `$controllerProvider`
* * check if evaluating the string on the current scope returns a constructor
* * check `window[constructor]` on the global `window` object
*
* @param {Object} locals Injection locals for Controller.
* @return {Object} Instance of given controller.
*
* @description
* `$controller` service is responsible for instantiating controllers.
*
* It's just a simple call to {@link AUTO.$injector $injector}, but extracted into
* a service, so that one can override this service with {@link https://gist.github.com/1649788
* BC version}.
*/
return function(expression, locals) {
var instance, match, constructor, identifier;
if(isString(expression)) {
match = expression.match(CNTRL_REG),
constructor = match[1],
identifier = match[3];
expression = controllers.hasOwnProperty(constructor)
? controllers[constructor]
: getter(locals.$scope, constructor, true) || getter($window, constructor, true);
assertArgFn(expression, constructor, true);
}
instance = $injector.instantiate(expression, locals);
if (identifier) {
if (!(locals && typeof locals.$scope == 'object')) {
throw minErr('$controller')('noscp',
"Cannot export controller '{0}' as '{1}'! No $scope object provided via `locals`.",
constructor || expression.name, identifier);
}
locals.$scope[identifier] = instance;
}
return instance;
};
}];
}
/**
* @ngdoc object
* @name ng.$document
* @requires $window
*
* @description
* A {@link angular.element jQuery (lite)}-wrapped reference to the browser's `window.document`
* element.
*/
function $DocumentProvider(){
this.$get = ['$window', function(window){
return jqLite(window.document);
}];
}
/**
* @ngdoc function
* @name ng.$exceptionHandler
* @requires $log
*
* @description
* Any uncaught exception in angular expressions is delegated to this service.
* The default implementation simply delegates to `$log.error` which logs it into
* the browser console.
*
* In unit tests, if `angular-mocks.js` is loaded, this service is overridden by
* {@link ngMock.$exceptionHandler mock $exceptionHandler} which aids in testing.
*
* ## Example:
*
* <pre>
* angular.module('exceptionOverride', []).factory('$exceptionHandler', function () {
* return function (exception, cause) {
* exception.message += ' (caused by "' + cause + '")';
* throw exception;
* };
* });
* </pre>
*
* This example will override the normal action of `$exceptionHandler`, to make angular
* exceptions fail hard when they happen, instead of just logging to the console.
*
* @param {Error} exception Exception associated with the error.
* @param {string=} cause optional information about the context in which
* the error was thrown.
*
*/
function $ExceptionHandlerProvider() {
this.$get = ['$log', function($log) {
return function(exception, cause) {
$log.error.apply($log, arguments);
};
}];
}
/**
* Parse headers into key value object
*
* @param {string} headers Raw headers as a string
* @returns {Object} Parsed headers as key value object
*/
function parseHeaders(headers) {
var parsed = {}, key, val, i;
if (!headers) return parsed;
forEach(headers.split('\n'), function(line) {
i = line.indexOf(':');
key = lowercase(trim(line.substr(0, i)));
val = trim(line.substr(i + 1));
if (key) {
if (parsed[key]) {
parsed[key] += ', ' + val;
} else {
parsed[key] = val;
}
}
});
return parsed;
}
/**
* Returns a function that provides access to parsed headers.
*
* Headers are lazy parsed when first requested.
* @see parseHeaders
*
* @param {(string|Object)} headers Headers to provide access to.
* @returns {function(string=)} Returns a getter function which if called with:
*
* - if called with single an argument returns a single header value or null
* - if called with no arguments returns an object containing all headers.
*/
function headersGetter(headers) {
var headersObj = isObject(headers) ? headers : undefined;
return function(name) {
if (!headersObj) headersObj = parseHeaders(headers);
if (name) {
return headersObj[lowercase(name)] || null;
}
return headersObj;
};
}
/**
* Chain all given functions
*
* This function is used for both request and response transforming
*
* @param {*} data Data to transform.
* @param {function(string=)} headers Http headers getter fn.
* @param {(function|Array.<function>)} fns Function or an array of functions.
* @returns {*} Transformed data.
*/
function transformData(data, headers, fns) {
if (isFunction(fns))
return fns(data, headers);
forEach(fns, function(fn) {
data = fn(data, headers);
});
return data;
}
function isSuccess(status) {
return 200 <= status && status < 300;
}
function $HttpProvider() {
var JSON_START = /^\s*(\[|\{[^\{])/,
JSON_END = /[\}\]]\s*$/,
PROTECTION_PREFIX = /^\)\]\}',?\n/,
CONTENT_TYPE_APPLICATION_JSON = {'Content-Type': 'application/json;charset=utf-8'};
var defaults = this.defaults = {
// transform incoming response data
transformResponse: [function(data) {
if (isString(data)) {
// strip json vulnerability protection prefix
data = data.replace(PROTECTION_PREFIX, '');
if (JSON_START.test(data) && JSON_END.test(data))
data = fromJson(data);
}
return data;
}],
// transform outgoing request data
transformRequest: [function(d) {
return isObject(d) && !isFile(d) ? toJson(d) : d;
}],
// default headers
headers: {
common: {
'Accept': 'application/json, text/plain, */*'
},
post: CONTENT_TYPE_APPLICATION_JSON,
put: CONTENT_TYPE_APPLICATION_JSON,
patch: CONTENT_TYPE_APPLICATION_JSON
},
xsrfCookieName: 'XSRF-TOKEN',
xsrfHeaderName: 'X-XSRF-TOKEN'
};
/**
* Are ordered by request, i.e. they are applied in the same order as the
* array, on request, but reverse order, on response.
*/
var interceptorFactories = this.interceptors = [];
/**
* For historical reasons, response interceptors are ordered by the order in which
* they are applied to the response. (This is the opposite of interceptorFactories)
*/
var responseInterceptorFactories = this.responseInterceptors = [];
this.$get = ['$httpBackend', '$browser', '$cacheFactory', '$rootScope', '$q', '$injector',
function($httpBackend, $browser, $cacheFactory, $rootScope, $q, $injector) {
var defaultCache = $cacheFactory('$http');
/**
* Interceptors stored in reverse order. Inner interceptors before outer interceptors.
* The reversal is needed so that we can build up the interception chain around the
* server request.
*/
var reversedInterceptors = [];
forEach(interceptorFactories, function(interceptorFactory) {
reversedInterceptors.unshift(isString(interceptorFactory)
? $injector.get(interceptorFactory) : $injector.invoke(interceptorFactory));
});
forEach(responseInterceptorFactories, function(interceptorFactory, index) {
var responseFn = isString(interceptorFactory)
? $injector.get(interceptorFactory)
: $injector.invoke(interceptorFactory);
/**
* Response interceptors go before "around" interceptors (no real reason, just
* had to pick one.) But they are already reversed, so we can't use unshift, hence
* the splice.
*/
reversedInterceptors.splice(index, 0, {
response: function(response) {
return responseFn($q.when(response));
},
responseError: function(response) {
return responseFn($q.reject(response));
}
});
});
/**
* @ngdoc function
* @name ng.$http
* @requires $httpBackend
* @requires $browser
* @requires $cacheFactory
* @requires $rootScope
* @requires $q
* @requires $injector
*
* @description
* The `$http` service is a core Angular service that facilitates communication with the remote
* HTTP servers via the browser's {@link https://developer.mozilla.org/en/xmlhttprequest
* XMLHttpRequest} object or via {@link http://en.wikipedia.org/wiki/JSONP JSONP}.
*
* For unit testing applications that use `$http` service, see
* {@link ngMock.$httpBackend $httpBackend mock}.
*
* For a higher level of abstraction, please check out the {@link ngResource.$resource
* $resource} service.
*
* The $http API is based on the {@link ng.$q deferred/promise APIs} exposed by
* the $q service. While for simple usage patterns this doesn't matter much, for advanced usage
* it is important to familiarize yourself with these APIs and the guarantees they provide.
*
*
* # General usage
* The `$http` service is a function which takes a single argument — a configuration object —
* that is used to generate an HTTP request and returns a {@link ng.$q promise}
* with two $http specific methods: `success` and `error`.
*
* <pre>
* $http({method: 'GET', url: '/someUrl'}).
* success(function(data, status, headers, config) {
* // this callback will be called asynchronously
* // when the response is available
* }).
* error(function(data, status, headers, config) {
* // called asynchronously if an error occurs
* // or server returns response with an error status.
* });
* </pre>
*
* Since the returned value of calling the $http function is a `promise`, you can also use
* the `then` method to register callbacks, and these callbacks will receive a single argument –
* an object representing the response. See the API signature and type info below for more
* details.
*
* A response status code between 200 and 299 is considered a success status and
* will result in the success callback being called. Note that if the response is a redirect,
* XMLHttpRequest will transparently follow it, meaning that the error callback will not be
* called for such responses.
*
* # Calling $http from outside AngularJS
* The `$http` service will not actually send the request until the next `$digest()` is
* executed. Normally this is not an issue, since almost all the time your call to `$http` will
* be from within a `$apply()` block.
* If you are calling `$http` from outside Angular, then you should wrap it in a call to
* `$apply` to cause a $digest to occur and also to handle errors in the block correctly.
*
* ```
* $scope.$apply(function() {
* $http(...);
* });
* ```
*
* # Writing Unit Tests that use $http
* When unit testing you are mostly responsible for scheduling the `$digest` cycle. If you do
* not trigger a `$digest` before calling `$httpBackend.flush()` then the request will not have
* been made and `$httpBackend.expect(...)` expectations will fail. The solution is to run the
* code that calls the `$http()` method inside a $apply block as explained in the previous
* section.
*
* ```
* $httpBackend.expectGET(...);
* $scope.$apply(function() {
* $http.get(...);
* });
* $httpBackend.flush();
* ```
*
* # Shortcut methods
*
* Since all invocations of the $http service require passing in an HTTP method and URL, and
* POST/PUT requests require request data to be provided as well, shortcut methods
* were created:
*
* <pre>
* $http.get('/someUrl').success(successCallback);
* $http.post('/someUrl', data).success(successCallback);
* </pre>
*
* Complete list of shortcut methods:
*
* - {@link ng.$http#methods_get $http.get}
* - {@link ng.$http#methods_head $http.head}
* - {@link ng.$http#methods_post $http.post}
* - {@link ng.$http#methods_put $http.put}
* - {@link ng.$http#methods_delete $http.delete}
* - {@link ng.$http#methods_jsonp $http.jsonp}
*
*
* # Setting HTTP Headers
*
* The $http service will automatically add certain HTTP headers to all requests. These defaults
* can be fully configured by accessing the `$httpProvider.defaults.headers` configuration
* object, which currently contains this default configuration:
*
* - `$httpProvider.defaults.headers.common` (headers that are common for all requests):
* - `Accept: application/json, text/plain, * / *`
* - `$httpProvider.defaults.headers.post`: (header defaults for POST requests)
* - `Content-Type: application/json`
* - `$httpProvider.defaults.headers.put` (header defaults for PUT requests)
* - `Content-Type: application/json`
*
* To add or overwrite these defaults, simply add or remove a property from these configuration
* objects. To add headers for an HTTP method other than POST or PUT, simply add a new object
* with the lowercased HTTP method name as the key, e.g.
* `$httpProvider.defaults.headers.get = { 'My-Header' : 'value' }.
*
* The defaults can also be set at runtime via the `$http.defaults` object in the same
* fashion. In addition, you can supply a `headers` property in the config object passed when
* calling `$http(config)`, which overrides the defaults without changing them globally.
*
*
* # Transforming Requests and Responses
*
* Both requests and responses can be transformed using transform functions. By default, Angular
* applies these transformations:
*
* Request transformations:
*
* - If the `data` property of the request configuration object contains an object, serialize it
* into JSON format.
*
* Response transformations:
*
* - If XSRF prefix is detected, strip it (see Security Considerations section below).
* - If JSON response is detected, deserialize it using a JSON parser.
*
* To globally augment or override the default transforms, modify the
* `$httpProvider.defaults.transformRequest` and `$httpProvider.defaults.transformResponse`
* properties. These properties are by default an array of transform functions, which allows you
* to `push` or `unshift` a new transformation function into the transformation chain. You can
* also decide to completely override any default transformations by assigning your
* transformation functions to these properties directly without the array wrapper.
*
* Similarly, to locally override the request/response transforms, augment the
* `transformRequest` and/or `transformResponse` properties of the configuration object passed
* into `$http`.
*
*
* # Caching
*
* To enable caching, set the configuration property `cache` to `true`. When the cache is
* enabled, `$http` stores the response from the server in local cache. Next time the
* response is served from the cache without sending a request to the server.
*
* Note that even if the response is served from cache, delivery of the data is asynchronous in
* the same way that real requests are.
*
* If there are multiple GET requests for the same URL that should be cached using the same
* cache, but the cache is not populated yet, only one request to the server will be made and
* the remaining requests will be fulfilled using the response from the first request.
*
* A custom default cache built with $cacheFactory can be provided in $http.defaults.cache.
* To skip it, set configuration property `cache` to `false`.
*
*
* # Interceptors
*
* Before you start creating interceptors, be sure to understand the
* {@link ng.$q $q and deferred/promise APIs}.
*
* For purposes of global error handling, authentication, or any kind of synchronous or
* asynchronous pre-processing of request or postprocessing of responses, it is desirable to be
* able to intercept requests before they are handed to the server and
* responses before they are handed over to the application code that
* initiated these requests. The interceptors leverage the {@link ng.$q
* promise APIs} to fulfill this need for both synchronous and asynchronous pre-processing.
*
* The interceptors are service factories that are registered with the `$httpProvider` by
* adding them to the `$httpProvider.interceptors` array. The factory is called and
* injected with dependencies (if specified) and returns the interceptor.
*
* There are two kinds of interceptors (and two kinds of rejection interceptors):
*
* * `request`: interceptors get called with http `config` object. The function is free to
* modify the `config` or create a new one. The function needs to return the `config`
* directly or as a promise.
* * `requestError`: interceptor gets called when a previous interceptor threw an error or
* resolved with a rejection.
* * `response`: interceptors get called with http `response` object. The function is free to
* modify the `response` or create a new one. The function needs to return the `response`
* directly or as a promise.
* * `responseError`: interceptor gets called when a previous interceptor threw an error or
* resolved with a rejection.
*
*
* <pre>
* // register the interceptor as a service
* $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
* return {
* // optional method
* 'request': function(config) {
* // do something on success
* return config || $q.when(config);
* },
*
* // optional method
* 'requestError': function(rejection) {
* // do something on error
* if (canRecover(rejection)) {
* return responseOrNewPromise
* }
* return $q.reject(rejection);
* },
*
*
*
* // optional method
* 'response': function(response) {
* // do something on success
* return response || $q.when(response);
* },
*
* // optional method
* 'responseError': function(rejection) {
* // do something on error
* if (canRecover(rejection)) {
* return responseOrNewPromise
* }
* return $q.reject(rejection);
* };
* }
* });
*
* $httpProvider.interceptors.push('myHttpInterceptor');
*
*
* // register the interceptor via an anonymous factory
* $httpProvider.interceptors.push(function($q, dependency1, dependency2) {
* return {
* 'request': function(config) {
* // same as above
* },
* 'response': function(response) {
* // same as above
* }
* };
* });
* </pre>
*
* # Response interceptors (DEPRECATED)
*
* Before you start creating interceptors, be sure to understand the
* {@link ng.$q $q and deferred/promise APIs}.
*
* For purposes of global error handling, authentication or any kind of synchronous or
* asynchronous preprocessing of received responses, it is desirable to be able to intercept
* responses for http requests before they are handed over to the application code that
* initiated these requests. The response interceptors leverage the {@link ng.$q
* promise apis} to fulfil this need for both synchronous and asynchronous preprocessing.
*
* The interceptors are service factories that are registered with the $httpProvider by
* adding them to the `$httpProvider.responseInterceptors` array. The factory is called and
* injected with dependencies (if specified) and returns the interceptor — a function that
* takes a {@link ng.$q promise} and returns the original or a new promise.
*
* <pre>
* // register the interceptor as a service
* $provide.factory('myHttpInterceptor', function($q, dependency1, dependency2) {
* return function(promise) {
* return promise.then(function(response) {
* // do something on success
* return response;
* }, function(response) {
* // do something on error
* if (canRecover(response)) {
* return responseOrNewPromise
* }
* return $q.reject(response);
* });
* }
* });
*
* $httpProvider.responseInterceptors.push('myHttpInterceptor');
*
*
* // register the interceptor via an anonymous factory
* $httpProvider.responseInterceptors.push(function($q, dependency1, dependency2) {
* return function(promise) {
* // same as above
* }
* });
* </pre>
*
*
* # Security Considerations
*
* When designing web applications, consider security threats from:
*
* - {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx
* JSON vulnerability}
* - {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF}
*
* Both server and the client must cooperate in order to eliminate these threats. Angular comes
* pre-configured with strategies that address these issues, but for this to work backend server
* cooperation is required.
*
* ## JSON Vulnerability Protection
*
* A {@link http://haacked.com/archive/2008/11/20/anatomy-of-a-subtle-json-vulnerability.aspx
* JSON vulnerability} allows third party website to turn your JSON resource URL into
* {@link http://en.wikipedia.org/wiki/JSONP JSONP} request under some conditions. To
* counter this your server can prefix all JSON requests with following string `")]}',\n"`.
* Angular will automatically strip the prefix before processing it as JSON.
*
* For example if your server needs to return:
* <pre>
* ['one','two']
* </pre>
*
* which is vulnerable to attack, your server can return:
* <pre>
* )]}',
* ['one','two']
* </pre>
*
* Angular will strip the prefix, before processing the JSON.
*
*
* ## Cross Site Request Forgery (XSRF) Protection
*
* {@link http://en.wikipedia.org/wiki/Cross-site_request_forgery XSRF} is a technique by which
* an unauthorized site can gain your user's private data. Angular provides a mechanism
* to counter XSRF. When performing XHR requests, the $http service reads a token from a cookie
* (by default, `XSRF-TOKEN`) and sets it as an HTTP header (`X-XSRF-TOKEN`). Since only
* JavaScript that runs on your domain could read the cookie, your server can be assured that
* the XHR came from JavaScript running on your domain. The header will not be set for
* cross-domain requests.
*
* To take advantage of this, your server needs to set a token in a JavaScript readable session
* cookie called `XSRF-TOKEN` on the first HTTP GET request. On subsequent XHR requests the
* server can verify that the cookie matches `X-XSRF-TOKEN` HTTP header, and therefore be sure
* that only JavaScript running on your domain could have sent the request. The token must be
* unique for each user and must be verifiable by the server (to prevent the JavaScript from
* making up its own tokens). We recommend that the token is a digest of your site's
* authentication cookie with a {@link https://en.wikipedia.org/wiki/Salt_(cryptography) salt}
* for added security.
*
* The name of the headers can be specified using the xsrfHeaderName and xsrfCookieName
* properties of either $httpProvider.defaults, or the per-request config object.
*
*
* @param {object} config Object describing the request to be made and how it should be
* processed. The object has following properties:
*
* - **method** – `{string}` – HTTP method (e.g. 'GET', 'POST', etc)
* - **url** – `{string}` – Absolute or relative URL of the resource that is being requested.
* - **params** – `{Object.<string|Object>}` – Map of strings or objects which will be turned
* to `?key1=value1&key2=value2` after the url. If the value is not a string, it will be
* JSONified.
* - **data** – `{string|Object}` – Data to be sent as the request message data.
* - **headers** – `{Object}` – Map of strings or functions which return strings representing
* HTTP headers to send to the server. If the return value of a function is null, the
* header will not be sent.
* - **xsrfHeaderName** – `{string}` – Name of HTTP header to populate with the XSRF token.
* - **xsrfCookieName** – `{string}` – Name of cookie containing the XSRF token.
* - **transformRequest** –
* `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
* transform function or an array of such functions. The transform function takes the http
* request body and headers and returns its transformed (typically serialized) version.
* - **transformResponse** –
* `{function(data, headersGetter)|Array.<function(data, headersGetter)>}` –
* transform function or an array of such functions. The transform function takes the http
* response body and headers and returns its transformed (typically deserialized) version.
* - **cache** – `{boolean|Cache}` – If true, a default $http cache will be used to cache the
* GET request, otherwise if a cache instance built with
* {@link ng.$cacheFactory $cacheFactory}, this cache will be used for
* caching.
* - **timeout** – `{number|Promise}` – timeout in milliseconds, or {@link ng.$q promise}
* that should abort the request when resolved.
* - **withCredentials** - `{boolean}` - whether to to set the `withCredentials` flag on the
* XHR object. See {@link https://developer.mozilla.org/en/http_access_control#section_5
* requests with credentials} for more information.
* - **responseType** - `{string}` - see {@link
* https://developer.mozilla.org/en-US/docs/DOM/XMLHttpRequest#responseType requestType}.
*
* @returns {HttpPromise} Returns a {@link ng.$q promise} object with the
* standard `then` method and two http specific methods: `success` and `error`. The `then`
* method takes two arguments a success and an error callback which will be called with a
* response object. The `success` and `error` methods take a single argument - a function that
* will be called when the request succeeds or fails respectively. The arguments passed into
* these functions are destructured representation of the response object passed into the
* `then` method. The response object has these properties:
*
* - **data** – `{string|Object}` – The response body transformed with the transform
* functions.
* - **status** – `{number}` – HTTP status code of the response.
* - **headers** – `{function([headerName])}` – Header getter function.
* - **config** – `{Object}` – The configuration object that was used to generate the request.
*
* @property {Array.<Object>} pendingRequests Array of config objects for currently pending
* requests. This is primarily meant to be used for debugging purposes.
*
*
* @example
<example>
<file name="index.html">
<div ng-controller="FetchCtrl">
<select ng-model="method">
<option>GET</option>
<option>JSONP</option>
</select>
<input type="text" ng-model="url" size="80"/>
<button ng-click="fetch()">fetch</button><br>
<button ng-click="updateModel('GET', 'http-hello.html')">Sample GET</button>
<button
ng-click="updateModel('JSONP',
'http://angularjs.org/greet.php?callback=JSON_CALLBACK&name=Super%20Hero')">
Sample JSONP
</button>
<button
ng-click="updateModel('JSONP', 'http://angularjs.org/doesntexist&callback=JSON_CALLBACK')">
Invalid JSONP
</button>
<pre>http status code: {{status}}</pre>
<pre>http response data: {{data}}</pre>
</div>
</file>
<file name="script.js">
function FetchCtrl($scope, $http, $templateCache) {
$scope.method = 'GET';
$scope.url = 'http-hello.html';
$scope.fetch = function() {
$scope.code = null;
$scope.response = null;
$http({method: $scope.method, url: $scope.url, cache: $templateCache}).
success(function(data, status) {
$scope.status = status;
$scope.data = data;
}).
error(function(data, status) {
$scope.data = data || "Request failed";
$scope.status = status;
});
};
$scope.updateModel = function(method, url) {
$scope.method = method;
$scope.url = url;
};
}
</file>
<file name="http-hello.html">
Hello, $http!
</file>
<file name="scenario.js">
it('should make an xhr GET request', function() {
element(':button:contains("Sample GET")').click();
element(':button:contains("fetch")').click();
expect(binding('status')).toBe('200');
expect(binding('data')).toMatch(/Hello, \$http!/);
});
it('should make a JSONP request to angularjs.org', function() {
element(':button:contains("Sample JSONP")').click();
element(':button:contains("fetch")').click();
expect(binding('status')).toBe('200');
expect(binding('data')).toMatch(/Super Hero!/);
});
it('should make JSONP request to invalid URL and invoke the error handler',
function() {
element(':button:contains("Invalid JSONP")').click();
element(':button:contains("fetch")').click();
expect(binding('status')).toBe('0');
expect(binding('data')).toBe('Request failed');
});
</file>
</example>
*/
function $http(requestConfig) {
var config = {
transformRequest: defaults.transformRequest,
transformResponse: defaults.transformResponse
};
var headers = mergeHeaders(requestConfig);
extend(config, requestConfig);
config.headers = headers;
config.method = uppercase(config.method);
var xsrfValue = urlIsSameOrigin(config.url)
? $browser.cookies()[config.xsrfCookieName || defaults.xsrfCookieName]
: undefined;
if (xsrfValue) {
headers[(config.xsrfHeaderName || defaults.xsrfHeaderName)] = xsrfValue;
}
var serverRequest = function(config) {
headers = config.headers;
var reqData = transformData(config.data, headersGetter(headers), config.transformRequest);
// strip content-type if data is undefined
if (isUndefined(config.data)) {
forEach(headers, function(value, header) {
if (lowercase(header) === 'content-type') {
delete headers[header];
}
});
}
if (isUndefined(config.withCredentials) && !isUndefined(defaults.withCredentials)) {
config.withCredentials = defaults.withCredentials;
}
// send request
return sendReq(config, reqData, headers).then(transformResponse, transformResponse);
};
var chain = [serverRequest, undefined];
var promise = $q.when(config);
// apply interceptors
forEach(reversedInterceptors, function(interceptor) {
if (interceptor.request || interceptor.requestError) {
chain.unshift(interceptor.request, interceptor.requestError);
}
if (interceptor.response || interceptor.responseError) {
chain.push(interceptor.response, interceptor.responseError);
}
});
while(chain.length) {
var thenFn = chain.shift();
var rejectFn = chain.shift();
promise = promise.then(thenFn, rejectFn);
}
promise.success = function(fn) {
promise.then(function(response) {
fn(response.data, response.status, response.headers, config);
});
return promise;
};
promise.error = function(fn) {
promise.then(null, function(response) {
fn(response.data, response.status, response.headers, config);
});
return promise;
};
return promise;
function transformResponse(response) {
// make a copy since the response must be cacheable
var resp = extend({}, response, {
data: transformData(response.data, response.headers, config.transformResponse)
});
return (isSuccess(response.status))
? resp
: $q.reject(resp);
}
function mergeHeaders(config) {
var defHeaders = defaults.headers,
reqHeaders = extend({}, config.headers),
defHeaderName, lowercaseDefHeaderName, reqHeaderName;
defHeaders = extend({}, defHeaders.common, defHeaders[lowercase(config.method)]);
// execute if header value is function
execHeaders(defHeaders);
execHeaders(reqHeaders);
// using for-in instead of forEach to avoid unecessary iteration after header has been found
defaultHeadersIteration:
for (defHeaderName in defHeaders) {
lowercaseDefHeaderName = lowercase(defHeaderName);
for (reqHeaderName in reqHeaders) {
if (lowercase(reqHeaderName) === lowercaseDefHeaderName) {
continue defaultHeadersIteration;
}
}
reqHeaders[defHeaderName] = defHeaders[defHeaderName];
}
return reqHeaders;
function execHeaders(headers) {
var headerContent;
forEach(headers, function(headerFn, header) {
if (isFunction(headerFn)) {
headerContent = headerFn();
if (headerContent != null) {
headers[header] = headerContent;
} else {
delete headers[header];
}
}
});
}
}
}
$http.pendingRequests = [];
/**
* @ngdoc method
* @name ng.$http#get
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `GET` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name ng.$http#delete
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `DELETE` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name ng.$http#head
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `HEAD` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name ng.$http#jsonp
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `JSONP` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request.
* Should contain `JSON_CALLBACK` string.
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
createShortMethods('get', 'delete', 'head', 'jsonp');
/**
* @ngdoc method
* @name ng.$http#post
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `POST` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {*} data Request content
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
/**
* @ngdoc method
* @name ng.$http#put
* @methodOf ng.$http
*
* @description
* Shortcut method to perform `PUT` request.
*
* @param {string} url Relative or absolute URL specifying the destination of the request
* @param {*} data Request content
* @param {Object=} config Optional configuration object
* @returns {HttpPromise} Future object
*/
createShortMethodsWithData('post', 'put');
/**
* @ngdoc property
* @name ng.$http#defaults
* @propertyOf ng.$http
*
* @description
* Runtime equivalent of the `$httpProvider.defaults` property. Allows configuration of
* default headers, withCredentials as well as request and response transformations.
*
* See "Setting HTTP Headers" and "Transforming Requests and Responses" sections above.
*/
$http.defaults = defaults;
return $http;
function createShortMethods(names) {
forEach(arguments, function(name) {
$http[name] = function(url, config) {
return $http(extend(config || {}, {
method: name,
url: url
}));
};
});
}
function createShortMethodsWithData(name) {
forEach(arguments, function(name) {
$http[name] = function(url, data, config) {
return $http(extend(config || {}, {
method: name,
url: url,
data: data
}));
};
});
}
/**
* Makes the request.
*
* !!! ACCESSES CLOSURE VARS:
* $httpBackend, defaults, $log, $rootScope, defaultCache, $http.pendingRequests
*/
function sendReq(config, reqData, reqHeaders) {
var deferred = $q.defer(),
promise = deferred.promise,
cache,
cachedResp,
url = buildUrl(config.url, config.params);
$http.pendingRequests.push(config);
promise.then(removePendingReq, removePendingReq);
if ((config.cache || defaults.cache) && config.cache !== false && config.method == 'GET') {
cache = isObject(config.cache) ? config.cache
: isObject(defaults.cache) ? defaults.cache
: defaultCache;
}
if (cache) {
cachedResp = cache.get(url);
if (isDefined(cachedResp)) {
if (cachedResp.then) {
// cached request has already been sent, but there is no response yet
cachedResp.then(removePendingReq, removePendingReq);
return cachedResp;
} else {
// serving from cache
if (isArray(cachedResp)) {
resolvePromise(cachedResp[1], cachedResp[0], copy(cachedResp[2]));
} else {
resolvePromise(cachedResp, 200, {});
}
}
} else {
// put the promise for the non-transformed response into cache as a placeholder
cache.put(url, promise);
}
}
// if we won't have the response in cache, send the request to the backend
if (isUndefined(cachedResp)) {
$httpBackend(config.method, url, reqData, done, reqHeaders, config.timeout,
config.withCredentials, config.responseType);
}
return promise;
/**
* Callback registered to $httpBackend():
* - caches the response if desired
* - resolves the raw $http promise
* - calls $apply
*/
function done(status, response, headersString) {
if (cache) {
if (isSuccess(status)) {
cache.put(url, [status, response, parseHeaders(headersString)]);
} else {
// remove promise from the cache
cache.remove(url);
}
}
resolvePromise(response, status, headersString);
if (!$rootScope.$$phase) $rootScope.$apply();
}
/**
* Resolves the raw $http promise.
*/
function resolvePromise(response, status, headers) {
// normalize internal statuses to 0
status = Math.max(status, 0);
(isSuccess(status) ? deferred.resolve : deferred.reject)({
data: response,
status: status,
headers: headersGetter(headers),
config: config
});
}
function removePendingReq() {
var idx = indexOf($http.pendingRequests, config);
if (idx !== -1) $http.pendingRequests.splice(idx, 1);
}
}
function buildUrl(url, params) {
if (!params) return url;
var parts = [];
forEachSorted(params, function(value, key) {
if (value === null || isUndefined(value)) return;
if (!isArray(value)) value = [value];
forEach(value, function(v) {
if (isObject(v)) {
v = toJson(v);
}
parts.push(encodeUriQuery(key) + '=' +
encodeUriQuery(v));
});
});
return url + ((url.indexOf('?') == -1) ? '?' : '&') + parts.join('&');
}
}];
}
var XHR = window.XMLHttpRequest || function() {
/* global ActiveXObject */
try { return new ActiveXObject("Msxml2.XMLHTTP.6.0"); } catch (e1) {}
try { return new ActiveXObject("Msxml2.XMLHTTP.3.0"); } catch (e2) {}
try { return new ActiveXObject("Msxml2.XMLHTTP"); } catch (e3) {}
throw minErr('$httpBackend')('noxhr', "This browser does not support XMLHttpRequest.");
};
/**
* @ngdoc object
* @name ng.$httpBackend
* @requires $browser
* @requires $window
* @requires $document
*
* @description
* HTTP backend used by the {@link ng.$http service} that delegates to
* XMLHttpRequest object or JSONP and deals with browser incompatibilities.
*
* You should never need to use this service directly, instead use the higher-level abstractions:
* {@link ng.$http $http} or {@link ngResource.$resource $resource}.
*
* During testing this implementation is swapped with {@link ngMock.$httpBackend mock
* $httpBackend} which can be trained with responses.
*/
function $HttpBackendProvider() {
this.$get = ['$browser', '$window', '$document', function($browser, $window, $document) {
return createHttpBackend($browser, XHR, $browser.defer, $window.angular.callbacks,
$document[0], $window.location.protocol.replace(':', ''));
}];
}
function createHttpBackend($browser, XHR, $browserDefer, callbacks, rawDocument, locationProtocol) {
// TODO(vojta): fix the signature
return function(method, url, post, callback, headers, timeout, withCredentials, responseType) {
var status;
$browser.$$incOutstandingRequestCount();
url = url || $browser.url();
if (lowercase(method) == 'jsonp') {
var callbackId = '_' + (callbacks.counter++).toString(36);
callbacks[callbackId] = function(data) {
callbacks[callbackId].data = data;
};
var jsonpDone = jsonpReq(url.replace('JSON_CALLBACK', 'angular.callbacks.' + callbackId),
function() {
if (callbacks[callbackId].data) {
completeRequest(callback, 200, callbacks[callbackId].data);
} else {
completeRequest(callback, status || -2);
}
delete callbacks[callbackId];
});
} else {
var xhr = new XHR();
xhr.open(method, url, true);
forEach(headers, function(value, key) {
if (isDefined(value)) {
xhr.setRequestHeader(key, value);
}
});
// In IE6 and 7, this might be called synchronously when xhr.send below is called and the
// response is in the cache. the promise api will ensure that to the app code the api is
// always async
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
var responseHeaders = xhr.getAllResponseHeaders();
// responseText is the old-school way of retrieving response (supported by IE8 & 9)
// response/responseType properties were introduced in XHR Level2 spec (supported by IE10)
completeRequest(callback,
status || xhr.status,
(xhr.responseType ? xhr.response : xhr.responseText),
responseHeaders);
}
};
if (withCredentials) {
xhr.withCredentials = true;
}
if (responseType) {
xhr.responseType = responseType;
}
xhr.send(post || null);
}
if (timeout > 0) {
var timeoutId = $browserDefer(timeoutRequest, timeout);
} else if (timeout && timeout.then) {
timeout.then(timeoutRequest);
}
function timeoutRequest() {
status = -1;
jsonpDone && jsonpDone();
xhr && xhr.abort();
}
function completeRequest(callback, status, response, headersString) {
var protocol = locationProtocol || urlResolve(url).protocol;
// cancel timeout and subsequent timeout promise resolution
timeoutId && $browserDefer.cancel(timeoutId);
jsonpDone = xhr = null;
// fix status code for file protocol (it's always 0)
status = (protocol == 'file') ? (response ? 200 : 404) : status;
// normalize IE bug (http://bugs.jquery.com/ticket/1450)
status = status == 1223 ? 204 : status;
callback(status, response, headersString);
$browser.$$completeOutstandingRequest(noop);
}
};
function jsonpReq(url, done) {
// we can't use jQuery/jqLite here because jQuery does crazy shit with script elements, e.g.:
// - fetches local scripts via XHR and evals them
// - adds and immediately removes script elements from the document
var script = rawDocument.createElement('script'),
doneWrapper = function() {
rawDocument.body.removeChild(script);
if (done) done();
};
script.type = 'text/javascript';
script.src = url;
if (msie) {
script.onreadystatechange = function() {
if (/loaded|complete/.test(script.readyState)) doneWrapper();
};
} else {
script.onload = script.onerror = doneWrapper;
}
rawDocument.body.appendChild(script);
return doneWrapper;
}
}
var $interpolateMinErr = minErr('$interpolate');
/**
* @ngdoc object
* @name ng.$interpolateProvider
* @function
*
* @description
*
* Used for configuring the interpolation markup. Defaults to `{{` and `}}`.
*
* @example
<doc:example module="customInterpolationApp">
<doc:source>
<script>
var customInterpolationApp = angular.module('customInterpolationApp', []);
customInterpolationApp.config(function($interpolateProvider) {
$interpolateProvider.startSymbol('//');
$interpolateProvider.endSymbol('//');
});
customInterpolationApp.controller('DemoController', function DemoController() {
this.label = "This binding is brought you by // interpolation symbols.";
});
</script>
<div ng-app="App" ng-controller="DemoController as demo">
//demo.label//
</div>
</doc:source>
<doc:scenario>
it('should interpolate binding with custom symbols', function() {
expect(binding('demo.label')).toBe('This binding is brought you by // interpolation symbols.');
});
</doc:scenario>
</doc:example>
*/
function $InterpolateProvider() {
var startSymbol = '{{';
var endSymbol = '}}';
/**
* @ngdoc method
* @name ng.$interpolateProvider#startSymbol
* @methodOf ng.$interpolateProvider
* @description
* Symbol to denote start of expression in the interpolated string. Defaults to `{{`.
*
* @param {string=} value new value to set the starting symbol to.
* @returns {string|self} Returns the symbol when used as getter and self if used as setter.
*/
this.startSymbol = function(value){
if (value) {
startSymbol = value;
return this;
} else {
return startSymbol;
}
};
/**
* @ngdoc method
* @name ng.$interpolateProvider#endSymbol
* @methodOf ng.$interpolateProvider
* @description
* Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
*
* @param {string=} value new value to set the ending symbol to.
* @returns {string|self} Returns the symbol when used as getter and self if used as setter.
*/
this.endSymbol = function(value){
if (value) {
endSymbol = value;
return this;
} else {
return endSymbol;
}
};
this.$get = ['$parse', '$exceptionHandler', '$sce', function($parse, $exceptionHandler, $sce) {
var startSymbolLength = startSymbol.length,
endSymbolLength = endSymbol.length;
/**
* @ngdoc function
* @name ng.$interpolate
* @function
*
* @requires $parse
* @requires $sce
*
* @description
*
* Compiles a string with markup into an interpolation function. This service is used by the
* HTML {@link ng.$compile $compile} service for data binding. See
* {@link ng.$interpolateProvider $interpolateProvider} for configuring the
* interpolation markup.
*
*
<pre>
var $interpolate = ...; // injected
var exp = $interpolate('Hello {{name}}!');
expect(exp({name:'Angular'}).toEqual('Hello Angular!');
</pre>
*
*
* @param {string} text The text with markup to interpolate.
* @param {boolean=} mustHaveExpression if set to true then the interpolation string must have
* embedded expression in order to return an interpolation function. Strings with no
* embedded expression will return null for the interpolation function.
* @param {string=} trustedContext when provided, the returned function passes the interpolated
* result through {@link ng.$sce#methods_getTrusted $sce.getTrusted(interpolatedResult,
* trustedContext)} before returning it. Refer to the {@link ng.$sce $sce} service that
* provides Strict Contextual Escaping for details.
* @returns {function(context)} an interpolation function which is used to compute the
* interpolated string. The function has these parameters:
*
* * `context`: an object against which any expressions embedded in the strings are evaluated
* against.
*
*/
function $interpolate(text, mustHaveExpression, trustedContext) {
var startIndex,
endIndex,
index = 0,
parts = [],
length = text.length,
hasInterpolation = false,
fn,
exp,
concat = [];
while(index < length) {
if ( ((startIndex = text.indexOf(startSymbol, index)) != -1) &&
((endIndex = text.indexOf(endSymbol, startIndex + startSymbolLength)) != -1) ) {
(index != startIndex) && parts.push(text.substring(index, startIndex));
parts.push(fn = $parse(exp = text.substring(startIndex + startSymbolLength, endIndex)));
fn.exp = exp;
index = endIndex + endSymbolLength;
hasInterpolation = true;
} else {
// we did not find anything, so we have to add the remainder to the parts array
(index != length) && parts.push(text.substring(index));
index = length;
}
}
if (!(length = parts.length)) {
// we added, nothing, must have been an empty string.
parts.push('');
length = 1;
}
// Concatenating expressions makes it hard to reason about whether some combination of
// concatenated values are unsafe to use and could easily lead to XSS. By requiring that a
// single expression be used for iframe[src], object[src], etc., we ensure that the value
// that's used is assigned or constructed by some JS code somewhere that is more testable or
// make it obvious that you bound the value to some user controlled value. This helps reduce
// the load when auditing for XSS issues.
if (trustedContext && parts.length > 1) {
throw $interpolateMinErr('noconcat',
"Error while interpolating: {0}\nStrict Contextual Escaping disallows " +
"interpolations that concatenate multiple expressions when a trusted value is " +
"required. See http://docs.angularjs.org/api/ng.$sce", text);
}
if (!mustHaveExpression || hasInterpolation) {
concat.length = length;
fn = function(context) {
try {
for(var i = 0, ii = length, part; i<ii; i++) {
if (typeof (part = parts[i]) == 'function') {
part = part(context);
if (trustedContext) {
part = $sce.getTrusted(trustedContext, part);
} else {
part = $sce.valueOf(part);
}
if (part === null || isUndefined(part)) {
part = '';
} else if (typeof part != 'string') {
part = toJson(part);
}
}
concat[i] = part;
}
return concat.join('');
}
catch(err) {
var newErr = $interpolateMinErr('interr', "Can't interpolate: {0}\n{1}", text,
err.toString());
$exceptionHandler(newErr);
}
};
fn.exp = text;
fn.parts = parts;
return fn;
}
}
/**
* @ngdoc method
* @name ng.$interpolate#startSymbol
* @methodOf ng.$interpolate
* @description
* Symbol to denote the start of expression in the interpolated string. Defaults to `{{`.
*
* Use {@link ng.$interpolateProvider#startSymbol $interpolateProvider#startSymbol} to change
* the symbol.
*
* @returns {string} start symbol.
*/
$interpolate.startSymbol = function() {
return startSymbol;
};
/**
* @ngdoc method
* @name ng.$interpolate#endSymbol
* @methodOf ng.$interpolate
* @description
* Symbol to denote the end of expression in the interpolated string. Defaults to `}}`.
*
* Use {@link ng.$interpolateProvider#endSymbol $interpolateProvider#endSymbol} to change
* the symbol.
*
* @returns {string} start symbol.
*/
$interpolate.endSymbol = function() {
return endSymbol;
};
return $interpolate;
}];
}
function $IntervalProvider() {
this.$get = ['$rootScope', '$window', '$q',
function($rootScope, $window, $q) {
var intervals = {};
/**
* @ngdoc function
* @name ng.$interval
*
* @description
* Angular's wrapper for `window.setInterval`. The `fn` function is executed every `delay`
* milliseconds.
*
* The return value of registering an interval function is a promise. This promise will be
* notified upon each tick of the interval, and will be resolved after `count` iterations, or
* run indefinitely if `count` is not defined. The value of the notification will be the
* number of iterations that have run.
* To cancel an interval, call `$interval.cancel(promise)`.
*
* In tests you can use {@link ngMock.$interval#methods_flush `$interval.flush(millis)`} to
* move forward by `millis` milliseconds and trigger any functions scheduled to run in that
* time.
*
* @param {function()} fn A function that should be called repeatedly.
* @param {number} delay Number of milliseconds between each function call.
* @param {number=} [count=0] Number of times to repeat. If not set, or 0, will repeat
* indefinitely.
* @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
* will invoke `fn` within the {@link ng.$rootScope.Scope#methods_$apply $apply} block.
* @returns {promise} A promise which will be notified on each iteration.
*/
function interval(fn, delay, count, invokeApply) {
var setInterval = $window.setInterval,
clearInterval = $window.clearInterval,
deferred = $q.defer(),
promise = deferred.promise,
iteration = 0,
skipApply = (isDefined(invokeApply) && !invokeApply);
count = isDefined(count) ? count : 0,
promise.then(null, null, fn);
promise.$$intervalId = setInterval(function tick() {
deferred.notify(iteration++);
if (count > 0 && iteration >= count) {
deferred.resolve(iteration);
clearInterval(promise.$$intervalId);
delete intervals[promise.$$intervalId];
}
if (!skipApply) $rootScope.$apply();
}, delay);
intervals[promise.$$intervalId] = deferred;
return promise;
}
/**
* @ngdoc function
* @name ng.$interval#cancel
* @methodOf ng.$interval
*
* @description
* Cancels a task associated with the `promise`.
*
* @param {number} promise Promise returned by the `$interval` function.
* @returns {boolean} Returns `true` if the task was successfully canceled.
*/
interval.cancel = function(promise) {
if (promise && promise.$$intervalId in intervals) {
intervals[promise.$$intervalId].reject('canceled');
clearInterval(promise.$$intervalId);
delete intervals[promise.$$intervalId];
return true;
}
return false;
};
return interval;
}];
}
/**
* @ngdoc object
* @name ng.$locale
*
* @description
* $locale service provides localization rules for various Angular components. As of right now the
* only public api is:
*
* * `id` – `{string}` – locale id formatted as `languageId-countryId` (e.g. `en-us`)
*/
function $LocaleProvider(){
this.$get = function() {
return {
id: 'en-us',
NUMBER_FORMATS: {
DECIMAL_SEP: '.',
GROUP_SEP: ',',
PATTERNS: [
{ // Decimal Pattern
minInt: 1,
minFrac: 0,
maxFrac: 3,
posPre: '',
posSuf: '',
negPre: '-',
negSuf: '',
gSize: 3,
lgSize: 3
},{ //Currency Pattern
minInt: 1,
minFrac: 2,
maxFrac: 2,
posPre: '\u00A4',
posSuf: '',
negPre: '(\u00A4',
negSuf: ')',
gSize: 3,
lgSize: 3
}
],
CURRENCY_SYM: '$'
},
DATETIME_FORMATS: {
MONTH:
'January,February,March,April,May,June,July,August,September,October,November,December'
.split(','),
SHORTMONTH: 'Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sep,Oct,Nov,Dec'.split(','),
DAY: 'Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday'.split(','),
SHORTDAY: 'Sun,Mon,Tue,Wed,Thu,Fri,Sat'.split(','),
AMPMS: ['AM','PM'],
medium: 'MMM d, y h:mm:ss a',
short: 'M/d/yy h:mm a',
fullDate: 'EEEE, MMMM d, y',
longDate: 'MMMM d, y',
mediumDate: 'MMM d, y',
shortDate: 'M/d/yy',
mediumTime: 'h:mm:ss a',
shortTime: 'h:mm a'
},
pluralCat: function(num) {
if (num === 1) {
return 'one';
}
return 'other';
}
};
};
}
var PATH_MATCH = /^([^\?#]*)(\?([^#]*))?(#(.*))?$/,
DEFAULT_PORTS = {'http': 80, 'https': 443, 'ftp': 21};
var $locationMinErr = minErr('$location');
/**
* Encode path using encodeUriSegment, ignoring forward slashes
*
* @param {string} path Path to encode
* @returns {string}
*/
function encodePath(path) {
var segments = path.split('/'),
i = segments.length;
while (i--) {
segments[i] = encodeUriSegment(segments[i]);
}
return segments.join('/');
}
function parseAbsoluteUrl(absoluteUrl, locationObj) {
var parsedUrl = urlResolve(absoluteUrl);
locationObj.$$protocol = parsedUrl.protocol;
locationObj.$$host = parsedUrl.hostname;
locationObj.$$port = int(parsedUrl.port) || DEFAULT_PORTS[parsedUrl.protocol] || null;
}
function parseAppUrl(relativeUrl, locationObj) {
var prefixed = (relativeUrl.charAt(0) !== '/');
if (prefixed) {
relativeUrl = '/' + relativeUrl;
}
var match = urlResolve(relativeUrl);
locationObj.$$path = decodeURIComponent(prefixed && match.pathname.charAt(0) === '/' ?
match.pathname.substring(1) : match.pathname);
locationObj.$$search = parseKeyValue(match.search);
locationObj.$$hash = decodeURIComponent(match.hash);
// make sure path starts with '/';
if (locationObj.$$path && locationObj.$$path.charAt(0) != '/') {
locationObj.$$path = '/' + locationObj.$$path;
}
}
/**
*
* @param {string} begin
* @param {string} whole
* @returns {string} returns text from whole after begin or undefined if it does not begin with
* expected string.
*/
function beginsWith(begin, whole) {
if (whole.indexOf(begin) === 0) {
return whole.substr(begin.length);
}
}
function stripHash(url) {
var index = url.indexOf('#');
return index == -1 ? url : url.substr(0, index);
}
function stripFile(url) {
return url.substr(0, stripHash(url).lastIndexOf('/') + 1);
}
/* return the server only (scheme://host:port) */
function serverBase(url) {
return url.substring(0, url.indexOf('/', url.indexOf('//') + 2));
}
/**
* LocationHtml5Url represents an url
* This object is exposed as $location service when HTML5 mode is enabled and supported
*
* @constructor
* @param {string} appBase application base URL
* @param {string} basePrefix url path prefix
*/
function LocationHtml5Url(appBase, basePrefix) {
this.$$html5 = true;
basePrefix = basePrefix || '';
var appBaseNoFile = stripFile(appBase);
parseAbsoluteUrl(appBase, this);
/**
* Parse given html5 (regular) url string into properties
* @param {string} newAbsoluteUrl HTML5 url
* @private
*/
this.$$parse = function(url) {
var pathUrl = beginsWith(appBaseNoFile, url);
if (!isString(pathUrl)) {
throw $locationMinErr('ipthprfx', 'Invalid url "{0}", missing path prefix "{1}".', url,
appBaseNoFile);
}
parseAppUrl(pathUrl, this);
if (!this.$$path) {
this.$$path = '/';
}
this.$$compose();
};
/**
* Compose url and update `absUrl` property
* @private
*/
this.$$compose = function() {
var search = toKeyValue(this.$$search),
hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
this.$$absUrl = appBaseNoFile + this.$$url.substr(1); // first char is always '/'
};
this.$$rewrite = function(url) {
var appUrl, prevAppUrl;
if ( (appUrl = beginsWith(appBase, url)) !== undefined ) {
prevAppUrl = appUrl;
if ( (appUrl = beginsWith(basePrefix, appUrl)) !== undefined ) {
return appBaseNoFile + (beginsWith('/', appUrl) || appUrl);
} else {
return appBase + prevAppUrl;
}
} else if ( (appUrl = beginsWith(appBaseNoFile, url)) !== undefined ) {
return appBaseNoFile + appUrl;
} else if (appBaseNoFile == url + '/') {
return appBaseNoFile;
}
};
}
/**
* LocationHashbangUrl represents url
* This object is exposed as $location service when developer doesn't opt into html5 mode.
* It also serves as the base class for html5 mode fallback on legacy browsers.
*
* @constructor
* @param {string} appBase application base URL
* @param {string} hashPrefix hashbang prefix
*/
function LocationHashbangUrl(appBase, hashPrefix) {
var appBaseNoFile = stripFile(appBase);
parseAbsoluteUrl(appBase, this);
/**
* Parse given hashbang url into properties
* @param {string} url Hashbang url
* @private
*/
this.$$parse = function(url) {
var withoutBaseUrl = beginsWith(appBase, url) || beginsWith(appBaseNoFile, url);
var withoutHashUrl = withoutBaseUrl.charAt(0) == '#'
? beginsWith(hashPrefix, withoutBaseUrl)
: (this.$$html5)
? withoutBaseUrl
: '';
if (!isString(withoutHashUrl)) {
throw $locationMinErr('ihshprfx', 'Invalid url "{0}", missing hash prefix "{1}".', url,
hashPrefix);
}
parseAppUrl(withoutHashUrl, this);
this.$$compose();
};
/**
* Compose hashbang url and update `absUrl` property
* @private
*/
this.$$compose = function() {
var search = toKeyValue(this.$$search),
hash = this.$$hash ? '#' + encodeUriSegment(this.$$hash) : '';
this.$$url = encodePath(this.$$path) + (search ? '?' + search : '') + hash;
this.$$absUrl = appBase + (this.$$url ? hashPrefix + this.$$url : '');
};
this.$$rewrite = function(url) {
if(stripHash(appBase) == stripHash(url)) {
return url;
}
};
}
/**
* LocationHashbangUrl represents url
* This object is exposed as $location service when html5 history api is enabled but the browser
* does not support it.
*
* @constructor
* @param {string} appBase application base URL
* @param {string} hashPrefix hashbang prefix
*/
function LocationHashbangInHtml5Url(appBase, hashPrefix) {
this.$$html5 = true;
LocationHashbangUrl.apply(this, arguments);
var appBaseNoFile = stripFile(appBase);
this.$$rewrite = function(url) {
var appUrl;
if ( appBase == stripHash(url) ) {
return url;
} else if ( (appUrl = beginsWith(appBaseNoFile, url)) ) {
return appBase + hashPrefix + appUrl;
} else if ( appBaseNoFile === url + '/') {
return appBaseNoFile;
}
};
}
LocationHashbangInHtml5Url.prototype =
LocationHashbangUrl.prototype =
LocationHtml5Url.prototype = {
/**
* Are we in html5 mode?
* @private
*/
$$html5: false,
/**
* Has any change been replacing ?
* @private
*/
$$replace: false,
/**
* @ngdoc method
* @name ng.$location#absUrl
* @methodOf ng.$location
*
* @description
* This method is getter only.
*
* Return full url representation with all segments encoded according to rules specified in
* {@link http://www.ietf.org/rfc/rfc3986.txt RFC 3986}.
*
* @return {string} full url
*/
absUrl: locationGetter('$$absUrl'),
/**
* @ngdoc method
* @name ng.$location#url
* @methodOf ng.$location
*
* @description
* This method is getter / setter.
*
* Return url (e.g. `/path?a=b#hash`) when called without any parameter.
*
* Change path, search and hash, when called with parameter and return `$location`.
*
* @param {string=} url New url without base prefix (e.g. `/path?a=b#hash`)
* @param {string=} replace The path that will be changed
* @return {string} url
*/
url: function(url, replace) {
if (isUndefined(url))
return this.$$url;
var match = PATH_MATCH.exec(url);
if (match[1]) this.path(decodeURIComponent(match[1]));
if (match[2] || match[1]) this.search(match[3] || '');
this.hash(match[5] || '', replace);
return this;
},
/**
* @ngdoc method
* @name ng.$location#protocol
* @methodOf ng.$location
*
* @description
* This method is getter only.
*
* Return protocol of current url.
*
* @return {string} protocol of current url
*/
protocol: locationGetter('$$protocol'),
/**
* @ngdoc method
* @name ng.$location#host
* @methodOf ng.$location
*
* @description
* This method is getter only.
*
* Return host of current url.
*
* @return {string} host of current url.
*/
host: locationGetter('$$host'),
/**
* @ngdoc method
* @name ng.$location#port
* @methodOf ng.$location
*
* @description
* This method is getter only.
*
* Return port of current url.
*
* @return {Number} port
*/
port: locationGetter('$$port'),
/**
* @ngdoc method
* @name ng.$location#path
* @methodOf ng.$location
*
* @description
* This method is getter / setter.
*
* Return path of current url when called without any parameter.
*
* Change path when called with parameter and return `$location`.
*
* Note: Path should always begin with forward slash (/), this method will add the forward slash
* if it is missing.
*
* @param {string=} path New path
* @return {string} path
*/
path: locationGetterSetter('$$path', function(path) {
return path.charAt(0) == '/' ? path : '/' + path;
}),
/**
* @ngdoc method
* @name ng.$location#search
* @methodOf ng.$location
*
* @description
* This method is getter / setter.
*
* Return search part (as object) of current url when called without any parameter.
*
* Change search part when called with parameter and return `$location`.
*
* @param {string|Object.<string>|Object.<Array.<string>>} search New search params - string or
* hash object. Hash object may contain an array of values, which will be decoded as duplicates in
* the url.
*
* @param {(string|Array<string>)=} paramValue If `search` is a string, then `paramValue` will override only a
* single search parameter. If `paramValue` is an array, it will set the parameter as a
* comma-separated value. If `paramValue` is `null`, the parameter will be deleted.
*
* @return {string} search
*/
search: function(search, paramValue) {
switch (arguments.length) {
case 0:
return this.$$search;
case 1:
if (isString(search)) {
this.$$search = parseKeyValue(search);
} else if (isObject(search)) {
this.$$search = search;
} else {
throw $locationMinErr('isrcharg',
'The first argument of the `$location#search()` call must be a string or an object.');
}
break;
default:
if (isUndefined(paramValue) || paramValue === null) {
delete this.$$search[search];
} else {
this.$$search[search] = paramValue;
}
}
this.$$compose();
return this;
},
/**
* @ngdoc method
* @name ng.$location#hash
* @methodOf ng.$location
*
* @description
* This method is getter / setter.
*
* Return hash fragment when called without any parameter.
*
* Change hash fragment when called with parameter and return `$location`.
*
* @param {string=} hash New hash fragment
* @return {string} hash
*/
hash: locationGetterSetter('$$hash', identity),
/**
* @ngdoc method
* @name ng.$location#replace
* @methodOf ng.$location
*
* @description
* If called, all changes to $location during current `$digest` will be replacing current history
* record, instead of adding new one.
*/
replace: function() {
this.$$replace = true;
return this;
}
};
function locationGetter(property) {
return function() {
return this[property];
};
}
function locationGetterSetter(property, preprocess) {
return function(value) {
if (isUndefined(value))
return this[property];
this[property] = preprocess(value);
this.$$compose();
return this;
};
}
/**
* @ngdoc object
* @name ng.$location
*
* @requires $browser
* @requires $sniffer
* @requires $rootElement
*
* @description
* The $location service parses the URL in the browser address bar (based on the
* {@link https://developer.mozilla.org/en/window.location window.location}) and makes the URL
* available to your application. Changes to the URL in the address bar are reflected into
* $location service and changes to $location are reflected into the browser address bar.
*
* **The $location service:**
*
* - Exposes the current URL in the browser address bar, so you can
* - Watch and observe the URL.
* - Change the URL.
* - Synchronizes the URL with the browser when the user
* - Changes the address bar.
* - Clicks the back or forward button (or clicks a History link).
* - Clicks on a link.
* - Represents the URL object as a set of methods (protocol, host, port, path, search, hash).
*
* For more information see {@link guide/dev_guide.services.$location Developer Guide: Angular
* Services: Using $location}
*/
/**
* @ngdoc object
* @name ng.$locationProvider
* @description
* Use the `$locationProvider` to configure how the application deep linking paths are stored.
*/
function $LocationProvider(){
var hashPrefix = '',
html5Mode = false;
/**
* @ngdoc property
* @name ng.$locationProvider#hashPrefix
* @methodOf ng.$locationProvider
* @description
* @param {string=} prefix Prefix for hash part (containing path and search)
* @returns {*} current value if used as getter or itself (chaining) if used as setter
*/
this.hashPrefix = function(prefix) {
if (isDefined(prefix)) {
hashPrefix = prefix;
return this;
} else {
return hashPrefix;
}
};
/**
* @ngdoc property
* @name ng.$locationProvider#html5Mode
* @methodOf ng.$locationProvider
* @description
* @param {boolean=} mode Use HTML5 strategy if available.
* @returns {*} current value if used as getter or itself (chaining) if used as setter
*/
this.html5Mode = function(mode) {
if (isDefined(mode)) {
html5Mode = mode;
return this;
} else {
return html5Mode;
}
};
/**
* @ngdoc event
* @name ng.$location#$locationChangeStart
* @eventOf ng.$location
* @eventType broadcast on root scope
* @description
* Broadcasted before a URL will change. This change can be prevented by calling
* `preventDefault` method of the event. See {@link ng.$rootScope.Scope#$on} for more
* details about event object. Upon successful change
* {@link ng.$location#$locationChangeSuccess $locationChangeSuccess} is fired.
*
* @param {Object} angularEvent Synthetic event object.
* @param {string} newUrl New URL
* @param {string=} oldUrl URL that was before it was changed.
*/
/**
* @ngdoc event
* @name ng.$location#$locationChangeSuccess
* @eventOf ng.$location
* @eventType broadcast on root scope
* @description
* Broadcasted after a URL was changed.
*
* @param {Object} angularEvent Synthetic event object.
* @param {string} newUrl New URL
* @param {string=} oldUrl URL that was before it was changed.
*/
this.$get = ['$rootScope', '$browser', '$sniffer', '$rootElement',
function( $rootScope, $browser, $sniffer, $rootElement) {
var $location,
LocationMode,
baseHref = $browser.baseHref(), // if base[href] is undefined, it defaults to ''
initialUrl = $browser.url(),
appBase;
if (html5Mode) {
appBase = serverBase(initialUrl) + (baseHref || '/');
LocationMode = $sniffer.history ? LocationHtml5Url : LocationHashbangInHtml5Url;
} else {
appBase = stripHash(initialUrl);
LocationMode = LocationHashbangUrl;
}
$location = new LocationMode(appBase, '#' + hashPrefix);
$location.$$parse($location.$$rewrite(initialUrl));
$rootElement.on('click', function(event) {
// TODO(vojta): rewrite link when opening in new tab/window (in legacy browser)
// currently we open nice url link and redirect then
if (event.ctrlKey || event.metaKey || event.which == 2) return;
var elm = jqLite(event.target);
// traverse the DOM up to find first A tag
while (lowercase(elm[0].nodeName) !== 'a') {
// ignore rewriting if no A tag (reached root element, or no parent - removed from document)
if (elm[0] === $rootElement[0] || !(elm = elm.parent())[0]) return;
}
var absHref = elm.prop('href');
var rewrittenUrl = $location.$$rewrite(absHref);
if (absHref && !elm.attr('target') && rewrittenUrl && !event.isDefaultPrevented()) {
event.preventDefault();
if (rewrittenUrl != $browser.url()) {
// update location manually
$location.$$parse(rewrittenUrl);
$rootScope.$apply();
// hack to work around FF6 bug 684208 when scenario runner clicks on links
window.angular['ff-684208-preventDefault'] = true;
}
}
});
// rewrite hashbang url <> html5 url
if ($location.absUrl() != initialUrl) {
$browser.url($location.absUrl(), true);
}
// update $location when $browser url changes
$browser.onUrlChange(function(newUrl) {
if ($location.absUrl() != newUrl) {
if ($rootScope.$broadcast('$locationChangeStart', newUrl,
$location.absUrl()).defaultPrevented) {
$browser.url($location.absUrl());
return;
}
$rootScope.$evalAsync(function() {
var oldUrl = $location.absUrl();
$location.$$parse(newUrl);
afterLocationChange(oldUrl);
});
if (!$rootScope.$$phase) $rootScope.$digest();
}
});
// update browser
var changeCounter = 0;
$rootScope.$watch(function $locationWatch() {
var oldUrl = $browser.url();
var currentReplace = $location.$$replace;
if (!changeCounter || oldUrl != $location.absUrl()) {
changeCounter++;
$rootScope.$evalAsync(function() {
if ($rootScope.$broadcast('$locationChangeStart', $location.absUrl(), oldUrl).
defaultPrevented) {
$location.$$parse(oldUrl);
} else {
$browser.url($location.absUrl(), currentReplace);
afterLocationChange(oldUrl);
}
});
}
$location.$$replace = false;
return changeCounter;
});
return $location;
function afterLocationChange(oldUrl) {
$rootScope.$broadcast('$locationChangeSuccess', $location.absUrl(), oldUrl);
}
}];
}
/**
* @ngdoc object
* @name ng.$log
* @requires $window
*
* @description
* Simple service for logging. Default implementation safely writes the message
* into the browser's console (if present).
*
* The main purpose of this service is to simplify debugging and troubleshooting.
*
* The default is not to log `debug` messages. You can use
* {@link ng.$logProvider ng.$logProvider#debugEnabled} to change this.
*
* @example
<example>
<file name="script.js">
function LogCtrl($scope, $log) {
$scope.$log = $log;
$scope.message = 'Hello World!';
}
</file>
<file name="index.html">
<div ng-controller="LogCtrl">
<p>Reload this page with open console, enter text and hit the log button...</p>
Message:
<input type="text" ng-model="message"/>
<button ng-click="$log.log(message)">log</button>
<button ng-click="$log.warn(message)">warn</button>
<button ng-click="$log.info(message)">info</button>
<button ng-click="$log.error(message)">error</button>
</div>
</file>
</example>
*/
/**
* @ngdoc object
* @name ng.$logProvider
* @description
* Use the `$logProvider` to configure how the application logs messages
*/
function $LogProvider(){
var debug = true,
self = this;
/**
* @ngdoc property
* @name ng.$logProvider#debugEnabled
* @methodOf ng.$logProvider
* @description
* @param {string=} flag enable or disable debug level messages
* @returns {*} current value if used as getter or itself (chaining) if used as setter
*/
this.debugEnabled = function(flag) {
if (isDefined(flag)) {
debug = flag;
return this;
} else {
return debug;
}
};
this.$get = ['$window', function($window){
return {
/**
* @ngdoc method
* @name ng.$log#log
* @methodOf ng.$log
*
* @description
* Write a log message
*/
log: consoleLog('log'),
/**
* @ngdoc method
* @name ng.$log#info
* @methodOf ng.$log
*
* @description
* Write an information message
*/
info: consoleLog('info'),
/**
* @ngdoc method
* @name ng.$log#warn
* @methodOf ng.$log
*
* @description
* Write a warning message
*/
warn: consoleLog('warn'),
/**
* @ngdoc method
* @name ng.$log#error
* @methodOf ng.$log
*
* @description
* Write an error message
*/
error: consoleLog('error'),
/**
* @ngdoc method
* @name ng.$log#debug
* @methodOf ng.$log
*
* @description
* Write a debug message
*/
debug: (function () {
var fn = consoleLog('debug');
return function() {
if (debug) {
fn.apply(self, arguments);
}
};
}())
};
function formatError(arg) {
if (arg instanceof Error) {
if (arg.stack) {
arg = (arg.message && arg.stack.indexOf(arg.message) === -1)
? 'Error: ' + arg.message + '\n' + arg.stack
: arg.stack;
} else if (arg.sourceURL) {
arg = arg.message + '\n' + arg.sourceURL + ':' + arg.line;
}
}
return arg;
}
function consoleLog(type) {
var console = $window.console || {},
logFn = console[type] || console.log || noop;
if (logFn.apply) {
return function() {
var args = [];
forEach(arguments, function(arg) {
args.push(formatError(arg));
});
return logFn.apply(console, args);
};
}
// we are IE which either doesn't have window.console => this is noop and we do nothing,
// or we are IE where console.log doesn't have apply so we log at least first 2 args
return function(arg1, arg2) {
logFn(arg1, arg2 == null ? '' : arg2);
};
}
}];
}
var $parseMinErr = minErr('$parse');
var promiseWarningCache = {};
var promiseWarning;
// Sandboxing Angular Expressions
// ------------------------------
// Angular expressions are generally considered safe because these expressions only have direct
// access to $scope and locals. However, one can obtain the ability to execute arbitrary JS code by
// obtaining a reference to native JS functions such as the Function constructor, the global Window
// or Document object. In addition, many powerful functions for use by JavaScript code are
// published on scope that shouldn't be available from within an Angular expression.
//
// As an example, consider the following Angular expression:
//
// {}.toString.constructor(alert("evil JS code"))
//
// We want to prevent this type of access. For the sake of performance, during the lexing phase we
// disallow any "dotted" access to any member named "constructor" or to any member whose name begins
// or ends with an underscore. The latter allows one to exclude the private / JavaScript only API
// available on the scope and controllers from the context of an Angular expression.
//
// For reflective calls (a[b]), we check that the value of the lookup is not the Function
// constructor, Window or DOM node while evaluating the expression, which is a stronger but more
// expensive test. Since reflective calls are expensive anyway, this is not such a big deal compared
// to static dereferencing.
//
// This sandboxing technique is not perfect and doesn't aim to be. The goal is to prevent exploits
// against the expression language, but not to prevent exploits that were enabled by exposing
// sensitive JavaScript or browser apis on Scope. Exposing such objects on a Scope is never a good
// practice and therefore we are not even trying to protect against interaction with an object
// explicitly exposed in this way.
//
// A developer could foil the name check by aliasing the Function constructor under a different
// name on the scope.
//
// In general, it is not possible to access a Window object from an angular expression unless a
// window or some DOM object that has a reference to window is published onto a Scope.
function ensureSafeMemberName(name, fullExpression, allowConstructor) {
if (typeof name !== 'string' && toString.apply(name) !== "[object String]") {
return name;
}
if (name === "constructor" && !allowConstructor) {
throw $parseMinErr('isecfld',
'Referencing "constructor" field in Angular expressions is disallowed! Expression: {0}',
fullExpression);
}
if (name.charAt(0) === '_' || name.charAt(name.length-1) === '_') {
throw $parseMinErr('isecprv',
'Referencing private fields in Angular expressions is disallowed! Expression: {0}',
fullExpression);
}
return name;
}
function ensureSafeObject(obj, fullExpression) {
// nifty check if obj is Function that is fast and works across iframes and other contexts
if (obj && obj.constructor === obj) {
throw $parseMinErr('isecfn',
'Referencing Function in Angular expressions is disallowed! Expression: {0}',
fullExpression);
} else if (// isWindow(obj)
obj && obj.document && obj.location && obj.alert && obj.setInterval) {
throw $parseMinErr('isecwindow',
'Referencing the Window in Angular expressions is disallowed! Expression: {0}',
fullExpression);
} else if (// isElement(obj)
obj && (obj.nodeName || (obj.on && obj.find))) {
throw $parseMinErr('isecdom',
'Referencing DOM nodes in Angular expressions is disallowed! Expression: {0}',
fullExpression);
} else {
return obj;
}
}
var OPERATORS = {
/* jshint bitwise : false */
'null':function(){return null;},
'true':function(){return true;},
'false':function(){return false;},
undefined:noop,
'+':function(self, locals, a,b){
a=a(self, locals); b=b(self, locals);
if (isDefined(a)) {
if (isDefined(b)) {
return a + b;
}
return a;
}
return isDefined(b)?b:undefined;},
'-':function(self, locals, a,b){
a=a(self, locals); b=b(self, locals);
return (isDefined(a)?a:0)-(isDefined(b)?b:0);
},
'*':function(self, locals, a,b){return a(self, locals)*b(self, locals);},
'/':function(self, locals, a,b){return a(self, locals)/b(self, locals);},
'%':function(self, locals, a,b){return a(self, locals)%b(self, locals);},
'^':function(self, locals, a,b){return a(self, locals)^b(self, locals);},
'=':noop,
'===':function(self, locals, a, b){return a(self, locals)===b(self, locals);},
'!==':function(self, locals, a, b){return a(self, locals)!==b(self, locals);},
'==':function(self, locals, a,b){return a(self, locals)==b(self, locals);},
'!=':function(self, locals, a,b){return a(self, locals)!=b(self, locals);},
'<':function(self, locals, a,b){return a(self, locals)<b(self, locals);},
'>':function(self, locals, a,b){return a(self, locals)>b(self, locals);},
'<=':function(self, locals, a,b){return a(self, locals)<=b(self, locals);},
'>=':function(self, locals, a,b){return a(self, locals)>=b(self, locals);},
'&&':function(self, locals, a,b){return a(self, locals)&&b(self, locals);},
'||':function(self, locals, a,b){return a(self, locals)||b(self, locals);},
'&':function(self, locals, a,b){return a(self, locals)&b(self, locals);},
// '|':function(self, locals, a,b){return a|b;},
'|':function(self, locals, a,b){return b(self, locals)(self, locals, a(self, locals));},
'!':function(self, locals, a){return !a(self, locals);}
};
/* jshint bitwise: true */
var ESCAPE = {"n":"\n", "f":"\f", "r":"\r", "t":"\t", "v":"\v", "'":"'", '"':'"'};
/////////////////////////////////////////
/**
* @constructor
*/
var Lexer = function (options) {
this.options = options;
};
Lexer.prototype = {
constructor: Lexer,
lex: function (text) {
this.text = text;
this.index = 0;
this.ch = undefined;
this.lastCh = ':'; // can start regexp
this.tokens = [];
var token;
var json = [];
while (this.index < this.text.length) {
this.ch = this.text.charAt(this.index);
if (this.is('"\'')) {
this.readString(this.ch);
} else if (this.isNumber(this.ch) || this.is('.') && this.isNumber(this.peek())) {
this.readNumber();
} else if (this.isIdent(this.ch)) {
this.readIdent();
// identifiers can only be if the preceding char was a { or ,
if (this.was('{,') && json[0] === '{' &&
(token = this.tokens[this.tokens.length - 1])) {
token.json = token.text.indexOf('.') === -1;
}
} else if (this.is('(){}[].,;:?')) {
this.tokens.push({
index: this.index,
text: this.ch,
json: (this.was(':[,') && this.is('{[')) || this.is('}]:,')
});
if (this.is('{[')) json.unshift(this.ch);
if (this.is('}]')) json.shift();
this.index++;
} else if (this.isWhitespace(this.ch)) {
this.index++;
continue;
} else {
var ch2 = this.ch + this.peek();
var ch3 = ch2 + this.peek(2);
var fn = OPERATORS[this.ch];
var fn2 = OPERATORS[ch2];
var fn3 = OPERATORS[ch3];
if (fn3) {
this.tokens.push({index: this.index, text: ch3, fn: fn3});
this.index += 3;
} else if (fn2) {
this.tokens.push({index: this.index, text: ch2, fn: fn2});
this.index += 2;
} else if (fn) {
this.tokens.push({
index: this.index,
text: this.ch,
fn: fn,
json: (this.was('[,:') && this.is('+-'))
});
this.index += 1;
} else {
this.throwError('Unexpected next character ', this.index, this.index + 1);
}
}
this.lastCh = this.ch;
}
return this.tokens;
},
is: function(chars) {
return chars.indexOf(this.ch) !== -1;
},
was: function(chars) {
return chars.indexOf(this.lastCh) !== -1;
},
peek: function(i) {
var num = i || 1;
return (this.index + num < this.text.length) ? this.text.charAt(this.index + num) : false;
},
isNumber: function(ch) {
return ('0' <= ch && ch <= '9');
},
isWhitespace: function(ch) {
// IE treats non-breaking space as \u00A0
return (ch === ' ' || ch === '\r' || ch === '\t' ||
ch === '\n' || ch === '\v' || ch === '\u00A0');
},
isIdent: function(ch) {
return ('a' <= ch && ch <= 'z' ||
'A' <= ch && ch <= 'Z' ||
'_' === ch || ch === '$');
},
isExpOperator: function(ch) {
return (ch === '-' || ch === '+' || this.isNumber(ch));
},
throwError: function(error, start, end) {
end = end || this.index;
var colStr = (isDefined(start)
? 's ' + start + '-' + this.index + ' [' + this.text.substring(start, end) + ']'
: ' ' + end);
throw $parseMinErr('lexerr', 'Lexer Error: {0} at column{1} in expression [{2}].',
error, colStr, this.text);
},
readNumber: function() {
var number = '';
var start = this.index;
while (this.index < this.text.length) {
var ch = lowercase(this.text.charAt(this.index));
if (ch == '.' || this.isNumber(ch)) {
number += ch;
} else {
var peekCh = this.peek();
if (ch == 'e' && this.isExpOperator(peekCh)) {
number += ch;
} else if (this.isExpOperator(ch) &&
peekCh && this.isNumber(peekCh) &&
number.charAt(number.length - 1) == 'e') {
number += ch;
} else if (this.isExpOperator(ch) &&
(!peekCh || !this.isNumber(peekCh)) &&
number.charAt(number.length - 1) == 'e') {
this.throwError('Invalid exponent');
} else {
break;
}
}
this.index++;
}
number = 1 * number;
this.tokens.push({
index: start,
text: number,
json: true,
fn: function() { return number; }
});
},
readIdent: function() {
var parser = this;
var ident = '';
var start = this.index;
var lastDot, peekIndex, methodName, ch;
while (this.index < this.text.length) {
ch = this.text.charAt(this.index);
if (ch === '.' || this.isIdent(ch) || this.isNumber(ch)) {
if (ch === '.') lastDot = this.index;
ident += ch;
} else {
break;
}
this.index++;
}
//check if this is not a method invocation and if it is back out to last dot
if (lastDot) {
peekIndex = this.index;
while (peekIndex < this.text.length) {
ch = this.text.charAt(peekIndex);
if (ch === '(') {
methodName = ident.substr(lastDot - start + 1);
ident = ident.substr(0, lastDot - start);
this.index = peekIndex;
break;
}
if (this.isWhitespace(ch)) {
peekIndex++;
} else {
break;
}
}
}
var token = {
index: start,
text: ident
};
// OPERATORS is our own object so we don't need to use special hasOwnPropertyFn
if (OPERATORS.hasOwnProperty(ident)) {
token.fn = OPERATORS[ident];
token.json = OPERATORS[ident];
} else {
var getter = getterFn(ident, this.options, this.text);
token.fn = extend(function(self, locals) {
return (getter(self, locals));
}, {
assign: function(self, value) {
return setter(self, ident, value, parser.text, parser.options);
}
});
}
this.tokens.push(token);
if (methodName) {
this.tokens.push({
index:lastDot,
text: '.',
json: false
});
this.tokens.push({
index: lastDot + 1,
text: methodName,
json: false
});
}
},
readString: function(quote) {
var start = this.index;
this.index++;
var string = '';
var rawString = quote;
var escape = false;
while (this.index < this.text.length) {
var ch = this.text.charAt(this.index);
rawString += ch;
if (escape) {
if (ch === 'u') {
var hex = this.text.substring(this.index + 1, this.index + 5);
if (!hex.match(/[\da-f]{4}/i))
this.throwError('Invalid unicode escape [\\u' + hex + ']');
this.index += 4;
string += String.fromCharCode(parseInt(hex, 16));
} else {
var rep = ESCAPE[ch];
if (rep) {
string += rep;
} else {
string += ch;
}
}
escape = false;
} else if (ch === '\\') {
escape = true;
} else if (ch === quote) {
this.index++;
this.tokens.push({
index: start,
text: rawString,
string: string,
json: true,
fn: function() { return string; }
});
return;
} else {
string += ch;
}
this.index++;
}
this.throwError('Unterminated quote', start);
}
};
/**
* @constructor
*/
var Parser = function (lexer, $filter, options) {
this.lexer = lexer;
this.$filter = $filter;
this.options = options;
};
Parser.ZERO = function () { return 0; };
Parser.prototype = {
constructor: Parser,
parse: function (text, json) {
this.text = text;
//TODO(i): strip all the obsolte json stuff from this file
this.json = json;
this.tokens = this.lexer.lex(text);
if (json) {
// The extra level of aliasing is here, just in case the lexer misses something, so that
// we prevent any accidental execution in JSON.
this.assignment = this.logicalOR;
this.functionCall =
this.fieldAccess =
this.objectIndex =
this.filterChain = function() {
this.throwError('is not valid json', {text: text, index: 0});
};
}
var value = json ? this.primary() : this.statements();
if (this.tokens.length !== 0) {
this.throwError('is an unexpected token', this.tokens[0]);
}
value.literal = !!value.literal;
value.constant = !!value.constant;
return value;
},
primary: function () {
var primary;
if (this.expect('(')) {
primary = this.filterChain();
this.consume(')');
} else if (this.expect('[')) {
primary = this.arrayDeclaration();
} else if (this.expect('{')) {
primary = this.object();
} else {
var token = this.expect();
primary = token.fn;
if (!primary) {
this.throwError('not a primary expression', token);
}
if (token.json) {
primary.constant = true;
primary.literal = true;
}
}
var next, context;
while ((next = this.expect('(', '[', '.'))) {
if (next.text === '(') {
primary = this.functionCall(primary, context);
context = null;
} else if (next.text === '[') {
context = primary;
primary = this.objectIndex(primary);
} else if (next.text === '.') {
context = primary;
primary = this.fieldAccess(primary);
} else {
this.throwError('IMPOSSIBLE');
}
}
return primary;
},
throwError: function(msg, token) {
throw $parseMinErr('syntax',
'Syntax Error: Token \'{0}\' {1} at column {2} of the expression [{3}] starting at [{4}].',
token.text, msg, (token.index + 1), this.text, this.text.substring(token.index));
},
peekToken: function() {
if (this.tokens.length === 0)
throw $parseMinErr('ueoe', 'Unexpected end of expression: {0}', this.text);
return this.tokens[0];
},
peek: function(e1, e2, e3, e4) {
if (this.tokens.length > 0) {
var token = this.tokens[0];
var t = token.text;
if (t === e1 || t === e2 || t === e3 || t === e4 ||
(!e1 && !e2 && !e3 && !e4)) {
return token;
}
}
return false;
},
expect: function(e1, e2, e3, e4){
var token = this.peek(e1, e2, e3, e4);
if (token) {
if (this.json && !token.json) {
this.throwError('is not valid json', token);
}
this.tokens.shift();
return token;
}
return false;
},
consume: function(e1){
if (!this.expect(e1)) {
this.throwError('is unexpected, expecting [' + e1 + ']', this.peek());
}
},
unaryFn: function(fn, right) {
return extend(function(self, locals) {
return fn(self, locals, right);
}, {
constant:right.constant
});
},
ternaryFn: function(left, middle, right){
return extend(function(self, locals){
return left(self, locals) ? middle(self, locals) : right(self, locals);
}, {
constant: left.constant && middle.constant && right.constant
});
},
binaryFn: function(left, fn, right) {
return extend(function(self, locals) {
return fn(self, locals, left, right);
}, {
constant:left.constant && right.constant
});
},
statements: function() {
var statements = [];
while (true) {
if (this.tokens.length > 0 && !this.peek('}', ')', ';', ']'))
statements.push(this.filterChain());
if (!this.expect(';')) {
// optimize for the common case where there is only one statement.
// TODO(size): maybe we should not support multiple statements?
return (statements.length === 1)
? statements[0]
: function(self, locals) {
var value;
for (var i = 0; i < statements.length; i++) {
var statement = statements[i];
if (statement) {
value = statement(self, locals);
}
}
return value;
};
}
}
},
filterChain: function() {
var left = this.expression();
var token;
while (true) {
if ((token = this.expect('|'))) {
left = this.binaryFn(left, token.fn, this.filter());
} else {
return left;
}
}
},
filter: function() {
var token = this.expect();
var fn = this.$filter(token.text);
var argsFn = [];
while (true) {
if ((token = this.expect(':'))) {
argsFn.push(this.expression());
} else {
var fnInvoke = function(self, locals, input) {
var args = [input];
for (var i = 0; i < argsFn.length; i++) {
args.push(argsFn[i](self, locals));
}
return fn.apply(self, args);
};
return function() {
return fnInvoke;
};
}
}
},
expression: function() {
return this.assignment();
},
assignment: function() {
var left = this.ternary();
var right;
var token;
if ((token = this.expect('='))) {
if (!left.assign) {
this.throwError('implies assignment but [' +
this.text.substring(0, token.index) + '] can not be assigned to', token);
}
right = this.ternary();
return function(scope, locals) {
return left.assign(scope, right(scope, locals), locals);
};
}
return left;
},
ternary: function() {
var left = this.logicalOR();
var middle;
var token;
if ((token = this.expect('?'))) {
middle = this.ternary();
if ((token = this.expect(':'))) {
return this.ternaryFn(left, middle, this.ternary());
} else {
this.throwError('expected :', token);
}
} else {
return left;
}
},
logicalOR: function() {
var left = this.logicalAND();
var token;
while (true) {
if ((token = this.expect('||'))) {
left = this.binaryFn(left, token.fn, this.logicalAND());
} else {
return left;
}
}
},
logicalAND: function() {
var left = this.equality();
var token;
if ((token = this.expect('&&'))) {
left = this.binaryFn(left, token.fn, this.logicalAND());
}
return left;
},
equality: function() {
var left = this.relational();
var token;
if ((token = this.expect('==','!=','===','!=='))) {
left = this.binaryFn(left, token.fn, this.equality());
}
return left;
},
relational: function() {
var left = this.additive();
var token;
if ((token = this.expect('<', '>', '<=', '>='))) {
left = this.binaryFn(left, token.fn, this.relational());
}
return left;
},
additive: function() {
var left = this.multiplicative();
var token;
while ((token = this.expect('+','-'))) {
left = this.binaryFn(left, token.fn, this.multiplicative());
}
return left;
},
multiplicative: function() {
var left = this.unary();
var token;
while ((token = this.expect('*','/','%'))) {
left = this.binaryFn(left, token.fn, this.unary());
}
return left;
},
unary: function() {
var token;
if (this.expect('+')) {
return this.primary();
} else if ((token = this.expect('-'))) {
return this.binaryFn(Parser.ZERO, token.fn, this.unary());
} else if ((token = this.expect('!'))) {
return this.unaryFn(token.fn, this.unary());
} else {
return this.primary();
}
},
fieldAccess: function(object) {
var parser = this;
var field = this.expect().text;
var getter = getterFn(field, this.options, this.text);
return extend(function(scope, locals, self) {
return getter(self || object(scope, locals), locals);
}, {
assign: function(scope, value, locals) {
return setter(object(scope, locals), field, value, parser.text, parser.options);
}
});
},
objectIndex: function(obj) {
var parser = this;
var indexFn = this.expression();
this.consume(']');
return extend(function(self, locals) {
var o = obj(self, locals),
// In the getter, we will not block looking up "constructor" by name in order to support user defined
// constructors. However, if value looked up is the Function constructor, we will still block it in the
// ensureSafeObject call right after we look up o[i] (a few lines below.)
i = ensureSafeMemberName(indexFn(self, locals), parser.text, true /* allowConstructor */),
v, p;
if (!o) return undefined;
v = ensureSafeObject(o[i], parser.text);
if (v && v.then && parser.options.unwrapPromises) {
p = v;
if (!('$$v' in v)) {
p.$$v = undefined;
p.then(function(val) { p.$$v = val; });
}
v = v.$$v;
}
return v;
}, {
assign: function(self, value, locals) {
var key = ensureSafeMemberName(indexFn(self, locals), parser.text);
// prevent overwriting of Function.constructor which would break ensureSafeObject check
var safe = ensureSafeObject(obj(self, locals), parser.text);
return safe[key] = value;
}
});
},
functionCall: function(fn, contextGetter) {
var argsFn = [];
if (this.peekToken().text !== ')') {
do {
argsFn.push(this.expression());
} while (this.expect(','));
}
this.consume(')');
var parser = this;
return function(scope, locals) {
var args = [];
var context = contextGetter ? contextGetter(scope, locals) : scope;
for (var i = 0; i < argsFn.length; i++) {
args.push(argsFn[i](scope, locals));
}
var fnPtr = fn(scope, locals, context) || noop;
ensureSafeObject(context, parser.text);
ensureSafeObject(fnPtr, parser.text);
// IE stupidity! (IE doesn't have apply for some native functions)
var v = fnPtr.apply
? fnPtr.apply(context, args)
: fnPtr(args[0], args[1], args[2], args[3], args[4]);
return ensureSafeObject(v, parser.text);
};
},
// This is used with json array declaration
arrayDeclaration: function () {
var elementFns = [];
var allConstant = true;
if (this.peekToken().text !== ']') {
do {
var elementFn = this.expression();
elementFns.push(elementFn);
if (!elementFn.constant) {
allConstant = false;
}
} while (this.expect(','));
}
this.consume(']');
return extend(function(self, locals) {
var array = [];
for (var i = 0; i < elementFns.length; i++) {
array.push(elementFns[i](self, locals));
}
return array;
}, {
literal: true,
constant: allConstant
});
},
object: function () {
var keyValues = [];
var allConstant = true;
if (this.peekToken().text !== '}') {
do {
var token = this.expect(),
key = token.string || token.text;
this.consume(':');
var value = this.expression();
keyValues.push({key: key, value: value});
if (!value.constant) {
allConstant = false;
}
} while (this.expect(','));
}
this.consume('}');
return extend(function(self, locals) {
var object = {};
for (var i = 0; i < keyValues.length; i++) {
var keyValue = keyValues[i];
object[keyValue.key] = keyValue.value(self, locals);
}
return object;
}, {
literal: true,
constant: allConstant
});
}
};
//////////////////////////////////////////////////
// Parser helper functions
//////////////////////////////////////////////////
function setter(obj, path, setValue, fullExp, options) {
//needed?
options = options || {};
var element = path.split('.'), key;
for (var i = 0; element.length > 1; i++) {
key = ensureSafeMemberName(element.shift(), fullExp);
var propertyObj = obj[key];
if (!propertyObj) {
propertyObj = {};
obj[key] = propertyObj;
}
obj = propertyObj;
if (obj.then && options.unwrapPromises) {
promiseWarning(fullExp);
if (!("$$v" in obj)) {
(function(promise) {
promise.then(function(val) { promise.$$v = val; }); }
)(obj);
}
if (obj.$$v === undefined) {
obj.$$v = {};
}
obj = obj.$$v;
}
}
key = ensureSafeMemberName(element.shift(), fullExp);
obj[key] = setValue;
return setValue;
}
var getterFnCache = {};
/**
* Implementation of the "Black Hole" variant from:
* - http://jsperf.com/angularjs-parse-getter/4
* - http://jsperf.com/path-evaluation-simplified/7
*/
function cspSafeGetterFn(key0, key1, key2, key3, key4, fullExp, options) {
ensureSafeMemberName(key0, fullExp);
ensureSafeMemberName(key1, fullExp);
ensureSafeMemberName(key2, fullExp);
ensureSafeMemberName(key3, fullExp);
ensureSafeMemberName(key4, fullExp);
return !options.unwrapPromises
? function cspSafeGetter(scope, locals) {
var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope;
if (pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key0];
if (!key1 || pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key1];
if (!key2 || pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key2];
if (!key3 || pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key3];
if (!key4 || pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key4];
return pathVal;
}
: function cspSafePromiseEnabledGetter(scope, locals) {
var pathVal = (locals && locals.hasOwnProperty(key0)) ? locals : scope,
promise;
if (pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key0];
if (pathVal && pathVal.then) {
promiseWarning(fullExp);
if (!("$$v" in pathVal)) {
promise = pathVal;
promise.$$v = undefined;
promise.then(function(val) { promise.$$v = val; });
}
pathVal = pathVal.$$v;
}
if (!key1 || pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key1];
if (pathVal && pathVal.then) {
promiseWarning(fullExp);
if (!("$$v" in pathVal)) {
promise = pathVal;
promise.$$v = undefined;
promise.then(function(val) { promise.$$v = val; });
}
pathVal = pathVal.$$v;
}
if (!key2 || pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key2];
if (pathVal && pathVal.then) {
promiseWarning(fullExp);
if (!("$$v" in pathVal)) {
promise = pathVal;
promise.$$v = undefined;
promise.then(function(val) { promise.$$v = val; });
}
pathVal = pathVal.$$v;
}
if (!key3 || pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key3];
if (pathVal && pathVal.then) {
promiseWarning(fullExp);
if (!("$$v" in pathVal)) {
promise = pathVal;
promise.$$v = undefined;
promise.then(function(val) { promise.$$v = val; });
}
pathVal = pathVal.$$v;
}
if (!key4 || pathVal === null || pathVal === undefined) return pathVal;
pathVal = pathVal[key4];
if (pathVal && pathVal.then) {
promiseWarning(fullExp);
if (!("$$v" in pathVal)) {
promise = pathVal;
promise.$$v = undefined;
promise.then(function(val) { promise.$$v = val; });
}
pathVal = pathVal.$$v;
}
return pathVal;
};
}
function getterFn(path, options, fullExp) {
// Check whether the cache has this getter already.
// We can use hasOwnProperty directly on the cache because we ensure,
// see below, that the cache never stores a path called 'hasOwnProperty'
if (getterFnCache.hasOwnProperty(path)) {
return getterFnCache[path];
}
var pathKeys = path.split('.'),
pathKeysLength = pathKeys.length,
fn;
if (options.csp) {
if (pathKeysLength < 6) {
fn = cspSafeGetterFn(pathKeys[0], pathKeys[1], pathKeys[2], pathKeys[3], pathKeys[4], fullExp,
options);
} else {
fn = function(scope, locals) {
var i = 0, val;
do {
val = cspSafeGetterFn(pathKeys[i++], pathKeys[i++], pathKeys[i++], pathKeys[i++],
pathKeys[i++], fullExp, options)(scope, locals);
locals = undefined; // clear after first iteration
scope = val;
} while (i < pathKeysLength);
return val;
};
}
} else {
var code = 'var l, fn, p;\n';
forEach(pathKeys, function(key, index) {
ensureSafeMemberName(key, fullExp);
code += 'if(s === null || s === undefined) return s;\n' +
'l=s;\n' +
's='+ (index
// we simply dereference 's' on any .dot notation
? 's'
// but if we are first then we check locals first, and if so read it first
: '((k&&k.hasOwnProperty("' + key + '"))?k:s)') + '["' + key + '"]' + ';\n' +
(options.unwrapPromises
? 'if (s && s.then) {\n' +
' pw("' + fullExp.replace(/\"/g, '\\"') + '");\n' +
' if (!("$$v" in s)) {\n' +
' p=s;\n' +
' p.$$v = undefined;\n' +
' p.then(function(v) {p.$$v=v;});\n' +
'}\n' +
' s=s.$$v\n' +
'}\n'
: '');
});
code += 'return s;';
/* jshint -W054 */
var evaledFnGetter = new Function('s', 'k', 'pw', code); // s=scope, k=locals, pw=promiseWarning
/* jshint +W054 */
evaledFnGetter.toString = function() { return code; };
fn = function(scope, locals) {
return evaledFnGetter(scope, locals, promiseWarning);
};
}
// Only cache the value if it's not going to mess up the cache object
// This is more performant that using Object.prototype.hasOwnProperty.call
if (path !== 'hasOwnProperty') {
getterFnCache[path] = fn;
}
return fn;
}
///////////////////////////////////
/**
* @ngdoc function
* @name ng.$parse
* @function
*
* @description
*
* Converts Angular {@link guide/expression expression} into a function.
*
* <pre>
* var getter = $parse('user.name');
* var setter = getter.assign;
* var context = {user:{name:'angular'}};
* var locals = {user:{name:'local'}};
*
* expect(getter(context)).toEqual('angular');
* setter(context, 'newValue');
* expect(context.user.name).toEqual('newValue');
* expect(getter(context, locals)).toEqual('local');
* </pre>
*
*
* @param {string} expression String expression to compile.
* @returns {function(context, locals)} a function which represents the compiled expression:
*
* * `context` – `{object}` – an object against which any expressions embedded in the strings
* are evaluated against (typically a scope object).
* * `locals` – `{object=}` – local variables context object, useful for overriding values in
* `context`.
*
* The returned function also has the following properties:
* * `literal` – `{boolean}` – whether the expression's top-level node is a JavaScript
* literal.
* * `constant` – `{boolean}` – whether the expression is made entirely of JavaScript
* constant literals.
* * `assign` – `{?function(context, value)}` – if the expression is assignable, this will be
* set to a function to change its value on the given context.
*
*/
/**
* @ngdoc object
* @name ng.$parseProvider
* @function
*
* @description
* `$parseProvider` can be used for configuring the default behavior of the {@link ng.$parse $parse}
* service.
*/
function $ParseProvider() {
var cache = {};
var $parseOptions = {
csp: false,
unwrapPromises: false,
logPromiseWarnings: true
};
/**
* @deprecated Promise unwrapping via $parse is deprecated and will be removed in the future.
*
* @ngdoc method
* @name ng.$parseProvider#unwrapPromises
* @methodOf ng.$parseProvider
* @description
*
* **This feature is deprecated, see deprecation notes below for more info**
*
* If set to true (default is false), $parse will unwrap promises automatically when a promise is
* found at any part of the expression. In other words, if set to true, the expression will always
* result in a non-promise value.
*
* While the promise is unresolved, it's treated as undefined, but once resolved and fulfilled,
* the fulfillment value is used in place of the promise while evaluating the expression.
*
* **Deprecation notice**
*
* This is a feature that didn't prove to be wildly useful or popular, primarily because of the
* dichotomy between data access in templates (accessed as raw values) and controller code
* (accessed as promises).
*
* In most code we ended up resolving promises manually in controllers anyway and thus unifying
* the model access there.
*
* Other downsides of automatic promise unwrapping:
*
* - when building components it's often desirable to receive the raw promises
* - adds complexity and slows down expression evaluation
* - makes expression code pre-generation unattractive due to the amount of code that needs to be
* generated
* - makes IDE auto-completion and tool support hard
*
* **Warning Logs**
*
* If the unwrapping is enabled, Angular will log a warning about each expression that unwraps a
* promise (to reduce the noise, each expression is logged only once). To disable this logging use
* `$parseProvider.logPromiseWarnings(false)` api.
*
*
* @param {boolean=} value New value.
* @returns {boolean|self} Returns the current setting when used as getter and self if used as
* setter.
*/
this.unwrapPromises = function(value) {
if (isDefined(value)) {
$parseOptions.unwrapPromises = !!value;
return this;
} else {
return $parseOptions.unwrapPromises;
}
};
/**
* @deprecated Promise unwrapping via $parse is deprecated and will be removed in the future.
*
* @ngdoc method
* @name ng.$parseProvider#logPromiseWarnings
* @methodOf ng.$parseProvider
* @description
*
* Controls whether Angular should log a warning on any encounter of a promise in an expression.
*
* The default is set to `true`.
*
* This setting applies only if `$parseProvider.unwrapPromises` setting is set to true as well.
*
* @param {boolean=} value New value.
* @returns {boolean|self} Returns the current setting when used as getter and self if used as
* setter.
*/
this.logPromiseWarnings = function(value) {
if (isDefined(value)) {
$parseOptions.logPromiseWarnings = value;
return this;
} else {
return $parseOptions.logPromiseWarnings;
}
};
this.$get = ['$filter', '$sniffer', '$log', function($filter, $sniffer, $log) {
$parseOptions.csp = $sniffer.csp;
promiseWarning = function promiseWarningFn(fullExp) {
if (!$parseOptions.logPromiseWarnings || promiseWarningCache.hasOwnProperty(fullExp)) return;
promiseWarningCache[fullExp] = true;
$log.warn('[$parse] Promise found in the expression `' + fullExp + '`. ' +
'Automatic unwrapping of promises in Angular expressions is deprecated.');
};
return function(exp) {
var parsedExpression;
switch (typeof exp) {
case 'string':
if (cache.hasOwnProperty(exp)) {
return cache[exp];
}
var lexer = new Lexer($parseOptions);
var parser = new Parser(lexer, $filter, $parseOptions);
parsedExpression = parser.parse(exp, false);
if (exp !== 'hasOwnProperty') {
// Only cache the value if it's not going to mess up the cache object
// This is more performant that using Object.prototype.hasOwnProperty.call
cache[exp] = parsedExpression;
}
return parsedExpression;
case 'function':
return exp;
default:
return noop;
}
};
}];
}
/**
* @ngdoc service
* @name ng.$q
* @requires $rootScope
*
* @description
* A promise/deferred implementation inspired by [Kris Kowal's Q](https://github.com/kriskowal/q).
*
* [The CommonJS Promise proposal](http://wiki.commonjs.org/wiki/Promises) describes a promise as an
* interface for interacting with an object that represents the result of an action that is
* performed asynchronously, and may or may not be finished at any given point in time.
*
* From the perspective of dealing with error handling, deferred and promise APIs are to
* asynchronous programming what `try`, `catch` and `throw` keywords are to synchronous programming.
*
* <pre>
* // for the purpose of this example let's assume that variables `$q` and `scope` are
* // available in the current lexical scope (they could have been injected or passed in).
*
* function asyncGreet(name) {
* var deferred = $q.defer();
*
* setTimeout(function() {
* // since this fn executes async in a future turn of the event loop, we need to wrap
* // our code into an $apply call so that the model changes are properly observed.
* scope.$apply(function() {
* deferred.notify('About to greet ' + name + '.');
*
* if (okToGreet(name)) {
* deferred.resolve('Hello, ' + name + '!');
* } else {
* deferred.reject('Greeting ' + name + ' is not allowed.');
* }
* });
* }, 1000);
*
* return deferred.promise;
* }
*
* var promise = asyncGreet('Robin Hood');
* promise.then(function(greeting) {
* alert('Success: ' + greeting);
* }, function(reason) {
* alert('Failed: ' + reason);
* }, function(update) {
* alert('Got notification: ' + update);
* });
* </pre>
*
* At first it might not be obvious why this extra complexity is worth the trouble. The payoff
* comes in the way of guarantees that promise and deferred APIs make, see
* https://github.com/kriskowal/uncommonjs/blob/master/promises/specification.md.
*
* Additionally the promise api allows for composition that is very hard to do with the
* traditional callback ([CPS](http://en.wikipedia.org/wiki/Continuation-passing_style)) approach.
* For more on this please see the [Q documentation](https://github.com/kriskowal/q) especially the
* section on serial or parallel joining of promises.
*
*
* # The Deferred API
*
* A new instance of deferred is constructed by calling `$q.defer()`.
*
* The purpose of the deferred object is to expose the associated Promise instance as well as APIs
* that can be used for signaling the successful or unsuccessful completion, as well as the status
* of the task.
*
* **Methods**
*
* - `resolve(value)` – resolves the derived promise with the `value`. If the value is a rejection
* constructed via `$q.reject`, the promise will be rejected instead.
* - `reject(reason)` – rejects the derived promise with the `reason`. This is equivalent to
* resolving it with a rejection constructed via `$q.reject`.
* - `notify(value)` - provides updates on the status of the promises execution. This may be called
* multiple times before the promise is either resolved or rejected.
*
* **Properties**
*
* - promise – `{Promise}` – promise object associated with this deferred.
*
*
* # The Promise API
*
* A new promise instance is created when a deferred instance is created and can be retrieved by
* calling `deferred.promise`.
*
* The purpose of the promise object is to allow for interested parties to get access to the result
* of the deferred task when it completes.
*
* **Methods**
*
* - `then(successCallback, errorCallback, notifyCallback)` – regardless of when the promise was or
* will be resolved or rejected, `then` calls one of the success or error callbacks asynchronously
* as soon as the result is available. The callbacks are called with a single argument: the result
* or rejection reason. Additionally, the notify callback may be called zero or more times to
* provide a progress indication, before the promise is resolved or rejected.
*
* This method *returns a new promise* which is resolved or rejected via the return value of the
* `successCallback`, `errorCallback`. It also notifies via the return value of the
* `notifyCallback` method. The promise can not be resolved or rejected from the notifyCallback
* method.
*
* - `catch(errorCallback)` – shorthand for `promise.then(null, errorCallback)`
*
* - `finally(callback)` – allows you to observe either the fulfillment or rejection of a promise,
* but to do so without modifying the final value. This is useful to release resources or do some
* clean-up that needs to be done whether the promise was rejected or resolved. See the [full
* specification](https://github.com/kriskowal/q/wiki/API-Reference#promisefinallycallback) for
* more information.
*
* Because `finally` is a reserved word in JavaScript and reserved keywords are not supported as
* property names by ES3, you'll need to invoke the method like `promise['finally'](callback)` to
* make your code IE8 compatible.
*
* # Chaining promises
*
* Because calling the `then` method of a promise returns a new derived promise, it is easily
* possible to create a chain of promises:
*
* <pre>
* promiseB = promiseA.then(function(result) {
* return result + 1;
* });
*
* // promiseB will be resolved immediately after promiseA is resolved and its value
* // will be the result of promiseA incremented by 1
* </pre>
*
* It is possible to create chains of any length and since a promise can be resolved with another
* promise (which will defer its resolution further), it is possible to pause/defer resolution of
* the promises at any point in the chain. This makes it possible to implement powerful APIs like
* $http's response interceptors.
*
*
* # Differences between Kris Kowal's Q and $q
*
* There are three main differences:
*
* - $q is integrated with the {@link ng.$rootScope.Scope} Scope model observation
* mechanism in angular, which means faster propagation of resolution or rejection into your
* models and avoiding unnecessary browser repaints, which would result in flickering UI.
* - Q has many more features than $q, but that comes at a cost of bytes. $q is tiny, but contains
* all the important functionality needed for common async tasks.
*
* # Testing
*
* <pre>
* it('should simulate promise', inject(function($q, $rootScope) {
* var deferred = $q.defer();
* var promise = deferred.promise;
* var resolvedValue;
*
* promise.then(function(value) { resolvedValue = value; });
* expect(resolvedValue).toBeUndefined();
*
* // Simulate resolving of promise
* deferred.resolve(123);
* // Note that the 'then' function does not get called synchronously.
* // This is because we want the promise API to always be async, whether or not
* // it got called synchronously or asynchronously.
* expect(resolvedValue).toBeUndefined();
*
* // Propagate promise resolution to 'then' functions using $apply().
* $rootScope.$apply();
* expect(resolvedValue).toEqual(123);
* });
* </pre>
*/
function $QProvider() {
this.$get = ['$rootScope', '$exceptionHandler', function($rootScope, $exceptionHandler) {
return qFactory(function(callback) {
$rootScope.$evalAsync(callback);
}, $exceptionHandler);
}];
}
/**
* Constructs a promise manager.
*
* @param {function(function)} nextTick Function for executing functions in the next turn.
* @param {function(...*)} exceptionHandler Function into which unexpected exceptions are passed for
* debugging purposes.
* @returns {object} Promise manager.
*/
function qFactory(nextTick, exceptionHandler) {
/**
* @ngdoc
* @name ng.$q#defer
* @methodOf ng.$q
* @description
* Creates a `Deferred` object which represents a task which will finish in the future.
*
* @returns {Deferred} Returns a new instance of deferred.
*/
var defer = function() {
var pending = [],
value, deferred;
deferred = {
resolve: function(val) {
if (pending) {
var callbacks = pending;
pending = undefined;
value = ref(val);
if (callbacks.length) {
nextTick(function() {
var callback;
for (var i = 0, ii = callbacks.length; i < ii; i++) {
callback = callbacks[i];
value.then(callback[0], callback[1], callback[2]);
}
});
}
}
},
reject: function(reason) {
deferred.resolve(reject(reason));
},
notify: function(progress) {
if (pending) {
var callbacks = pending;
if (pending.length) {
nextTick(function() {
var callback;
for (var i = 0, ii = callbacks.length; i < ii; i++) {
callback = callbacks[i];
callback[2](progress);
}
});
}
}
},
promise: {
then: function(callback, errback, progressback) {
var result = defer();
var wrappedCallback = function(value) {
try {
result.resolve((isFunction(callback) ? callback : defaultCallback)(value));
} catch(e) {
result.reject(e);
exceptionHandler(e);
}
};
var wrappedErrback = function(reason) {
try {
result.resolve((isFunction(errback) ? errback : defaultErrback)(reason));
} catch(e) {
result.reject(e);
exceptionHandler(e);
}
};
var wrappedProgressback = function(progress) {
try {
result.notify((isFunction(progressback) ? progressback : defaultCallback)(progress));
} catch(e) {
exceptionHandler(e);
}
};
if (pending) {
pending.push([wrappedCallback, wrappedErrback, wrappedProgressback]);
} else {
value.then(wrappedCallback, wrappedErrback, wrappedProgressback);
}
return result.promise;
},
"catch": function(callback) {
return this.then(null, callback);
},
"finally": function(callback) {
function makePromise(value, resolved) {
var result = defer();
if (resolved) {
result.resolve(value);
} else {
result.reject(value);
}
return result.promise;
}
function handleCallback(value, isResolved) {
var callbackOutput = null;
try {
callbackOutput = (callback ||defaultCallback)();
} catch(e) {
return makePromise(e, false);
}
if (callbackOutput && isFunction(callbackOutput.then)) {
return callbackOutput.then(function() {
return makePromise(value, isResolved);
}, function(error) {
return makePromise(error, false);
});
} else {
return makePromise(value, isResolved);
}
}
return this.then(function(value) {
return handleCallback(value, true);
}, function(error) {
return handleCallback(error, false);
});
}
}
};
return deferred;
};
var ref = function(value) {
if (value && isFunction(value.then)) return value;
return {
then: function(callback) {
var result = defer();
nextTick(function() {
result.resolve(callback(value));
});
return result.promise;
}
};
};
/**
* @ngdoc
* @name ng.$q#reject
* @methodOf ng.$q
* @description
* Creates a promise that is resolved as rejected with the specified `reason`. This api should be
* used to forward rejection in a chain of promises. If you are dealing with the last promise in
* a promise chain, you don't need to worry about it.
*
* When comparing deferreds/promises to the familiar behavior of try/catch/throw, think of
* `reject` as the `throw` keyword in JavaScript. This also means that if you "catch" an error via
* a promise error callback and you want to forward the error to the promise derived from the
* current promise, you have to "rethrow" the error by returning a rejection constructed via
* `reject`.
*
* <pre>
* promiseB = promiseA.then(function(result) {
* // success: do something and resolve promiseB
* // with the old or a new result
* return result;
* }, function(reason) {
* // error: handle the error if possible and
* // resolve promiseB with newPromiseOrValue,
* // otherwise forward the rejection to promiseB
* if (canHandle(reason)) {
* // handle the error and recover
* return newPromiseOrValue;
* }
* return $q.reject(reason);
* });
* </pre>
*
* @param {*} reason Constant, message, exception or an object representing the rejection reason.
* @returns {Promise} Returns a promise that was already resolved as rejected with the `reason`.
*/
var reject = function(reason) {
return {
then: function(callback, errback) {
var result = defer();
nextTick(function() {
try {
result.resolve((isFunction(errback) ? errback : defaultErrback)(reason));
} catch(e) {
result.reject(e);
exceptionHandler(e);
}
});
return result.promise;
}
};
};
/**
* @ngdoc
* @name ng.$q#when
* @methodOf ng.$q
* @description
* Wraps an object that might be a value or a (3rd party) then-able promise into a $q promise.
* This is useful when you are dealing with an object that might or might not be a promise, or if
* the promise comes from a source that can't be trusted.
*
* @param {*} value Value or a promise
* @returns {Promise} Returns a promise of the passed value or promise
*/
var when = function(value, callback, errback, progressback) {
var result = defer(),
done;
var wrappedCallback = function(value) {
try {
return (isFunction(callback) ? callback : defaultCallback)(value);
} catch (e) {
exceptionHandler(e);
return reject(e);
}
};
var wrappedErrback = function(reason) {
try {
return (isFunction(errback) ? errback : defaultErrback)(reason);
} catch (e) {
exceptionHandler(e);
return reject(e);
}
};
var wrappedProgressback = function(progress) {
try {
return (isFunction(progressback) ? progressback : defaultCallback)(progress);
} catch (e) {
exceptionHandler(e);
}
};
nextTick(function() {
ref(value).then(function(value) {
if (done) return;
done = true;
result.resolve(ref(value).then(wrappedCallback, wrappedErrback, wrappedProgressback));
}, function(reason) {
if (done) return;
done = true;
result.resolve(wrappedErrback(reason));
}, function(progress) {
if (done) return;
result.notify(wrappedProgressback(progress));
});
});
return result.promise;
};
function defaultCallback(value) {
return value;
}
function defaultErrback(reason) {
return reject(reason);
}
/**
* @ngdoc
* @name ng.$q#all
* @methodOf ng.$q
* @description
* Combines multiple promises into a single promise that is resolved when all of the input
* promises are resolved.
*
* @param {Array.<Promise>|Object.<Promise>} promises An array or hash of promises.
* @returns {Promise} Returns a single promise that will be resolved with an array/hash of values,
* each value corresponding to the promise at the same index/key in the `promises` array/hash.
* If any of the promises is resolved with a rejection, this resulting promise will be rejected
* with the same rejection value.
*/
function all(promises) {
var deferred = defer(),
counter = 0,
results = isArray(promises) ? [] : {};
forEach(promises, function(promise, key) {
counter++;
ref(promise).then(function(value) {
if (results.hasOwnProperty(key)) return;
results[key] = value;
if (!(--counter)) deferred.resolve(results);
}, function(reason) {
if (results.hasOwnProperty(key)) return;
deferred.reject(reason);
});
});
if (counter === 0) {
deferred.resolve(results);
}
return deferred.promise;
}
return {
defer: defer,
reject: reject,
when: when,
all: all
};
}
/**
* DESIGN NOTES
*
* The design decisions behind the scope are heavily favored for speed and memory consumption.
*
* The typical use of scope is to watch the expressions, which most of the time return the same
* value as last time so we optimize the operation.
*
* Closures construction is expensive in terms of speed as well as memory:
* - No closures, instead use prototypical inheritance for API
* - Internal state needs to be stored on scope directly, which means that private state is
* exposed as $$____ properties
*
* Loop operations are optimized by using while(count--) { ... }
* - this means that in order to keep the same order of execution as addition we have to add
* items to the array at the beginning (shift) instead of at the end (push)
*
* Child scopes are created and removed often
* - Using an array would be slow since inserts in middle are expensive so we use linked list
*
* There are few watches then a lot of observers. This is why you don't want the observer to be
* implemented in the same way as watch. Watch requires return of initialization function which
* are expensive to construct.
*/
/**
* @ngdoc object
* @name ng.$rootScopeProvider
* @description
*
* Provider for the $rootScope service.
*/
/**
* @ngdoc function
* @name ng.$rootScopeProvider#digestTtl
* @methodOf ng.$rootScopeProvider
* @description
*
* Sets the number of `$digest` iterations the scope should attempt to execute before giving up and
* assuming that the model is unstable.
*
* The current default is 10 iterations.
*
* In complex applications it's possible that the dependencies between `$watch`s will result in
* several digest iterations. However if an application needs more than the default 10 digest
* iterations for its model to stabilize then you should investigate what is causing the model to
* continuously change during the digest.
*
* Increasing the TTL could have performance implications, so you should not change it without
* proper justification.
*
* @param {number} limit The number of digest iterations.
*/
/**
* @ngdoc object
* @name ng.$rootScope
* @description
*
* Every application has a single root {@link ng.$rootScope.Scope scope}.
* All other scopes are descendant scopes of the root scope. Scopes provide separation
* between the model and the view, via a mechanism for watching the model for changes.
* They also provide an event emission/broadcast and subscription facility. See the
* {@link guide/scope developer guide on scopes}.
*/
function $RootScopeProvider(){
var TTL = 10;
var $rootScopeMinErr = minErr('$rootScope');
this.digestTtl = function(value) {
if (arguments.length) {
TTL = value;
}
return TTL;
};
this.$get = ['$injector', '$exceptionHandler', '$parse', '$browser',
function( $injector, $exceptionHandler, $parse, $browser) {
/**
* @ngdoc function
* @name ng.$rootScope.Scope
*
* @description
* A root scope can be retrieved using the {@link ng.$rootScope $rootScope} key from the
* {@link AUTO.$injector $injector}. Child scopes are created using the
* {@link ng.$rootScope.Scope#methods_$new $new()} method. (Most scopes are created automatically when
* compiled HTML template is executed.)
*
* Here is a simple scope snippet to show how you can interact with the scope.
* <pre>
* <file src="./test/ng/rootScopeSpec.js" tag="docs1" />
* </pre>
*
* # Inheritance
* A scope can inherit from a parent scope, as in this example:
* <pre>
var parent = $rootScope;
var child = parent.$new();
parent.salutation = "Hello";
child.name = "World";
expect(child.salutation).toEqual('Hello');
child.salutation = "Welcome";
expect(child.salutation).toEqual('Welcome');
expect(parent.salutation).toEqual('Hello');
* </pre>
*
*
* @param {Object.<string, function()>=} providers Map of service factory which need to be
* provided for the current scope. Defaults to {@link ng}.
* @param {Object.<string, *>=} instanceCache Provides pre-instantiated services which should
* append/override services provided by `providers`. This is handy
* when unit-testing and having the need to override a default
* service.
* @returns {Object} Newly created scope.
*
*/
function Scope() {
this.$id = nextUid();
this.$$phase = this.$parent = this.$$watchers =
this.$$nextSibling = this.$$prevSibling =
this.$$childHead = this.$$childTail = null;
this['this'] = this.$root = this;
this.$$destroyed = false;
this.$$asyncQueue = [];
this.$$postDigestQueue = [];
this.$$listeners = {};
this.$$isolateBindings = {};
}
/**
* @ngdoc property
* @name ng.$rootScope.Scope#$id
* @propertyOf ng.$rootScope.Scope
* @returns {number} Unique scope ID (monotonically increasing alphanumeric sequence) useful for
* debugging.
*/
Scope.prototype = {
constructor: Scope,
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$new
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Creates a new child {@link ng.$rootScope.Scope scope}.
*
* The parent scope will propagate the {@link ng.$rootScope.Scope#$digest $digest()} and
* {@link ng.$rootScope.Scope#$digest $digest()} events. The scope can be removed from the
* scope hierarchy using {@link ng.$rootScope.Scope#$destroy $destroy()}.
*
* {@link ng.$rootScope.Scope#$destroy $destroy()} must be called on a scope when it is
* desired for the scope and its child scopes to be permanently detached from the parent and
* thus stop participating in model change detection and listener notification by invoking.
*
* @param {boolean} isolate If true, then the scope does not prototypically inherit from the
* parent scope. The scope is isolated, as it can not see parent scope properties.
* When creating widgets, it is useful for the widget to not accidentally read parent
* state.
*
* @returns {Object} The newly created child scope.
*
*/
$new: function(isolate) {
var Child,
child;
if (isolate) {
child = new Scope();
child.$root = this.$root;
// ensure that there is just one async queue per $rootScope and its children
child.$$asyncQueue = this.$$asyncQueue;
child.$$postDigestQueue = this.$$postDigestQueue;
} else {
Child = function() {}; // should be anonymous; This is so that when the minifier munges
// the name it does not become random set of chars. This will then show up as class
// name in the debugger.
Child.prototype = this;
child = new Child();
child.$id = nextUid();
}
child['this'] = child;
child.$$listeners = {};
child.$parent = this;
child.$$watchers = child.$$nextSibling = child.$$childHead = child.$$childTail = null;
child.$$prevSibling = this.$$childTail;
if (this.$$childHead) {
this.$$childTail.$$nextSibling = child;
this.$$childTail = child;
} else {
this.$$childHead = this.$$childTail = child;
}
return child;
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$watch
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Registers a `listener` callback to be executed whenever the `watchExpression` changes.
*
* - The `watchExpression` is called on every call to {@link ng.$rootScope.Scope#$digest
* $digest()} and should return the value that will be watched. (Since
* {@link ng.$rootScope.Scope#$digest $digest()} reruns when it detects changes the
* `watchExpression` can execute multiple times per
* {@link ng.$rootScope.Scope#$digest $digest()} and should be idempotent.)
* - The `listener` is called only when the value from the current `watchExpression` and the
* previous call to `watchExpression` are not equal (with the exception of the initial run,
* see below). The inequality is determined according to
* {@link angular.equals} function. To save the value of the object for later comparison,
* the {@link angular.copy} function is used. It also means that watching complex options
* will have adverse memory and performance implications.
* - The watch `listener` may change the model, which may trigger other `listener`s to fire.
* This is achieved by rerunning the watchers until no changes are detected. The rerun
* iteration limit is 10 to prevent an infinite loop deadlock.
*
*
* If you want to be notified whenever {@link ng.$rootScope.Scope#$digest $digest} is called,
* you can register a `watchExpression` function with no `listener`. (Since `watchExpression`
* can execute multiple times per {@link ng.$rootScope.Scope#$digest $digest} cycle when a
* change is detected, be prepared for multiple calls to your listener.)
*
* After a watcher is registered with the scope, the `listener` fn is called asynchronously
* (via {@link ng.$rootScope.Scope#$evalAsync $evalAsync}) to initialize the
* watcher. In rare cases, this is undesirable because the listener is called when the result
* of `watchExpression` didn't change. To detect this scenario within the `listener` fn, you
* can compare the `newVal` and `oldVal`. If these two values are identical (`===`) then the
* listener was called due to initialization.
*
* The example below contains an illustration of using a function as your $watch listener
*
*
* # Example
* <pre>
// let's assume that scope was dependency injected as the $rootScope
var scope = $rootScope;
scope.name = 'misko';
scope.counter = 0;
expect(scope.counter).toEqual(0);
scope.$watch('name', function(newValue, oldValue) {
scope.counter = scope.counter + 1;
});
expect(scope.counter).toEqual(0);
scope.$digest();
// no variable change
expect(scope.counter).toEqual(0);
scope.name = 'adam';
scope.$digest();
expect(scope.counter).toEqual(1);
// Using a listener function
var food;
scope.foodCounter = 0;
expect(scope.foodCounter).toEqual(0);
scope.$watch(
// This is the listener function
function() { return food; },
// This is the change handler
function(newValue, oldValue) {
if ( newValue !== oldValue ) {
// Only increment the counter if the value changed
scope.foodCounter = scope.foodCounter + 1;
}
}
);
// No digest has been run so the counter will be zero
expect(scope.foodCounter).toEqual(0);
// Run the digest but since food has not changed cout will still be zero
scope.$digest();
expect(scope.foodCounter).toEqual(0);
// Update food and run digest. Now the counter will increment
food = 'cheeseburger';
scope.$digest();
expect(scope.foodCounter).toEqual(1);
* </pre>
*
*
*
* @param {(function()|string)} watchExpression Expression that is evaluated on each
* {@link ng.$rootScope.Scope#$digest $digest} cycle. A change in the return value triggers
* a call to the `listener`.
*
* - `string`: Evaluated as {@link guide/expression expression}
* - `function(scope)`: called with current `scope` as a parameter.
* @param {(function()|string)=} listener Callback called whenever the return value of
* the `watchExpression` changes.
*
* - `string`: Evaluated as {@link guide/expression expression}
* - `function(newValue, oldValue, scope)`: called with current and previous values as
* parameters.
*
* @param {boolean=} objectEquality Compare object for equality rather than for reference.
* @returns {function()} Returns a deregistration function for this listener.
*/
$watch: function(watchExp, listener, objectEquality) {
var scope = this,
get = compileToFn(watchExp, 'watch'),
array = scope.$$watchers,
watcher = {
fn: listener,
last: initWatchVal,
get: get,
exp: watchExp,
eq: !!objectEquality
};
// in the case user pass string, we need to compile it, do we really need this ?
if (!isFunction(listener)) {
var listenFn = compileToFn(listener || noop, 'listener');
watcher.fn = function(newVal, oldVal, scope) {listenFn(scope);};
}
if (typeof watchExp == 'string' && get.constant) {
var originalFn = watcher.fn;
watcher.fn = function(newVal, oldVal, scope) {
originalFn.call(this, newVal, oldVal, scope);
arrayRemove(array, watcher);
};
}
if (!array) {
array = scope.$$watchers = [];
}
// we use unshift since we use a while loop in $digest for speed.
// the while loop reads in reverse order.
array.unshift(watcher);
return function() {
arrayRemove(array, watcher);
};
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$watchCollection
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Shallow watches the properties of an object and fires whenever any of the properties change
* (for arrays, this implies watching the array items; for object maps, this implies watching
* the properties). If a change is detected, the `listener` callback is fired.
*
* - The `obj` collection is observed via standard $watch operation and is examined on every
* call to $digest() to see if any items have been added, removed, or moved.
* - The `listener` is called whenever anything within the `obj` has changed. Examples include
* adding, removing, and moving items belonging to an object or array.
*
*
* # Example
* <pre>
$scope.names = ['igor', 'matias', 'misko', 'james'];
$scope.dataCount = 4;
$scope.$watchCollection('names', function(newNames, oldNames) {
$scope.dataCount = newNames.length;
});
expect($scope.dataCount).toEqual(4);
$scope.$digest();
//still at 4 ... no changes
expect($scope.dataCount).toEqual(4);
$scope.names.pop();
$scope.$digest();
//now there's been a change
expect($scope.dataCount).toEqual(3);
* </pre>
*
*
* @param {string|Function(scope)} obj Evaluated as {@link guide/expression expression}. The
* expression value should evaluate to an object or an array which is observed on each
* {@link ng.$rootScope.Scope#$digest $digest} cycle. Any shallow change within the
* collection will trigger a call to the `listener`.
*
* @param {function(newCollection, oldCollection, scope)} listener a callback function that is
* fired with both the `newCollection` and `oldCollection` as parameters.
* The `newCollection` object is the newly modified data obtained from the `obj` expression
* and the `oldCollection` object is a copy of the former collection data.
* The `scope` refers to the current scope.
*
* @returns {function()} Returns a de-registration function for this listener. When the
* de-registration function is executed, the internal watch operation is terminated.
*/
$watchCollection: function(obj, listener) {
var self = this;
var oldValue;
var newValue;
var changeDetected = 0;
var objGetter = $parse(obj);
var internalArray = [];
var internalObject = {};
var oldLength = 0;
function $watchCollectionWatch() {
newValue = objGetter(self);
var newLength, key;
if (!isObject(newValue)) {
if (oldValue !== newValue) {
oldValue = newValue;
changeDetected++;
}
} else if (isArrayLike(newValue)) {
if (oldValue !== internalArray) {
// we are transitioning from something which was not an array into array.
oldValue = internalArray;
oldLength = oldValue.length = 0;
changeDetected++;
}
newLength = newValue.length;
if (oldLength !== newLength) {
// if lengths do not match we need to trigger change notification
changeDetected++;
oldValue.length = oldLength = newLength;
}
// copy the items to oldValue and look for changes.
for (var i = 0; i < newLength; i++) {
if (oldValue[i] !== newValue[i]) {
changeDetected++;
oldValue[i] = newValue[i];
}
}
} else {
if (oldValue !== internalObject) {
// we are transitioning from something which was not an object into object.
oldValue = internalObject = {};
oldLength = 0;
changeDetected++;
}
// copy the items to oldValue and look for changes.
newLength = 0;
for (key in newValue) {
if (newValue.hasOwnProperty(key)) {
newLength++;
if (oldValue.hasOwnProperty(key)) {
if (oldValue[key] !== newValue[key]) {
changeDetected++;
oldValue[key] = newValue[key];
}
} else {
oldLength++;
oldValue[key] = newValue[key];
changeDetected++;
}
}
}
if (oldLength > newLength) {
// we used to have more keys, need to find them and destroy them.
changeDetected++;
for(key in oldValue) {
if (oldValue.hasOwnProperty(key) && !newValue.hasOwnProperty(key)) {
oldLength--;
delete oldValue[key];
}
}
}
}
return changeDetected;
}
function $watchCollectionAction() {
listener(newValue, oldValue, self);
}
return this.$watch($watchCollectionWatch, $watchCollectionAction);
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$digest
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Processes all of the {@link ng.$rootScope.Scope#$watch watchers} of the current scope and
* its children. Because a {@link ng.$rootScope.Scope#$watch watcher}'s listener can change
* the model, the `$digest()` keeps calling the {@link ng.$rootScope.Scope#$watch watchers}
* until no more listeners are firing. This means that it is possible to get into an infinite
* loop. This function will throw `'Maximum iteration limit exceeded.'` if the number of
* iterations exceeds 10.
*
* Usually, you don't call `$digest()` directly in
* {@link ng.directive:ngController controllers} or in
* {@link ng.$compileProvider#methods_directive directives}.
* Instead, you should call {@link ng.$rootScope.Scope#$apply $apply()} (typically from within
* a {@link ng.$compileProvider#methods_directive directives}), which will force a `$digest()`.
*
* If you want to be notified whenever `$digest()` is called,
* you can register a `watchExpression` function with
* {@link ng.$rootScope.Scope#$watch $watch()} with no `listener`.
*
* In unit tests, you may need to call `$digest()` to simulate the scope life cycle.
*
* # Example
* <pre>
var scope = ...;
scope.name = 'misko';
scope.counter = 0;
expect(scope.counter).toEqual(0);
scope.$watch('name', function(newValue, oldValue) {
scope.counter = scope.counter + 1;
});
expect(scope.counter).toEqual(0);
scope.$digest();
// no variable change
expect(scope.counter).toEqual(0);
scope.name = 'adam';
scope.$digest();
expect(scope.counter).toEqual(1);
* </pre>
*
*/
$digest: function() {
var watch, value, last,
watchers,
asyncQueue = this.$$asyncQueue,
postDigestQueue = this.$$postDigestQueue,
length,
dirty, ttl = TTL,
next, current, target = this,
watchLog = [],
logIdx, logMsg, asyncTask;
beginPhase('$digest');
do { // "while dirty" loop
dirty = false;
current = target;
while(asyncQueue.length) {
try {
asyncTask = asyncQueue.shift();
asyncTask.scope.$eval(asyncTask.expression);
} catch (e) {
$exceptionHandler(e);
}
}
do { // "traverse the scopes" loop
if ((watchers = current.$$watchers)) {
// process our watches
length = watchers.length;
while (length--) {
try {
watch = watchers[length];
// Most common watches are on primitives, in which case we can short
// circuit it with === operator, only when === fails do we use .equals
if (watch && (value = watch.get(current)) !== (last = watch.last) &&
!(watch.eq
? equals(value, last)
: (typeof value == 'number' && typeof last == 'number'
&& isNaN(value) && isNaN(last)))) {
dirty = true;
watch.last = watch.eq ? copy(value) : value;
watch.fn(value, ((last === initWatchVal) ? value : last), current);
if (ttl < 5) {
logIdx = 4 - ttl;
if (!watchLog[logIdx]) watchLog[logIdx] = [];
logMsg = (isFunction(watch.exp))
? 'fn: ' + (watch.exp.name || watch.exp.toString())
: watch.exp;
logMsg += '; newVal: ' + toJson(value) + '; oldVal: ' + toJson(last);
watchLog[logIdx].push(logMsg);
}
}
} catch (e) {
$exceptionHandler(e);
}
}
}
// Insanity Warning: scope depth-first traversal
// yes, this code is a bit crazy, but it works and we have tests to prove it!
// this piece should be kept in sync with the traversal in $broadcast
if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) {
while(current !== target && !(next = current.$$nextSibling)) {
current = current.$parent;
}
}
} while ((current = next));
if(dirty && !(ttl--)) {
clearPhase();
throw $rootScopeMinErr('infdig',
'{0} $digest() iterations reached. Aborting!\n' +
'Watchers fired in the last 5 iterations: {1}',
TTL, toJson(watchLog));
}
} while (dirty || asyncQueue.length);
clearPhase();
while(postDigestQueue.length) {
try {
postDigestQueue.shift()();
} catch (e) {
$exceptionHandler(e);
}
}
},
/**
* @ngdoc event
* @name ng.$rootScope.Scope#$destroy
* @eventOf ng.$rootScope.Scope
* @eventType broadcast on scope being destroyed
*
* @description
* Broadcasted when a scope and its children are being destroyed.
*
* Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
* clean up DOM bindings before an element is removed from the DOM.
*/
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$destroy
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Removes the current scope (and all of its children) from the parent scope. Removal implies
* that calls to {@link ng.$rootScope.Scope#$digest $digest()} will no longer
* propagate to the current scope and its children. Removal also implies that the current
* scope is eligible for garbage collection.
*
* The `$destroy()` is usually used by directives such as
* {@link ng.directive:ngRepeat ngRepeat} for managing the
* unrolling of the loop.
*
* Just before a scope is destroyed, a `$destroy` event is broadcasted on this scope.
* Application code can register a `$destroy` event handler that will give it a chance to
* perform any necessary cleanup.
*
* Note that, in AngularJS, there is also a `$destroy` jQuery event, which can be used to
* clean up DOM bindings before an element is removed from the DOM.
*/
$destroy: function() {
// we can't destroy the root scope or a scope that has been already destroyed
if ($rootScope == this || this.$$destroyed) return;
var parent = this.$parent;
this.$broadcast('$destroy');
this.$$destroyed = true;
if (parent.$$childHead == this) parent.$$childHead = this.$$nextSibling;
if (parent.$$childTail == this) parent.$$childTail = this.$$prevSibling;
if (this.$$prevSibling) this.$$prevSibling.$$nextSibling = this.$$nextSibling;
if (this.$$nextSibling) this.$$nextSibling.$$prevSibling = this.$$prevSibling;
// This is bogus code that works around Chrome's GC leak
// see: https://github.com/angular/angular.js/issues/1313#issuecomment-10378451
this.$parent = this.$$nextSibling = this.$$prevSibling = this.$$childHead =
this.$$childTail = null;
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$eval
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Executes the `expression` on the current scope and returns the result. Any exceptions in
* the expression are propagated (uncaught). This is useful when evaluating Angular
* expressions.
*
* # Example
* <pre>
var scope = ng.$rootScope.Scope();
scope.a = 1;
scope.b = 2;
expect(scope.$eval('a+b')).toEqual(3);
expect(scope.$eval(function(scope){ return scope.a + scope.b; })).toEqual(3);
* </pre>
*
* @param {(string|function())=} expression An angular expression to be executed.
*
* - `string`: execute using the rules as defined in {@link guide/expression expression}.
* - `function(scope)`: execute the function with the current `scope` parameter.
*
* @param {(object)=} locals Local variables object, useful for overriding values in scope.
* @returns {*} The result of evaluating the expression.
*/
$eval: function(expr, locals) {
return $parse(expr)(this, locals);
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$evalAsync
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Executes the expression on the current scope at a later point in time.
*
* The `$evalAsync` makes no guarantees as to when the `expression` will be executed, only
* that:
*
* - it will execute after the function that scheduled the evaluation (preferably before DOM
* rendering).
* - at least one {@link ng.$rootScope.Scope#$digest $digest cycle} will be performed after
* `expression` execution.
*
* Any exceptions from the execution of the expression are forwarded to the
* {@link ng.$exceptionHandler $exceptionHandler} service.
*
* __Note:__ if this function is called outside of a `$digest` cycle, a new `$digest` cycle
* will be scheduled. However, it is encouraged to always call code that changes the model
* from within an `$apply` call. That includes code evaluated via `$evalAsync`.
*
* @param {(string|function())=} expression An angular expression to be executed.
*
* - `string`: execute using the rules as defined in {@link guide/expression expression}.
* - `function(scope)`: execute the function with the current `scope` parameter.
*
*/
$evalAsync: function(expr) {
// if we are outside of an $digest loop and this is the first time we are scheduling async
// task also schedule async auto-flush
if (!$rootScope.$$phase && !$rootScope.$$asyncQueue.length) {
$browser.defer(function() {
if ($rootScope.$$asyncQueue.length) {
$rootScope.$digest();
}
});
}
this.$$asyncQueue.push({scope: this, expression: expr});
},
$$postDigest : function(fn) {
this.$$postDigestQueue.push(fn);
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$apply
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* `$apply()` is used to execute an expression in angular from outside of the angular
* framework. (For example from browser DOM events, setTimeout, XHR or third party libraries).
* Because we are calling into the angular framework we need to perform proper scope life
* cycle of {@link ng.$exceptionHandler exception handling},
* {@link ng.$rootScope.Scope#$digest executing watches}.
*
* ## Life cycle
*
* # Pseudo-Code of `$apply()`
* <pre>
function $apply(expr) {
try {
return $eval(expr);
} catch (e) {
$exceptionHandler(e);
} finally {
$root.$digest();
}
}
* </pre>
*
*
* Scope's `$apply()` method transitions through the following stages:
*
* 1. The {@link guide/expression expression} is executed using the
* {@link ng.$rootScope.Scope#$eval $eval()} method.
* 2. Any exceptions from the execution of the expression are forwarded to the
* {@link ng.$exceptionHandler $exceptionHandler} service.
* 3. The {@link ng.$rootScope.Scope#$watch watch} listeners are fired immediately after the
* expression was executed using the {@link ng.$rootScope.Scope#$digest $digest()} method.
*
*
* @param {(string|function())=} exp An angular expression to be executed.
*
* - `string`: execute using the rules as defined in {@link guide/expression expression}.
* - `function(scope)`: execute the function with current `scope` parameter.
*
* @returns {*} The result of evaluating the expression.
*/
$apply: function(expr) {
try {
beginPhase('$apply');
return this.$eval(expr);
} catch (e) {
$exceptionHandler(e);
} finally {
clearPhase();
try {
$rootScope.$digest();
} catch (e) {
$exceptionHandler(e);
throw e;
}
}
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$on
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Listens on events of a given type. See {@link ng.$rootScope.Scope#$emit $emit} for
* discussion of event life cycle.
*
* The event listener function format is: `function(event, args...)`. The `event` object
* passed into the listener has the following attributes:
*
* - `targetScope` - `{Scope}`: the scope on which the event was `$emit`-ed or
* `$broadcast`-ed.
* - `currentScope` - `{Scope}`: the current scope which is handling the event.
* - `name` - `{string}`: name of the event.
* - `stopPropagation` - `{function=}`: calling `stopPropagation` function will cancel
* further event propagation (available only for events that were `$emit`-ed).
* - `preventDefault` - `{function}`: calling `preventDefault` sets `defaultPrevented` flag
* to true.
* - `defaultPrevented` - `{boolean}`: true if `preventDefault` was called.
*
* @param {string} name Event name to listen on.
* @param {function(event, args...)} listener Function to call when the event is emitted.
* @returns {function()} Returns a deregistration function for this listener.
*/
$on: function(name, listener) {
var namedListeners = this.$$listeners[name];
if (!namedListeners) {
this.$$listeners[name] = namedListeners = [];
}
namedListeners.push(listener);
return function() {
namedListeners[indexOf(namedListeners, listener)] = null;
};
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$emit
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Dispatches an event `name` upwards through the scope hierarchy notifying the
* registered {@link ng.$rootScope.Scope#$on} listeners.
*
* The event life cycle starts at the scope on which `$emit` was called. All
* {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
* notified. Afterwards, the event traverses upwards toward the root scope and calls all
* registered listeners along the way. The event will stop propagating if one of the listeners
* cancels it.
*
* Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
* onto the {@link ng.$exceptionHandler $exceptionHandler} service.
*
* @param {string} name Event name to emit.
* @param {...*} args Optional set of arguments which will be passed onto the event listeners.
* @return {Object} Event object (see {@link ng.$rootScope.Scope#$on}).
*/
$emit: function(name, args) {
var empty = [],
namedListeners,
scope = this,
stopPropagation = false,
event = {
name: name,
targetScope: scope,
stopPropagation: function() {stopPropagation = true;},
preventDefault: function() {
event.defaultPrevented = true;
},
defaultPrevented: false
},
listenerArgs = concat([event], arguments, 1),
i, length;
do {
namedListeners = scope.$$listeners[name] || empty;
event.currentScope = scope;
for (i=0, length=namedListeners.length; i<length; i++) {
// if listeners were deregistered, defragment the array
if (!namedListeners[i]) {
namedListeners.splice(i, 1);
i--;
length--;
continue;
}
try {
//allow all listeners attached to the current scope to run
namedListeners[i].apply(null, listenerArgs);
} catch (e) {
$exceptionHandler(e);
}
}
//if any listener on the current scope stops propagation, prevent bubbling
if (stopPropagation) return event;
//traverse upwards
scope = scope.$parent;
} while (scope);
return event;
},
/**
* @ngdoc function
* @name ng.$rootScope.Scope#$broadcast
* @methodOf ng.$rootScope.Scope
* @function
*
* @description
* Dispatches an event `name` downwards to all child scopes (and their children) notifying the
* registered {@link ng.$rootScope.Scope#$on} listeners.
*
* The event life cycle starts at the scope on which `$broadcast` was called. All
* {@link ng.$rootScope.Scope#$on listeners} listening for `name` event on this scope get
* notified. Afterwards, the event propagates to all direct and indirect scopes of the current
* scope and calls all registered listeners along the way. The event cannot be canceled.
*
* Any exception emitted from the {@link ng.$rootScope.Scope#$on listeners} will be passed
* onto the {@link ng.$exceptionHandler $exceptionHandler} service.
*
* @param {string} name Event name to broadcast.
* @param {...*} args Optional set of arguments which will be passed onto the event listeners.
* @return {Object} Event object, see {@link ng.$rootScope.Scope#$on}
*/
$broadcast: function(name, args) {
var target = this,
current = target,
next = target,
event = {
name: name,
targetScope: target,
preventDefault: function() {
event.defaultPrevented = true;
},
defaultPrevented: false
},
listenerArgs = concat([event], arguments, 1),
listeners, i, length;
//down while you can, then up and next sibling or up and next sibling until back at root
do {
current = next;
event.currentScope = current;
listeners = current.$$listeners[name] || [];
for (i=0, length = listeners.length; i<length; i++) {
// if listeners were deregistered, defragment the array
if (!listeners[i]) {
listeners.splice(i, 1);
i--;
length--;
continue;
}
try {
listeners[i].apply(null, listenerArgs);
} catch(e) {
$exceptionHandler(e);
}
}
// Insanity Warning: scope depth-first traversal
// yes, this code is a bit crazy, but it works and we have tests to prove it!
// this piece should be kept in sync with the traversal in $digest
if (!(next = (current.$$childHead || (current !== target && current.$$nextSibling)))) {
while(current !== target && !(next = current.$$nextSibling)) {
current = current.$parent;
}
}
} while ((current = next));
return event;
}
};
var $rootScope = new Scope();
return $rootScope;
function beginPhase(phase) {
if ($rootScope.$$phase) {
throw $rootScopeMinErr('inprog', '{0} already in progress', $rootScope.$$phase);
}
$rootScope.$$phase = phase;
}
function clearPhase() {
$rootScope.$$phase = null;
}
function compileToFn(exp, name) {
var fn = $parse(exp);
assertArgFn(fn, name);
return fn;
}
/**
* function used as an initial value for watchers.
* because it's unique we can easily tell it apart from other values
*/
function initWatchVal() {}
}];
}
var $sceMinErr = minErr('$sce');
var SCE_CONTEXTS = {
HTML: 'html',
CSS: 'css',
URL: 'url',
// RESOURCE_URL is a subtype of URL used in contexts where a privileged resource is sourced from a
// url. (e.g. ng-include, script src, templateUrl)
RESOURCE_URL: 'resourceUrl',
JS: 'js'
};
// Helper functions follow.
// Copied from:
// http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962
// Prereq: s is a string.
function escapeForRegexp(s) {
return s.replace(/([-()\[\]{}+?*.$\^|,:#<!\\])/g, '\\$1').
replace(/\x08/g, '\\x08');
}
function adjustMatcher(matcher) {
if (matcher === 'self') {
return matcher;
} else if (isString(matcher)) {
// Strings match exactly except for 2 wildcards - '*' and '**'.
// '*' matches any character except those from the set ':/.?&'.
// '**' matches any character (like .* in a RegExp).
// More than 2 *'s raises an error as it's ill defined.
if (matcher.indexOf('***') > -1) {
throw $sceMinErr('iwcard',
'Illegal sequence *** in string matcher. String: {0}', matcher);
}
matcher = escapeForRegexp(matcher).
replace('\\*\\*', '.*').
replace('\\*', '[^:/.?&;]*');
return new RegExp('^' + matcher + '$');
} else if (isRegExp(matcher)) {
// The only other type of matcher allowed is a Regexp.
// Match entire URL / disallow partial matches.
// Flags are reset (i.e. no global, ignoreCase or multiline)
return new RegExp('^' + matcher.source + '$');
} else {
throw $sceMinErr('imatcher',
'Matchers may only be "self", string patterns or RegExp objects');
}
}
function adjustMatchers(matchers) {
var adjustedMatchers = [];
if (isDefined(matchers)) {
forEach(matchers, function(matcher) {
adjustedMatchers.push(adjustMatcher(matcher));
});
}
return adjustedMatchers;
}
/**
* @ngdoc service
* @name ng.$sceDelegate
* @function
*
* @description
*
* `$sceDelegate` is a service that is used by the `$sce` service to provide {@link ng.$sce Strict
* Contextual Escaping (SCE)} services to AngularJS.
*
* Typically, you would configure or override the {@link ng.$sceDelegate $sceDelegate} instead of
* the `$sce` service to customize the way Strict Contextual Escaping works in AngularJS. This is
* because, while the `$sce` provides numerous shorthand methods, etc., you really only need to
* override 3 core functions (`trustAs`, `getTrusted` and `valueOf`) to replace the way things
* work because `$sce` delegates to `$sceDelegate` for these operations.
*
* Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} to configure this service.
*
* The default instance of `$sceDelegate` should work out of the box with little pain. While you
* can override it completely to change the behavior of `$sce`, the common case would
* involve configuring the {@link ng.$sceDelegateProvider $sceDelegateProvider} instead by setting
* your own whitelists and blacklists for trusting URLs used for loading AngularJS resources such as
* templates. Refer {@link ng.$sceDelegateProvider#methods_resourceUrlWhitelist
* $sceDelegateProvider.resourceUrlWhitelist} and {@link
* ng.$sceDelegateProvider#methods_resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
*/
/**
* @ngdoc object
* @name ng.$sceDelegateProvider
* @description
*
* The `$sceDelegateProvider` provider allows developers to configure the {@link ng.$sceDelegate
* $sceDelegate} service. This allows one to get/set the whitelists and blacklists used to ensure
* that the URLs used for sourcing Angular templates are safe. Refer {@link
* ng.$sceDelegateProvider#methods_resourceUrlWhitelist $sceDelegateProvider.resourceUrlWhitelist} and
* {@link ng.$sceDelegateProvider#methods_resourceUrlBlacklist $sceDelegateProvider.resourceUrlBlacklist}
*
* For the general details about this service in Angular, read the main page for {@link ng.$sce
* Strict Contextual Escaping (SCE)}.
*
* **Example**: Consider the following case. <a name="example"></a>
*
* - your app is hosted at url `http://myapp.example.com/`
* - but some of your templates are hosted on other domains you control such as
* `http://srv01.assets.example.com/`, `http://srv02.assets.example.com/`, etc.
* - and you have an open redirect at `http://myapp.example.com/clickThru?...`.
*
* Here is what a secure configuration for this scenario might look like:
*
* <pre class="prettyprint">
* angular.module('myApp', []).config(function($sceDelegateProvider) {
* $sceDelegateProvider.resourceUrlWhitelist([
* // Allow same origin resource loads.
* 'self',
* // Allow loading from our assets domain. Notice the difference between * and **.
* 'http://srv*.assets.example.com/**']);
*
* // The blacklist overrides the whitelist so the open redirect here is blocked.
* $sceDelegateProvider.resourceUrlBlacklist([
* 'http://myapp.example.com/clickThru**']);
* });
* </pre>
*/
function $SceDelegateProvider() {
this.SCE_CONTEXTS = SCE_CONTEXTS;
// Resource URLs can also be trusted by policy.
var resourceUrlWhitelist = ['self'],
resourceUrlBlacklist = [];
/**
* @ngdoc function
* @name ng.sceDelegateProvider#resourceUrlWhitelist
* @methodOf ng.$sceDelegateProvider
* @function
*
* @param {Array=} whitelist When provided, replaces the resourceUrlWhitelist with the value
* provided. This must be an array or null. A snapshot of this array is used so further
* changes to the array are ignored.
*
* Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
* allowed in this array.
*
* Note: **an empty whitelist array will block all URLs**!
*
* @return {Array} the currently set whitelist array.
*
* The **default value** when no whitelist has been explicitly set is `['self']` allowing only
* same origin resource requests.
*
* @description
* Sets/Gets the whitelist of trusted resource URLs.
*/
this.resourceUrlWhitelist = function (value) {
if (arguments.length) {
resourceUrlWhitelist = adjustMatchers(value);
}
return resourceUrlWhitelist;
};
/**
* @ngdoc function
* @name ng.sceDelegateProvider#resourceUrlBlacklist
* @methodOf ng.$sceDelegateProvider
* @function
*
* @param {Array=} blacklist When provided, replaces the resourceUrlBlacklist with the value
* provided. This must be an array or null. A snapshot of this array is used so further
* changes to the array are ignored.
*
* Follow {@link ng.$sce#resourceUrlPatternItem this link} for a description of the items
* allowed in this array.
*
* The typical usage for the blacklist is to **block
* [open redirects](http://cwe.mitre.org/data/definitions/601.html)** served by your domain as
* these would otherwise be trusted but actually return content from the redirected domain.
*
* Finally, **the blacklist overrides the whitelist** and has the final say.
*
* @return {Array} the currently set blacklist array.
*
* The **default value** when no whitelist has been explicitly set is the empty array (i.e. there
* is no blacklist.)
*
* @description
* Sets/Gets the blacklist of trusted resource URLs.
*/
this.resourceUrlBlacklist = function (value) {
if (arguments.length) {
resourceUrlBlacklist = adjustMatchers(value);
}
return resourceUrlBlacklist;
};
this.$get = ['$log', '$document', '$injector', function(
$log, $document, $injector) {
var htmlSanitizer = function htmlSanitizer(html) {
throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
};
if ($injector.has('$sanitize')) {
htmlSanitizer = $injector.get('$sanitize');
}
function matchUrl(matcher, parsedUrl) {
if (matcher === 'self') {
return urlIsSameOrigin(parsedUrl);
} else {
// definitely a regex. See adjustMatchers()
return !!matcher.exec(parsedUrl.href);
}
}
function isResourceUrlAllowedByPolicy(url) {
var parsedUrl = urlResolve(url.toString());
var i, n, allowed = false;
// Ensure that at least one item from the whitelist allows this url.
for (i = 0, n = resourceUrlWhitelist.length; i < n; i++) {
if (matchUrl(resourceUrlWhitelist[i], parsedUrl)) {
allowed = true;
break;
}
}
if (allowed) {
// Ensure that no item from the blacklist blocked this url.
for (i = 0, n = resourceUrlBlacklist.length; i < n; i++) {
if (matchUrl(resourceUrlBlacklist[i], parsedUrl)) {
allowed = false;
break;
}
}
}
return allowed;
}
function generateHolderType(Base) {
var holderType = function TrustedValueHolderType(trustedValue) {
this.$$unwrapTrustedValue = function() {
return trustedValue;
};
};
if (Base) {
holderType.prototype = new Base();
}
holderType.prototype.valueOf = function sceValueOf() {
return this.$$unwrapTrustedValue();
};
holderType.prototype.toString = function sceToString() {
return this.$$unwrapTrustedValue().toString();
};
return holderType;
}
var trustedValueHolderBase = generateHolderType(),
byType = {};
byType[SCE_CONTEXTS.HTML] = generateHolderType(trustedValueHolderBase);
byType[SCE_CONTEXTS.CSS] = generateHolderType(trustedValueHolderBase);
byType[SCE_CONTEXTS.URL] = generateHolderType(trustedValueHolderBase);
byType[SCE_CONTEXTS.JS] = generateHolderType(trustedValueHolderBase);
byType[SCE_CONTEXTS.RESOURCE_URL] = generateHolderType(byType[SCE_CONTEXTS.URL]);
/**
* @ngdoc method
* @name ng.$sceDelegate#trustAs
* @methodOf ng.$sceDelegate
*
* @description
* Returns an object that is trusted by angular for use in specified strict
* contextual escaping contexts (such as ng-html-bind-unsafe, ng-include, any src
* attribute interpolation, any dom event binding attribute interpolation
* such as for onclick, etc.) that uses the provided value.
* See {@link ng.$sce $sce} for enabling strict contextual escaping.
*
* @param {string} type The kind of context in which this value is safe for use. e.g. url,
* resourceUrl, html, js and css.
* @param {*} value The value that that should be considered trusted/safe.
* @returns {*} A value that can be used to stand in for the provided `value` in places
* where Angular expects a $sce.trustAs() return value.
*/
function trustAs(type, trustedValue) {
var Constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
if (!Constructor) {
throw $sceMinErr('icontext',
'Attempted to trust a value in invalid context. Context: {0}; Value: {1}',
type, trustedValue);
}
if (trustedValue === null || trustedValue === undefined || trustedValue === '') {
return trustedValue;
}
// All the current contexts in SCE_CONTEXTS happen to be strings. In order to avoid trusting
// mutable objects, we ensure here that the value passed in is actually a string.
if (typeof trustedValue !== 'string') {
throw $sceMinErr('itype',
'Attempted to trust a non-string value in a content requiring a string: Context: {0}',
type);
}
return new Constructor(trustedValue);
}
/**
* @ngdoc method
* @name ng.$sceDelegate#valueOf
* @methodOf ng.$sceDelegate
*
* @description
* If the passed parameter had been returned by a prior call to {@link ng.$sceDelegate#methods_trustAs
* `$sceDelegate.trustAs`}, returns the value that had been passed to {@link
* ng.$sceDelegate#methods_trustAs `$sceDelegate.trustAs`}.
*
* If the passed parameter is not a value that had been returned by {@link
* ng.$sceDelegate#methods_trustAs `$sceDelegate.trustAs`}, returns it as-is.
*
* @param {*} value The result of a prior {@link ng.$sceDelegate#methods_trustAs `$sceDelegate.trustAs`}
* call or anything else.
* @returns {*} The value the was originally provided to {@link ng.$sceDelegate#methods_trustAs
* `$sceDelegate.trustAs`} if `value` is the result of such a call. Otherwise, returns
* `value` unchanged.
*/
function valueOf(maybeTrusted) {
if (maybeTrusted instanceof trustedValueHolderBase) {
return maybeTrusted.$$unwrapTrustedValue();
} else {
return maybeTrusted;
}
}
/**
* @ngdoc method
* @name ng.$sceDelegate#getTrusted
* @methodOf ng.$sceDelegate
*
* @description
* Takes the result of a {@link ng.$sceDelegate#methods_trustAs `$sceDelegate.trustAs`} call and
* returns the originally supplied value if the queried context type is a supertype of the
* created type. If this condition isn't satisfied, throws an exception.
*
* @param {string} type The kind of context in which this value is to be used.
* @param {*} maybeTrusted The result of a prior {@link ng.$sceDelegate#methods_trustAs
* `$sceDelegate.trustAs`} call.
* @returns {*} The value the was originally provided to {@link ng.$sceDelegate#methods_trustAs
* `$sceDelegate.trustAs`} if valid in this context. Otherwise, throws an exception.
*/
function getTrusted(type, maybeTrusted) {
if (maybeTrusted === null || maybeTrusted === undefined || maybeTrusted === '') {
return maybeTrusted;
}
var constructor = (byType.hasOwnProperty(type) ? byType[type] : null);
if (constructor && maybeTrusted instanceof constructor) {
return maybeTrusted.$$unwrapTrustedValue();
}
// If we get here, then we may only take one of two actions.
// 1. sanitize the value for the requested type, or
// 2. throw an exception.
if (type === SCE_CONTEXTS.RESOURCE_URL) {
if (isResourceUrlAllowedByPolicy(maybeTrusted)) {
return maybeTrusted;
} else {
throw $sceMinErr('insecurl',
'Blocked loading resource from url not allowed by $sceDelegate policy. URL: {0}',
maybeTrusted.toString());
}
} else if (type === SCE_CONTEXTS.HTML) {
return htmlSanitizer(maybeTrusted);
}
throw $sceMinErr('unsafe', 'Attempting to use an unsafe value in a safe context.');
}
return { trustAs: trustAs,
getTrusted: getTrusted,
valueOf: valueOf };
}];
}
/**
* @ngdoc object
* @name ng.$sceProvider
* @description
*
* The $sceProvider provider allows developers to configure the {@link ng.$sce $sce} service.
* - enable/disable Strict Contextual Escaping (SCE) in a module
* - override the default implementation with a custom delegate
*
* Read more about {@link ng.$sce Strict Contextual Escaping (SCE)}.
*/
/* jshint maxlen: false*/
/**
* @ngdoc service
* @name ng.$sce
* @function
*
* @description
*
* `$sce` is a service that provides Strict Contextual Escaping services to AngularJS.
*
* # Strict Contextual Escaping
*
* Strict Contextual Escaping (SCE) is a mode in which AngularJS requires bindings in certain
* contexts to result in a value that is marked as safe to use for that context. One example of
* such a context is binding arbitrary html controlled by the user via `ng-bind-html`. We refer
* to these contexts as privileged or SCE contexts.
*
* As of version 1.2, Angular ships with SCE enabled by default.
*
* Note: When enabled (the default), IE8 in quirks mode is not supported. In this mode, IE8 allows
* one to execute arbitrary javascript by the use of the expression() syntax. Refer
* <http://blogs.msdn.com/b/ie/archive/2008/10/16/ending-expressions.aspx> to learn more about them.
* You can ensure your document is in standards mode and not quirks mode by adding `<!doctype html>`
* to the top of your HTML document.
*
* SCE assists in writing code in way that (a) is secure by default and (b) makes auditing for
* security vulnerabilities such as XSS, clickjacking, etc. a lot easier.
*
* Here's an example of a binding in a privileged context:
*
* <pre class="prettyprint">
* <input ng-model="userHtml">
* <div ng-bind-html="{{userHtml}}">
* </pre>
*
* Notice that `ng-bind-html` is bound to `{{userHtml}}` controlled by the user. With SCE
* disabled, this application allows the user to render arbitrary HTML into the DIV.
* In a more realistic example, one may be rendering user comments, blog articles, etc. via
* bindings. (HTML is just one example of a context where rendering user controlled input creates
* security vulnerabilities.)
*
* For the case of HTML, you might use a library, either on the client side, or on the server side,
* to sanitize unsafe HTML before binding to the value and rendering it in the document.
*
* How would you ensure that every place that used these types of bindings was bound to a value that
* was sanitized by your library (or returned as safe for rendering by your server?) How can you
* ensure that you didn't accidentally delete the line that sanitized the value, or renamed some
* properties/fields and forgot to update the binding to the sanitized value?
*
* To be secure by default, you want to ensure that any such bindings are disallowed unless you can
* determine that something explicitly says it's safe to use a value for binding in that
* context. You can then audit your code (a simple grep would do) to ensure that this is only done
* for those values that you can easily tell are safe - because they were received from your server,
* sanitized by your library, etc. You can organize your codebase to help with this - perhaps
* allowing only the files in a specific directory to do this. Ensuring that the internal API
* exposed by that code doesn't markup arbitrary values as safe then becomes a more manageable task.
*
* In the case of AngularJS' SCE service, one uses {@link ng.$sce#methods_trustAs $sce.trustAs}
* (and shorthand methods such as {@link ng.$sce#methods_trustAsHtml $sce.trustAsHtml}, etc.) to
* obtain values that will be accepted by SCE / privileged contexts.
*
*
* ## How does it work?
*
* In privileged contexts, directives and code will bind to the result of {@link ng.$sce#methods_getTrusted
* $sce.getTrusted(context, value)} rather than to the value directly. Directives use {@link
* ng.$sce#methods_parse $sce.parseAs} rather than `$parse` to watch attribute bindings, which performs the
* {@link ng.$sce#methods_getTrusted $sce.getTrusted} behind the scenes on non-constant literals.
*
* As an example, {@link ng.directive:ngBindHtml ngBindHtml} uses {@link
* ng.$sce#methods_parseAsHtml $sce.parseAsHtml(binding expression)}. Here's the actual code (slightly
* simplified):
*
* <pre class="prettyprint">
* var ngBindHtmlDirective = ['$sce', function($sce) {
* return function(scope, element, attr) {
* scope.$watch($sce.parseAsHtml(attr.ngBindHtml), function(value) {
* element.html(value || '');
* });
* };
* }];
* </pre>
*
* ## Impact on loading templates
*
* This applies both to the {@link ng.directive:ngInclude `ng-include`} directive as well as
* `templateUrl`'s specified by {@link guide/directive directives}.
*
* By default, Angular only loads templates from the same domain and protocol as the application
* document. This is done by calling {@link ng.$sce#methods_getTrustedResourceUrl
* $sce.getTrustedResourceUrl} on the template URL. To load templates from other domains and/or
* protocols, you may either either {@link ng.$sceDelegateProvider#methods_resourceUrlWhitelist whitelist
* them} or {@link ng.$sce#methods_trustAsResourceUrl wrap it} into a trusted value.
*
* *Please note*:
* The browser's
* {@link https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest
* Same Origin Policy} and {@link http://www.w3.org/TR/cors/ Cross-Origin Resource Sharing (CORS)}
* policy apply in addition to this and may further restrict whether the template is successfully
* loaded. This means that without the right CORS policy, loading templates from a different domain
* won't work on all browsers. Also, loading templates from `file://` URL does not work on some
* browsers.
*
* ## This feels like too much overhead for the developer?
*
* It's important to remember that SCE only applies to interpolation expressions.
*
* If your expressions are constant literals, they're automatically trusted and you don't need to
* call `$sce.trustAs` on them. (e.g.
* `<div ng-html-bind-unsafe="'<b>implicitly trusted</b>'"></div>`) just works.
*
* Additionally, `a[href]` and `img[src]` automatically sanitize their URLs and do not pass them
* through {@link ng.$sce#methods_getTrusted $sce.getTrusted}. SCE doesn't play a role here.
*
* The included {@link ng.$sceDelegate $sceDelegate} comes with sane defaults to allow you to load
* templates in `ng-include` from your application's domain without having to even know about SCE.
* It blocks loading templates from other domains or loading templates over http from an https
* served document. You can change these by setting your own custom {@link
* ng.$sceDelegateProvider#methods_resourceUrlWhitelist whitelists} and {@link
* ng.$sceDelegateProvider#methods_resourceUrlBlacklist blacklists} for matching such URLs.
*
* This significantly reduces the overhead. It is far easier to pay the small overhead and have an
* application that's secure and can be audited to verify that with much more ease than bolting
* security onto an application later.
*
* <a name="contexts"></a>
* ## What trusted context types are supported?
*
* | Context | Notes |
* |---------------------|----------------|
* | `$sce.HTML` | For HTML that's safe to source into the application. The {@link ng.directive:ngBindHtml ngBindHtml} directive uses this context for bindings. |
* | `$sce.CSS` | For CSS that's safe to source into the application. Currently unused. Feel free to use it in your own directives. |
* | `$sce.URL` | For URLs that are safe to follow as links. Currently unused (`<a href=` and `<img src=` sanitize their urls and don't consititute an SCE context. |
* | `$sce.RESOURCE_URL` | For URLs that are not only safe to follow as links, but whose contens are also safe to include in your application. Examples include `ng-include`, `src` / `ngSrc` bindings for tags other than `IMG` (e.g. `IFRAME`, `OBJECT`, etc.) <br><br>Note that `$sce.RESOURCE_URL` makes a stronger statement about the URL than `$sce.URL` does and therefore contexts requiring values trusted for `$sce.RESOURCE_URL` can be used anywhere that values trusted for `$sce.URL` are required. |
* | `$sce.JS` | For JavaScript that is safe to execute in your application's context. Currently unused. Feel free to use it in your own directives. |
*
* ## Format of items in {@link ng.$sceDelegateProvider#methods_resourceUrlWhitelist resourceUrlWhitelist}/{@link ng.$sceDelegateProvider#methods_resourceUrlBlacklist Blacklist} <a name="resourceUrlPatternItem"></a>
*
* Each element in these arrays must be one of the following:
*
* - **'self'**
* - The special **string**, `'self'`, can be used to match against all URLs of the **same
* domain** as the application document using the **same protocol**.
* - **String** (except the special value `'self'`)
* - The string is matched against the full *normalized / absolute URL* of the resource
* being tested (substring matches are not good enough.)
* - There are exactly **two wildcard sequences** - `*` and `**`. All other characters
* match themselves.
* - `*`: matches zero or more occurances of any character other than one of the following 6
* characters: '`:`', '`/`', '`.`', '`?`', '`&`' and ';'. It's a useful wildcard for use
* in a whitelist.
* - `**`: matches zero or more occurances of *any* character. As such, it's not
* not appropriate to use in for a scheme, domain, etc. as it would match too much. (e.g.
* http://**.example.com/ would match http://evil.com/?ignore=.example.com/ and that might
* not have been the intention.) It's usage at the very end of the path is ok. (e.g.
* http://foo.example.com/templates/**).
* - **RegExp** (*see caveat below*)
* - *Caveat*: While regular expressions are powerful and offer great flexibility, their syntax
* (and all the inevitable escaping) makes them *harder to maintain*. It's easy to
* accidentally introduce a bug when one updates a complex expression (imho, all regexes should
* have good test coverage.). For instance, the use of `.` in the regex is correct only in a
* small number of cases. A `.` character in the regex used when matching the scheme or a
* subdomain could be matched against a `:` or literal `.` that was likely not intended. It
* is highly recommended to use the string patterns and only fall back to regular expressions
* if they as a last resort.
* - The regular expression must be an instance of RegExp (i.e. not a string.) It is
* matched against the **entire** *normalized / absolute URL* of the resource being tested
* (even when the RegExp did not have the `^` and `$` codes.) In addition, any flags
* present on the RegExp (such as multiline, global, ignoreCase) are ignored.
* - If you are generating your Javascript from some other templating engine (not
* recommended, e.g. in issue [#4006](https://github.com/angular/angular.js/issues/4006)),
* remember to escape your regular expression (and be aware that you might need more than
* one level of escaping depending on your templating engine and the way you interpolated
* the value.) Do make use of your platform's escaping mechanism as it might be good
* enough before coding your own. e.g. Ruby has
* [Regexp.escape(str)](http://www.ruby-doc.org/core-2.0.0/Regexp.html#method-c-escape)
* and Python has [re.escape](http://docs.python.org/library/re.html#re.escape).
* Javascript lacks a similar built in function for escaping. Take a look at Google
* Closure library's [goog.string.regExpEscape(s)](
* http://docs.closure-library.googlecode.com/git/closure_goog_string_string.js.source.html#line962).
*
* Refer {@link ng.$sceDelegateProvider $sceDelegateProvider} for an example.
*
* ## Show me an example using SCE.
*
* @example
<example module="mySceApp">
<file name="index.html">
<div ng-controller="myAppController as myCtrl">
<i ng-bind-html="myCtrl.explicitlyTrustedHtml" id="explicitlyTrustedHtml"></i><br><br>
<b>User comments</b><br>
By default, HTML that isn't explicitly trusted (e.g. Alice's comment) is sanitized when
$sanitize is available. If $sanitize isn't available, this results in an error instead of an
exploit.
<div class="well">
<div ng-repeat="userComment in myCtrl.userComments">
<b>{{userComment.name}}</b>:
<span ng-bind-html="userComment.htmlComment" class="htmlComment"></span>
<br>
</div>
</div>
</div>
</file>
<file name="script.js">
var mySceApp = angular.module('mySceApp', ['ngSanitize']);
mySceApp.controller("myAppController", function myAppController($http, $templateCache, $sce) {
var self = this;
$http.get("test_data.json", {cache: $templateCache}).success(function(userComments) {
self.userComments = userComments;
});
self.explicitlyTrustedHtml = $sce.trustAsHtml(
'<span onmouseover="this.textContent="Explicitly trusted HTML bypasses ' +
'sanitization."">Hover over this text.</span>');
});
</file>
<file name="test_data.json">
[
{ "name": "Alice",
"htmlComment":
"<span onmouseover='this.textContent=\"PWN3D!\"'>Is <i>anyone</i> reading this?</span>"
},
{ "name": "Bob",
"htmlComment": "<i>Yes!</i> Am I the only other one?"
}
]
</file>
<file name="scenario.js">
describe('SCE doc demo', function() {
it('should sanitize untrusted values', function() {
expect(element('.htmlComment').html()).toBe('<span>Is <i>anyone</i> reading this?</span>');
});
it('should NOT sanitize explicitly trusted values', function() {
expect(element('#explicitlyTrustedHtml').html()).toBe(
'<span onmouseover="this.textContent="Explicitly trusted HTML bypasses ' +
'sanitization."">Hover over this text.</span>');
});
});
</file>
</example>
*
*
*
* ## Can I disable SCE completely?
*
* Yes, you can. However, this is strongly discouraged. SCE gives you a lot of security benefits
* for little coding overhead. It will be much harder to take an SCE disabled application and
* either secure it on your own or enable SCE at a later stage. It might make sense to disable SCE
* for cases where you have a lot of existing code that was written before SCE was introduced and
* you're migrating them a module at a time.
*
* That said, here's how you can completely disable SCE:
*
* <pre class="prettyprint">
* angular.module('myAppWithSceDisabledmyApp', []).config(function($sceProvider) {
* // Completely disable SCE. For demonstration purposes only!
* // Do not use in new projects.
* $sceProvider.enabled(false);
* });
* </pre>
*
*/
/* jshint maxlen: 100 */
function $SceProvider() {
var enabled = true;
/**
* @ngdoc function
* @name ng.sceProvider#enabled
* @methodOf ng.$sceProvider
* @function
*
* @param {boolean=} value If provided, then enables/disables SCE.
* @return {boolean} true if SCE is enabled, false otherwise.
*
* @description
* Enables/disables SCE and returns the current value.
*/
this.enabled = function (value) {
if (arguments.length) {
enabled = !!value;
}
return enabled;
};
/* Design notes on the default implementation for SCE.
*
* The API contract for the SCE delegate
* -------------------------------------
* The SCE delegate object must provide the following 3 methods:
*
* - trustAs(contextEnum, value)
* This method is used to tell the SCE service that the provided value is OK to use in the
* contexts specified by contextEnum. It must return an object that will be accepted by
* getTrusted() for a compatible contextEnum and return this value.
*
* - valueOf(value)
* For values that were not produced by trustAs(), return them as is. For values that were
* produced by trustAs(), return the corresponding input value to trustAs. Basically, if
* trustAs is wrapping the given values into some type, this operation unwraps it when given
* such a value.
*
* - getTrusted(contextEnum, value)
* This function should return the a value that is safe to use in the context specified by
* contextEnum or throw and exception otherwise.
*
* NOTE: This contract deliberately does NOT state that values returned by trustAs() must be
* opaque or wrapped in some holder object. That happens to be an implementation detail. For
* instance, an implementation could maintain a registry of all trusted objects by context. In
* such a case, trustAs() would return the same object that was passed in. getTrusted() would
* return the same object passed in if it was found in the registry under a compatible context or
* throw an exception otherwise. An implementation might only wrap values some of the time based
* on some criteria. getTrusted() might return a value and not throw an exception for special
* constants or objects even if not wrapped. All such implementations fulfill this contract.
*
*
* A note on the inheritance model for SCE contexts
* ------------------------------------------------
* I've used inheritance and made RESOURCE_URL wrapped types a subtype of URL wrapped types. This
* is purely an implementation details.
*
* The contract is simply this:
*
* getTrusted($sce.RESOURCE_URL, value) succeeding implies that getTrusted($sce.URL, value)
* will also succeed.
*
* Inheritance happens to capture this in a natural way. In some future, we
* may not use inheritance anymore. That is OK because no code outside of
* sce.js and sceSpecs.js would need to be aware of this detail.
*/
this.$get = ['$parse', '$document', '$sceDelegate', function(
$parse, $document, $sceDelegate) {
// Prereq: Ensure that we're not running in IE8 quirks mode. In that mode, IE allows
// the "expression(javascript expression)" syntax which is insecure.
if (enabled && msie) {
var documentMode = $document[0].documentMode;
if (documentMode !== undefined && documentMode < 8) {
throw $sceMinErr('iequirks',
'Strict Contextual Escaping does not support Internet Explorer version < 9 in quirks ' +
'mode. You can fix this by adding the text <!doctype html> to the top of your HTML ' +
'document. See http://docs.angularjs.org/api/ng.$sce for more information.');
}
}
var sce = copy(SCE_CONTEXTS);
/**
* @ngdoc function
* @name ng.sce#isEnabled
* @methodOf ng.$sce
* @function
*
* @return {Boolean} true if SCE is enabled, false otherwise. If you want to set the value, you
* have to do it at module config time on {@link ng.$sceProvider $sceProvider}.
*
* @description
* Returns a boolean indicating if SCE is enabled.
*/
sce.isEnabled = function () {
return enabled;
};
sce.trustAs = $sceDelegate.trustAs;
sce.getTrusted = $sceDelegate.getTrusted;
sce.valueOf = $sceDelegate.valueOf;
if (!enabled) {
sce.trustAs = sce.getTrusted = function(type, value) { return value; };
sce.valueOf = identity;
}
/**
* @ngdoc method
* @name ng.$sce#parse
* @methodOf ng.$sce
*
* @description
* Converts Angular {@link guide/expression expression} into a function. This is like {@link
* ng.$parse $parse} and is identical when the expression is a literal constant. Otherwise, it
* wraps the expression in a call to {@link ng.$sce#methods_getTrusted $sce.getTrusted(*type*,
* *result*)}
*
* @param {string} type The kind of SCE context in which this result will be used.
* @param {string} expression String expression to compile.
* @returns {function(context, locals)} a function which represents the compiled expression:
*
* * `context` – `{object}` – an object against which any expressions embedded in the strings
* are evaluated against (typically a scope object).
* * `locals` – `{object=}` – local variables context object, useful for overriding values in
* `context`.
*/
sce.parseAs = function sceParseAs(type, expr) {
var parsed = $parse(expr);
if (parsed.literal && parsed.constant) {
return parsed;
} else {
return function sceParseAsTrusted(self, locals) {
return sce.getTrusted(type, parsed(self, locals));
};
}
};
/**
* @ngdoc method
* @name ng.$sce#trustAs
* @methodOf ng.$sce
*
* @description
* Delegates to {@link ng.$sceDelegate#methods_trustAs `$sceDelegate.trustAs`}. As such,
* returns an objectthat is trusted by angular for use in specified strict contextual
* escaping contexts (such as ng-html-bind-unsafe, ng-include, any src attribute
* interpolation, any dom event binding attribute interpolation such as for onclick, etc.)
* that uses the provided value. See * {@link ng.$sce $sce} for enabling strict contextual
* escaping.
*
* @param {string} type The kind of context in which this value is safe for use. e.g. url,
* resource_url, html, js and css.
* @param {*} value The value that that should be considered trusted/safe.
* @returns {*} A value that can be used to stand in for the provided `value` in places
* where Angular expects a $sce.trustAs() return value.
*/
/**
* @ngdoc method
* @name ng.$sce#trustAsHtml
* @methodOf ng.$sce
*
* @description
* Shorthand method. `$sce.trustAsHtml(value)` →
* {@link ng.$sceDelegate#methods_trustAs `$sceDelegate.trustAs($sce.HTML, value)`}
*
* @param {*} value The value to trustAs.
* @returns {*} An object that can be passed to {@link ng.$sce#methods_getTrustedHtml
* $sce.getTrustedHtml(value)} to obtain the original value. (privileged directives
* only accept expressions that are either literal constants or are the
* return value of {@link ng.$sce#methods_trustAs $sce.trustAs}.)
*/
/**
* @ngdoc method
* @name ng.$sce#trustAsUrl
* @methodOf ng.$sce
*
* @description
* Shorthand method. `$sce.trustAsUrl(value)` →
* {@link ng.$sceDelegate#methods_trustAs `$sceDelegate.trustAs($sce.URL, value)`}
*
* @param {*} value The value to trustAs.
* @returns {*} An object that can be passed to {@link ng.$sce#methods_getTrustedUrl
* $sce.getTrustedUrl(value)} to obtain the original value. (privileged directives
* only accept expressions that are either literal constants or are the
* return value of {@link ng.$sce#methods_trustAs $sce.trustAs}.)
*/
/**
* @ngdoc method
* @name ng.$sce#trustAsResourceUrl
* @methodOf ng.$sce
*
* @description
* Shorthand method. `$sce.trustAsResourceUrl(value)` →
* {@link ng.$sceDelegate#methods_trustAs `$sceDelegate.trustAs($sce.RESOURCE_URL, value)`}
*
* @param {*} value The value to trustAs.
* @returns {*} An object that can be passed to {@link ng.$sce#methods_getTrustedResourceUrl
* $sce.getTrustedResourceUrl(value)} to obtain the original value. (privileged directives
* only accept expressions that are either literal constants or are the return
* value of {@link ng.$sce#methods_trustAs $sce.trustAs}.)
*/
/**
* @ngdoc method
* @name ng.$sce#trustAsJs
* @methodOf ng.$sce
*
* @description
* Shorthand method. `$sce.trustAsJs(value)` →
* {@link ng.$sceDelegate#methods_trustAs `$sceDelegate.trustAs($sce.JS, value)`}
*
* @param {*} value The value to trustAs.
* @returns {*} An object that can be passed to {@link ng.$sce#methods_getTrustedJs
* $sce.getTrustedJs(value)} to obtain the original value. (privileged directives
* only accept expressions that are either literal constants or are the
* return value of {@link ng.$sce#methods_trustAs $sce.trustAs}.)
*/
/**
* @ngdoc method
* @name ng.$sce#getTrusted
* @methodOf ng.$sce
*
* @description
* Delegates to {@link ng.$sceDelegate#methods_getTrusted `$sceDelegate.getTrusted`}. As such,
* takes the result of a {@link ng.$sce#methods_trustAs `$sce.trustAs`}() call and returns the
* originally supplied value if the queried context type is a supertype of the created type.
* If this condition isn't satisfied, throws an exception.
*
* @param {string} type The kind of context in which this value is to be used.
* @param {*} maybeTrusted The result of a prior {@link ng.$sce#methods_trustAs `$sce.trustAs`}
* call.
* @returns {*} The value the was originally provided to
* {@link ng.$sce#methods_trustAs `$sce.trustAs`} if valid in this context.
* Otherwise, throws an exception.
*/
/**
* @ngdoc method
* @name ng.$sce#getTrustedHtml
* @methodOf ng.$sce
*
* @description
* Shorthand method. `$sce.getTrustedHtml(value)` →
* {@link ng.$sceDelegate#methods_getTrusted `$sceDelegate.getTrusted($sce.HTML, value)`}
*
* @param {*} value The value to pass to `$sce.getTrusted`.
* @returns {*} The return value of `$sce.getTrusted($sce.HTML, value)`
*/
/**
* @ngdoc method
* @name ng.$sce#getTrustedCss
* @methodOf ng.$sce
*
* @description
* Shorthand method. `$sce.getTrustedCss(value)` →
* {@link ng.$sceDelegate#methods_getTrusted `$sceDelegate.getTrusted($sce.CSS, value)`}
*
* @param {*} value The value to pass to `$sce.getTrusted`.
* @returns {*} The return value of `$sce.getTrusted($sce.CSS, value)`
*/
/**
* @ngdoc method
* @name ng.$sce#getTrustedUrl
* @methodOf ng.$sce
*
* @description
* Shorthand method. `$sce.getTrustedUrl(value)` →
* {@link ng.$sceDelegate#methods_getTrusted `$sceDelegate.getTrusted($sce.URL, value)`}
*
* @param {*} value The value to pass to `$sce.getTrusted`.
* @returns {*} The return value of `$sce.getTrusted($sce.URL, value)`
*/
/**
* @ngdoc method
* @name ng.$sce#getTrustedResourceUrl
* @methodOf ng.$sce
*
* @description
* Shorthand method. `$sce.getTrustedResourceUrl(value)` →
* {@link ng.$sceDelegate#methods_getTrusted `$sceDelegate.getTrusted($sce.RESOURCE_URL, value)`}
*
* @param {*} value The value to pass to `$sceDelegate.getTrusted`.
* @returns {*} The return value of `$sce.getTrusted($sce.RESOURCE_URL, value)`
*/
/**
* @ngdoc method
* @name ng.$sce#getTrustedJs
* @methodOf ng.$sce
*
* @description
* Shorthand method. `$sce.getTrustedJs(value)` →
* {@link ng.$sceDelegate#methods_getTrusted `$sceDelegate.getTrusted($sce.JS, value)`}
*
* @param {*} value The value to pass to `$sce.getTrusted`.
* @returns {*} The return value of `$sce.getTrusted($sce.JS, value)`
*/
/**
* @ngdoc method
* @name ng.$sce#parseAsHtml
* @methodOf ng.$sce
*
* @description
* Shorthand method. `$sce.parseAsHtml(expression string)` →
* {@link ng.$sce#methods_parse `$sce.parseAs($sce.HTML, value)`}
*
* @param {string} expression String expression to compile.
* @returns {function(context, locals)} a function which represents the compiled expression:
*
* * `context` – `{object}` – an object against which any expressions embedded in the strings
* are evaluated against (typically a scope object).
* * `locals` – `{object=}` – local variables context object, useful for overriding values in
* `context`.
*/
/**
* @ngdoc method
* @name ng.$sce#parseAsCss
* @methodOf ng.$sce
*
* @description
* Shorthand method. `$sce.parseAsCss(value)` →
* {@link ng.$sce#methods_parse `$sce.parseAs($sce.CSS, value)`}
*
* @param {string} expression String expression to compile.
* @returns {function(context, locals)} a function which represents the compiled expression:
*
* * `context` – `{object}` – an object against which any expressions embedded in the strings
* are evaluated against (typically a scope object).
* * `locals` – `{object=}` – local variables context object, useful for overriding values in
* `context`.
*/
/**
* @ngdoc method
* @name ng.$sce#parseAsUrl
* @methodOf ng.$sce
*
* @description
* Shorthand method. `$sce.parseAsUrl(value)` →
* {@link ng.$sce#methods_parse `$sce.parseAs($sce.URL, value)`}
*
* @param {string} expression String expression to compile.
* @returns {function(context, locals)} a function which represents the compiled expression:
*
* * `context` – `{object}` – an object against which any expressions embedded in the strings
* are evaluated against (typically a scope object).
* * `locals` – `{object=}` – local variables context object, useful for overriding values in
* `context`.
*/
/**
* @ngdoc method
* @name ng.$sce#parseAsResourceUrl
* @methodOf ng.$sce
*
* @description
* Shorthand method. `$sce.parseAsResourceUrl(value)` →
* {@link ng.$sce#methods_parse `$sce.parseAs($sce.RESOURCE_URL, value)`}
*
* @param {string} expression String expression to compile.
* @returns {function(context, locals)} a function which represents the compiled expression:
*
* * `context` – `{object}` – an object against which any expressions embedded in the strings
* are evaluated against (typically a scope object).
* * `locals` – `{object=}` – local variables context object, useful for overriding values in
* `context`.
*/
/**
* @ngdoc method
* @name ng.$sce#parseAsJs
* @methodOf ng.$sce
*
* @description
* Shorthand method. `$sce.parseAsJs(value)` →
* {@link ng.$sce#methods_parse `$sce.parseAs($sce.JS, value)`}
*
* @param {string} expression String expression to compile.
* @returns {function(context, locals)} a function which represents the compiled expression:
*
* * `context` – `{object}` – an object against which any expressions embedded in the strings
* are evaluated against (typically a scope object).
* * `locals` – `{object=}` – local variables context object, useful for overriding values in
* `context`.
*/
// Shorthand delegations.
var parse = sce.parseAs,
getTrusted = sce.getTrusted,
trustAs = sce.trustAs;
forEach(SCE_CONTEXTS, function (enumValue, name) {
var lName = lowercase(name);
sce[camelCase("parse_as_" + lName)] = function (expr) {
return parse(enumValue, expr);
};
sce[camelCase("get_trusted_" + lName)] = function (value) {
return getTrusted(enumValue, value);
};
sce[camelCase("trust_as_" + lName)] = function (value) {
return trustAs(enumValue, value);
};
});
return sce;
}];
}
/**
* !!! This is an undocumented "private" service !!!
*
* @name ng.$sniffer
* @requires $window
* @requires $document
*
* @property {boolean} history Does the browser support html5 history api ?
* @property {boolean} hashchange Does the browser support hashchange event ?
* @property {boolean} transitions Does the browser support CSS transition events ?
* @property {boolean} animations Does the browser support CSS animation events ?
*
* @description
* This is very simple implementation of testing browser's features.
*/
function $SnifferProvider() {
this.$get = ['$window', '$document', function($window, $document) {
var eventSupport = {},
android =
int((/android (\d+)/.exec(lowercase(($window.navigator || {}).userAgent)) || [])[1]),
boxee = /Boxee/i.test(($window.navigator || {}).userAgent),
document = $document[0] || {},
vendorPrefix,
vendorRegex = /^(Moz|webkit|O|ms)(?=[A-Z])/,
bodyStyle = document.body && document.body.style,
transitions = false,
animations = false,
match;
if (bodyStyle) {
for(var prop in bodyStyle) {
if(match = vendorRegex.exec(prop)) {
vendorPrefix = match[0];
vendorPrefix = vendorPrefix.substr(0, 1).toUpperCase() + vendorPrefix.substr(1);
break;
}
}
if(!vendorPrefix) {
vendorPrefix = ('WebkitOpacity' in bodyStyle) && 'webkit';
}
transitions = !!(('transition' in bodyStyle) || (vendorPrefix + 'Transition' in bodyStyle));
animations = !!(('animation' in bodyStyle) || (vendorPrefix + 'Animation' in bodyStyle));
if (android && (!transitions||!animations)) {
transitions = isString(document.body.style.webkitTransition);
animations = isString(document.body.style.webkitAnimation);
}
}
return {
// Android has history.pushState, but it does not update location correctly
// so let's not use the history API at all.
// http://code.google.com/p/android/issues/detail?id=17471
// https://github.com/angular/angular.js/issues/904
// older webit browser (533.9) on Boxee box has exactly the same problem as Android has
// so let's not use the history API also
// We are purposefully using `!(android < 4)` to cover the case when `android` is undefined
// jshint -W018
history: !!($window.history && $window.history.pushState && !(android < 4) && !boxee),
// jshint +W018
hashchange: 'onhashchange' in $window &&
// IE8 compatible mode lies
(!document.documentMode || document.documentMode > 7),
hasEvent: function(event) {
// IE9 implements 'input' event it's so fubared that we rather pretend that it doesn't have
// it. In particular the event is not fired when backspace or delete key are pressed or
// when cut operation is performed.
if (event == 'input' && msie == 9) return false;
if (isUndefined(eventSupport[event])) {
var divElm = document.createElement('div');
eventSupport[event] = 'on' + event in divElm;
}
return eventSupport[event];
},
csp: csp(),
vendorPrefix: vendorPrefix,
transitions : transitions,
animations : animations,
msie : msie
};
}];
}
function $TimeoutProvider() {
this.$get = ['$rootScope', '$browser', '$q', '$exceptionHandler',
function($rootScope, $browser, $q, $exceptionHandler) {
var deferreds = {};
/**
* @ngdoc function
* @name ng.$timeout
* @requires $browser
*
* @description
* Angular's wrapper for `window.setTimeout`. The `fn` function is wrapped into a try/catch
* block and delegates any exceptions to
* {@link ng.$exceptionHandler $exceptionHandler} service.
*
* The return value of registering a timeout function is a promise, which will be resolved when
* the timeout is reached and the timeout function is executed.
*
* To cancel a timeout request, call `$timeout.cancel(promise)`.
*
* In tests you can use {@link ngMock.$timeout `$timeout.flush()`} to
* synchronously flush the queue of deferred functions.
*
* @param {function()} fn A function, whose execution should be delayed.
* @param {number=} [delay=0] Delay in milliseconds.
* @param {boolean=} [invokeApply=true] If set to `false` skips model dirty checking, otherwise
* will invoke `fn` within the {@link ng.$rootScope.Scope#methods_$apply $apply} block.
* @returns {Promise} Promise that will be resolved when the timeout is reached. The value this
* promise will be resolved with is the return value of the `fn` function.
*
* @example
<doc:example module="time">
<doc:source>
<script>
function Ctrl2($scope,$timeout) {
$scope.format = 'M/d/yy h:mm:ss a';
$scope.blood_1 = 100;
$scope.blood_2 = 120;
var stop;
$scope.fight = function() {
stop = $timeout(function() {
if ($scope.blood_1 > 0 && $scope.blood_2 > 0) {
$scope.blood_1 = $scope.blood_1 - 3;
$scope.blood_2 = $scope.blood_2 - 4;
$scope.fight();
} else {
$timeout.cancel(stop);
}
}, 100);
};
$scope.stopFight = function() {
$timeout.cancel(stop);
};
$scope.resetFight = function() {
$scope.blood_1 = 100;
$scope.blood_2 = 120;
}
}
angular.module('time', [])
// Register the 'myCurrentTime' directive factory method.
// We inject $timeout and dateFilter service since the factory method is DI.
.directive('myCurrentTime', function($timeout, dateFilter) {
// return the directive link function. (compile function not needed)
return function(scope, element, attrs) {
var format, // date format
timeoutId; // timeoutId, so that we can cancel the time updates
// used to update the UI
function updateTime() {
element.text(dateFilter(new Date(), format));
}
// watch the expression, and update the UI on change.
scope.$watch(attrs.myCurrentTime, function(value) {
format = value;
updateTime();
});
// schedule update in one second
function updateLater() {
// save the timeoutId for canceling
timeoutId = $timeout(function() {
updateTime(); // update DOM
updateLater(); // schedule another update
}, 1000);
}
// listen on DOM destroy (removal) event, and cancel the next UI update
// to prevent updating time ofter the DOM element was removed.
element.bind('$destroy', function() {
$timeout.cancel(timeoutId);
});
updateLater(); // kick off the UI update process.
}
});
</script>
<div>
<div ng-controller="Ctrl2">
Date format: <input ng-model="format"> <hr/>
Current time is: <span my-current-time="format"></span>
<hr/>
Blood 1 : <font color='red'>{{blood_1}}</font>
Blood 2 : <font color='red'>{{blood_2}}</font>
<button type="button" data-ng-click="fight()">Fight</button>
<button type="button" data-ng-click="stopFight()">StopFight</button>
<button type="button" data-ng-click="resetFight()">resetFight</button>
</div>
</div>
</doc:source>
</doc:example>
*/
function timeout(fn, delay, invokeApply) {
var deferred = $q.defer(),
promise = deferred.promise,
skipApply = (isDefined(invokeApply) && !invokeApply),
timeoutId;
timeoutId = $browser.defer(function() {
try {
deferred.resolve(fn());
} catch(e) {
deferred.reject(e);
$exceptionHandler(e);
}
finally {
delete deferreds[promise.$$timeoutId];
}
if (!skipApply) $rootScope.$apply();
}, delay);
promise.$$timeoutId = timeoutId;
deferreds[timeoutId] = deferred;
return promise;
}
/**
* @ngdoc function
* @name ng.$timeout#cancel
* @methodOf ng.$timeout
*
* @description
* Cancels a task associated with the `promise`. As a result of this, the promise will be
* resolved with a rejection.
*
* @param {Promise=} promise Promise returned by the `$timeout` function.
* @returns {boolean} Returns `true` if the task hasn't executed yet and was successfully
* canceled.
*/
timeout.cancel = function(promise) {
if (promise && promise.$$timeoutId in deferreds) {
deferreds[promise.$$timeoutId].reject('canceled');
delete deferreds[promise.$$timeoutId];
return $browser.defer.cancel(promise.$$timeoutId);
}
return false;
};
return timeout;
}];
}
// NOTE: The usage of window and document instead of $window and $document here is
// deliberate. This service depends on the specific behavior of anchor nodes created by the
// browser (resolving and parsing URLs) that is unlikely to be provided by mock objects and
// cause us to break tests. In addition, when the browser resolves a URL for XHR, it
// doesn't know about mocked locations and resolves URLs to the real document - which is
// exactly the behavior needed here. There is little value is mocking these out for this
// service.
var urlParsingNode = document.createElement("a");
var originUrl = urlResolve(window.location.href, true);
/**
*
* Implementation Notes for non-IE browsers
* ----------------------------------------
* Assigning a URL to the href property of an anchor DOM node, even one attached to the DOM,
* results both in the normalizing and parsing of the URL. Normalizing means that a relative
* URL will be resolved into an absolute URL in the context of the application document.
* Parsing means that the anchor node's host, hostname, protocol, port, pathname and related
* properties are all populated to reflect the normalized URL. This approach has wide
* compatibility - Safari 1+, Mozilla 1+, Opera 7+,e etc. See
* http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
*
* Implementation Notes for IE
* ---------------------------
* IE >= 8 and <= 10 normalizes the URL when assigned to the anchor node similar to the other
* browsers. However, the parsed components will not be set if the URL assigned did not specify
* them. (e.g. if you assign a.href = "foo", then a.protocol, a.host, etc. will be empty.) We
* work around that by performing the parsing in a 2nd step by taking a previously normalized
* URL (e.g. by assining to a.href) and assigning it a.href again. This correctly populates the
* properties such as protocol, hostname, port, etc.
*
* IE7 does not normalize the URL when assigned to an anchor node. (Apparently, it does, if one
* uses the inner HTML approach to assign the URL as part of an HTML snippet -
* http://stackoverflow.com/a/472729) However, setting img[src] does normalize the URL.
* Unfortunately, setting img[src] to something like "javascript:foo" on IE throws an exception.
* Since the primary usage for normalizing URLs is to sanitize such URLs, we can't use that
* method and IE < 8 is unsupported.
*
* References:
* http://developer.mozilla.org/en-US/docs/Web/API/HTMLAnchorElement
* http://www.aptana.com/reference/html/api/HTMLAnchorElement.html
* http://url.spec.whatwg.org/#urlutils
* https://github.com/angular/angular.js/pull/2902
* http://james.padolsey.com/javascript/parsing-urls-with-the-dom/
*
* @function
* @param {string} url The URL to be parsed.
* @description Normalizes and parses a URL.
* @returns {object} Returns the normalized URL as a dictionary.
*
* | member name | Description |
* |---------------|----------------|
* | href | A normalized version of the provided URL if it was not an absolute URL |
* | protocol | The protocol including the trailing colon |
* | host | The host and port (if the port is non-default) of the normalizedUrl |
* | search | The search params, minus the question mark |
* | hash | The hash string, minus the hash symbol
* | hostname | The hostname
* | port | The port, without ":"
* | pathname | The pathname, beginning with "/"
*
*/
function urlResolve(url) {
var href = url;
if (msie) {
// Normalize before parse. Refer Implementation Notes on why this is
// done in two steps on IE.
urlParsingNode.setAttribute("href", href);
href = urlParsingNode.href;
}
urlParsingNode.setAttribute('href', href);
// $$urlParsingNode provides the UrlUtils interface - http://url.spec.whatwg.org/#urlutils
return {
href: urlParsingNode.href,
protocol: urlParsingNode.protocol ? urlParsingNode.protocol.replace(/:$/, '') : '',
host: urlParsingNode.host,
search: urlParsingNode.search ? urlParsingNode.search.replace(/^\?/, '') : '',
hash: urlParsingNode.hash ? urlParsingNode.hash.replace(/^#/, '') : '',
hostname: urlParsingNode.hostname,
port: urlParsingNode.port,
pathname: urlParsingNode.pathname && urlParsingNode.pathname.charAt(0) === '/' ?
urlParsingNode.pathname : '/' + urlParsingNode.pathname
};
}
/**
* Parse a request URL and determine whether this is a same-origin request as the application document.
*
* @param {string|object} requestUrl The url of the request as a string that will be resolved
* or a parsed URL object.
* @returns {boolean} Whether the request is for the same origin as the application document.
*/
function urlIsSameOrigin(requestUrl) {
var parsed = (isString(requestUrl)) ? urlResolve(requestUrl) : requestUrl;
return (parsed.protocol === originUrl.protocol &&
parsed.host === originUrl.host);
}
/**
* @ngdoc object
* @name ng.$window
*
* @description
* A reference to the browser's `window` object. While `window`
* is globally available in JavaScript, it causes testability problems, because
* it is a global variable. In angular we always refer to it through the
* `$window` service, so it may be overridden, removed or mocked for testing.
*
* Expressions, like the one defined for the `ngClick` directive in the example
* below, are evaluated with respect to the current scope. Therefore, there is
* no risk of inadvertently coding in a dependency on a global value in such an
* expression.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope, $window) {
$scope.$window = $window;
$scope.greeting = 'Hello, World!';
}
</script>
<div ng-controller="Ctrl">
<input type="text" ng-model="greeting" />
<button ng-click="$window.alert(greeting)">ALERT</button>
</div>
</doc:source>
<doc:scenario>
it('should display the greeting in the input box', function() {
input('greeting').enter('Hello, E2E Tests');
// If we click the button it will block the test runner
// element(':button').click();
});
</doc:scenario>
</doc:example>
*/
function $WindowProvider(){
this.$get = valueFn(window);
}
/**
* @ngdoc object
* @name ng.$filterProvider
* @description
*
* Filters are just functions which transform input to an output. However filters need to be
* Dependency Injected. To achieve this a filter definition consists of a factory function which is
* annotated with dependencies and is responsible for creating a filter function.
*
* <pre>
* // Filter registration
* function MyModule($provide, $filterProvider) {
* // create a service to demonstrate injection (not always needed)
* $provide.value('greet', function(name){
* return 'Hello ' + name + '!';
* });
*
* // register a filter factory which uses the
* // greet service to demonstrate DI.
* $filterProvider.register('greet', function(greet){
* // return the filter function which uses the greet service
* // to generate salutation
* return function(text) {
* // filters need to be forgiving so check input validity
* return text && greet(text) || text;
* };
* });
* }
* </pre>
*
* The filter function is registered with the `$injector` under the filter name suffix with
* `Filter`.
*
* <pre>
* it('should be the same instance', inject(
* function($filterProvider) {
* $filterProvider.register('reverse', function(){
* return ...;
* });
* },
* function($filter, reverseFilter) {
* expect($filter('reverse')).toBe(reverseFilter);
* });
* </pre>
*
*
* For more information about how angular filters work, and how to create your own filters, see
* {@link guide/filter Filters} in the Angular Developer Guide.
*/
/**
* @ngdoc method
* @name ng.$filterProvider#register
* @methodOf ng.$filterProvider
* @description
* Register filter factory function.
*
* @param {String} name Name of the filter.
* @param {function} fn The filter factory function which is injectable.
*/
/**
* @ngdoc function
* @name ng.$filter
* @function
* @description
* Filters are used for formatting data displayed to the user.
*
* The general syntax in templates is as follows:
*
* {{ expression [| filter_name[:parameter_value] ... ] }}
*
* @param {String} name Name of the filter function to retrieve
* @return {Function} the filter function
*/
$FilterProvider.$inject = ['$provide'];
function $FilterProvider($provide) {
var suffix = 'Filter';
/**
* @ngdoc function
* @name ng.$controllerProvider#register
* @methodOf ng.$controllerProvider
* @param {string|Object} name Name of the filter function, or an object map of filters where
* the keys are the filter names and the values are the filter factories.
* @returns {Object} Registered filter instance, or if a map of filters was provided then a map
* of the registered filter instances.
*/
function register(name, factory) {
if(isObject(name)) {
var filters = {};
forEach(name, function(filter, key) {
filters[key] = register(key, filter);
});
return filters;
} else {
return $provide.factory(name + suffix, factory);
}
}
this.register = register;
this.$get = ['$injector', function($injector) {
return function(name) {
return $injector.get(name + suffix);
};
}];
////////////////////////////////////////
/* global
currencyFilter: false,
dateFilter: false,
filterFilter: false,
jsonFilter: false,
limitToFilter: false,
lowercaseFilter: false,
numberFilter: false,
orderByFilter: false,
uppercaseFilter: false,
*/
register('currency', currencyFilter);
register('date', dateFilter);
register('filter', filterFilter);
register('json', jsonFilter);
register('limitTo', limitToFilter);
register('lowercase', lowercaseFilter);
register('number', numberFilter);
register('orderBy', orderByFilter);
register('uppercase', uppercaseFilter);
}
/**
* @ngdoc filter
* @name ng.filter:filter
* @function
*
* @description
* Selects a subset of items from `array` and returns it as a new array.
*
* @param {Array} array The source array.
* @param {string|Object|function()} expression The predicate to be used for selecting items from
* `array`.
*
* Can be one of:
*
* - `string`: Predicate that results in a substring match using the value of `expression`
* string. All strings or objects with string properties in `array` that contain this string
* will be returned. The predicate can be negated by prefixing the string with `!`.
*
* - `Object`: A pattern object can be used to filter specific properties on objects contained
* by `array`. For example `{name:"M", phone:"1"}` predicate will return an array of items
* which have property `name` containing "M" and property `phone` containing "1". A special
* property name `$` can be used (as in `{$:"text"}`) to accept a match against any
* property of the object. That's equivalent to the simple substring match with a `string`
* as described above.
*
* - `function`: A predicate function can be used to write arbitrary filters. The function is
* called for each element of `array`. The final result is an array of those elements that
* the predicate returned true for.
*
* @param {function(expected, actual)|true|undefined} comparator Comparator which is used in
* determining if the expected value (from the filter expression) and actual value (from
* the object in the array) should be considered a match.
*
* Can be one of:
*
* - `function(expected, actual)`:
* The function will be given the object value and the predicate value to compare and
* should return true if the item should be included in filtered result.
*
* - `true`: A shorthand for `function(expected, actual) { return angular.equals(expected, actual)}`.
* this is essentially strict comparison of expected and actual.
*
* - `false|undefined`: A short hand for a function which will look for a substring match in case
* insensitive way.
*
* @example
<doc:example>
<doc:source>
<div ng-init="friends = [{name:'John', phone:'555-1276'},
{name:'Mary', phone:'800-BIG-MARY'},
{name:'Mike', phone:'555-4321'},
{name:'Adam', phone:'555-5678'},
{name:'Julie', phone:'555-8765'},
{name:'Juliette', phone:'555-5678'}]"></div>
Search: <input ng-model="searchText">
<table id="searchTextResults">
<tr><th>Name</th><th>Phone</th></tr>
<tr ng-repeat="friend in friends | filter:searchText">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
</tr>
</table>
<hr>
Any: <input ng-model="search.$"> <br>
Name only <input ng-model="search.name"><br>
Phone only <input ng-model="search.phone"><br>
Equality <input type="checkbox" ng-model="strict"><br>
<table id="searchObjResults">
<tr><th>Name</th><th>Phone</th></tr>
<tr ng-repeat="friend in friends | filter:search:strict">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
</tr>
</table>
</doc:source>
<doc:scenario>
it('should search across all fields when filtering with a string', function() {
input('searchText').enter('m');
expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')).
toEqual(['Mary', 'Mike', 'Adam']);
input('searchText').enter('76');
expect(repeater('#searchTextResults tr', 'friend in friends').column('friend.name')).
toEqual(['John', 'Julie']);
});
it('should search in specific fields when filtering with a predicate object', function() {
input('search.$').enter('i');
expect(repeater('#searchObjResults tr', 'friend in friends').column('friend.name')).
toEqual(['Mary', 'Mike', 'Julie', 'Juliette']);
});
it('should use a equal comparison when comparator is true', function() {
input('search.name').enter('Julie');
input('strict').check();
expect(repeater('#searchObjResults tr', 'friend in friends').column('friend.name')).
toEqual(['Julie']);
});
</doc:scenario>
</doc:example>
*/
function filterFilter() {
return function(array, expression, comparator) {
if (!isArray(array)) return array;
var comparatorType = typeof(comparator),
predicates = [];
predicates.check = function(value) {
for (var j = 0; j < predicates.length; j++) {
if(!predicates[j](value)) {
return false;
}
}
return true;
};
if (comparatorType !== 'function') {
if (comparatorType === 'boolean' && comparator) {
comparator = function(obj, text) {
return angular.equals(obj, text);
};
} else {
comparator = function(obj, text) {
text = (''+text).toLowerCase();
return (''+obj).toLowerCase().indexOf(text) > -1;
};
}
}
var search = function(obj, text){
if (typeof text == 'string' && text.charAt(0) === '!') {
return !search(obj, text.substr(1));
}
switch (typeof obj) {
case "boolean":
case "number":
case "string":
return comparator(obj, text);
case "object":
switch (typeof text) {
case "object":
return comparator(obj, text);
default:
for ( var objKey in obj) {
if (objKey.charAt(0) !== '$' && search(obj[objKey], text)) {
return true;
}
}
break;
}
return false;
case "array":
for ( var i = 0; i < obj.length; i++) {
if (search(obj[i], text)) {
return true;
}
}
return false;
default:
return false;
}
};
switch (typeof expression) {
case "boolean":
case "number":
case "string":
// Set up expression object and fall through
expression = {$:expression};
// jshint -W086
case "object":
// jshint +W086
for (var key in expression) {
if (key == '$') {
(function() {
if (!expression[key]) return;
var path = key;
predicates.push(function(value) {
return search(value, expression[path]);
});
})();
} else {
(function() {
if (typeof(expression[key]) == 'undefined') { return; }
var path = key;
predicates.push(function(value) {
return search(getter(value,path), expression[path]);
});
})();
}
}
break;
case 'function':
predicates.push(expression);
break;
default:
return array;
}
var filtered = [];
for ( var j = 0; j < array.length; j++) {
var value = array[j];
if (predicates.check(value)) {
filtered.push(value);
}
}
return filtered;
};
}
/**
* @ngdoc filter
* @name ng.filter:currency
* @function
*
* @description
* Formats a number as a currency (ie $1,234.56). When no currency symbol is provided, default
* symbol for current locale is used.
*
* @param {number} amount Input to filter.
* @param {string=} symbol Currency symbol or identifier to be displayed.
* @returns {string} Formatted number.
*
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.amount = 1234.56;
}
</script>
<div ng-controller="Ctrl">
<input type="number" ng-model="amount"> <br>
default currency symbol ($): {{amount | currency}}<br>
custom currency identifier (USD$): {{amount | currency:"USD$"}}
</div>
</doc:source>
<doc:scenario>
it('should init with 1234.56', function() {
expect(binding('amount | currency')).toBe('$1,234.56');
expect(binding('amount | currency:"USD$"')).toBe('USD$1,234.56');
});
it('should update', function() {
input('amount').enter('-1234');
expect(binding('amount | currency')).toBe('($1,234.00)');
expect(binding('amount | currency:"USD$"')).toBe('(USD$1,234.00)');
});
</doc:scenario>
</doc:example>
*/
currencyFilter.$inject = ['$locale'];
function currencyFilter($locale) {
var formats = $locale.NUMBER_FORMATS;
return function(amount, currencySymbol){
if (isUndefined(currencySymbol)) currencySymbol = formats.CURRENCY_SYM;
return formatNumber(amount, formats.PATTERNS[1], formats.GROUP_SEP, formats.DECIMAL_SEP, 2).
replace(/\u00A4/g, currencySymbol);
};
}
/**
* @ngdoc filter
* @name ng.filter:number
* @function
*
* @description
* Formats a number as text.
*
* If the input is not a number an empty string is returned.
*
* @param {number|string} number Number to format.
* @param {(number|string)=} fractionSize Number of decimal places to round the number to.
* If this is not provided then the fraction size is computed from the current locale's number
* formatting pattern. In the case of the default locale, it will be 3.
* @returns {string} Number rounded to decimalPlaces and places a “,” after each third digit.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.val = 1234.56789;
}
</script>
<div ng-controller="Ctrl">
Enter number: <input ng-model='val'><br>
Default formatting: {{val | number}}<br>
No fractions: {{val | number:0}}<br>
Negative number: {{-val | number:4}}
</div>
</doc:source>
<doc:scenario>
it('should format numbers', function() {
expect(binding('val | number')).toBe('1,234.568');
expect(binding('val | number:0')).toBe('1,235');
expect(binding('-val | number:4')).toBe('-1,234.5679');
});
it('should update', function() {
input('val').enter('3374.333');
expect(binding('val | number')).toBe('3,374.333');
expect(binding('val | number:0')).toBe('3,374');
expect(binding('-val | number:4')).toBe('-3,374.3330');
});
</doc:scenario>
</doc:example>
*/
numberFilter.$inject = ['$locale'];
function numberFilter($locale) {
var formats = $locale.NUMBER_FORMATS;
return function(number, fractionSize) {
return formatNumber(number, formats.PATTERNS[0], formats.GROUP_SEP, formats.DECIMAL_SEP,
fractionSize);
};
}
var DECIMAL_SEP = '.';
function formatNumber(number, pattern, groupSep, decimalSep, fractionSize) {
if (isNaN(number) || !isFinite(number)) return '';
var isNegative = number < 0;
number = Math.abs(number);
var numStr = number + '',
formatedText = '',
parts = [];
var hasExponent = false;
if (numStr.indexOf('e') !== -1) {
var match = numStr.match(/([\d\.]+)e(-?)(\d+)/);
if (match && match[2] == '-' && match[3] > fractionSize + 1) {
numStr = '0';
} else {
formatedText = numStr;
hasExponent = true;
}
}
if (!hasExponent) {
var fractionLen = (numStr.split(DECIMAL_SEP)[1] || '').length;
// determine fractionSize if it is not specified
if (isUndefined(fractionSize)) {
fractionSize = Math.min(Math.max(pattern.minFrac, fractionLen), pattern.maxFrac);
}
var pow = Math.pow(10, fractionSize);
number = Math.round(number * pow) / pow;
var fraction = ('' + number).split(DECIMAL_SEP);
var whole = fraction[0];
fraction = fraction[1] || '';
var i, pos = 0,
lgroup = pattern.lgSize,
group = pattern.gSize;
if (whole.length >= (lgroup + group)) {
pos = whole.length - lgroup;
for (i = 0; i < pos; i++) {
if ((pos - i)%group === 0 && i !== 0) {
formatedText += groupSep;
}
formatedText += whole.charAt(i);
}
}
for (i = pos; i < whole.length; i++) {
if ((whole.length - i)%lgroup === 0 && i !== 0) {
formatedText += groupSep;
}
formatedText += whole.charAt(i);
}
// format fraction part.
while(fraction.length < fractionSize) {
fraction += '0';
}
if (fractionSize && fractionSize !== "0") formatedText += decimalSep + fraction.substr(0, fractionSize);
} else {
if (fractionSize > 0 && number > -1 && number < 1) {
formatedText = number.toFixed(fractionSize);
}
}
parts.push(isNegative ? pattern.negPre : pattern.posPre);
parts.push(formatedText);
parts.push(isNegative ? pattern.negSuf : pattern.posSuf);
return parts.join('');
}
function padNumber(num, digits, trim) {
var neg = '';
if (num < 0) {
neg = '-';
num = -num;
}
num = '' + num;
while(num.length < digits) num = '0' + num;
if (trim)
num = num.substr(num.length - digits);
return neg + num;
}
function dateGetter(name, size, offset, trim) {
offset = offset || 0;
return function(date) {
var value = date['get' + name]();
if (offset > 0 || value > -offset)
value += offset;
if (value === 0 && offset == -12 ) value = 12;
return padNumber(value, size, trim);
};
}
function dateStrGetter(name, shortForm) {
return function(date, formats) {
var value = date['get' + name]();
var get = uppercase(shortForm ? ('SHORT' + name) : name);
return formats[get][value];
};
}
function timeZoneGetter(date) {
var zone = -1 * date.getTimezoneOffset();
var paddedZone = (zone >= 0) ? "+" : "";
paddedZone += padNumber(Math[zone > 0 ? 'floor' : 'ceil'](zone / 60), 2) +
padNumber(Math.abs(zone % 60), 2);
return paddedZone;
}
function ampmGetter(date, formats) {
return date.getHours() < 12 ? formats.AMPMS[0] : formats.AMPMS[1];
}
var DATE_FORMATS = {
yyyy: dateGetter('FullYear', 4),
yy: dateGetter('FullYear', 2, 0, true),
y: dateGetter('FullYear', 1),
MMMM: dateStrGetter('Month'),
MMM: dateStrGetter('Month', true),
MM: dateGetter('Month', 2, 1),
M: dateGetter('Month', 1, 1),
dd: dateGetter('Date', 2),
d: dateGetter('Date', 1),
HH: dateGetter('Hours', 2),
H: dateGetter('Hours', 1),
hh: dateGetter('Hours', 2, -12),
h: dateGetter('Hours', 1, -12),
mm: dateGetter('Minutes', 2),
m: dateGetter('Minutes', 1),
ss: dateGetter('Seconds', 2),
s: dateGetter('Seconds', 1),
// while ISO 8601 requires fractions to be prefixed with `.` or `,`
// we can be just safely rely on using `sss` since we currently don't support single or two digit fractions
sss: dateGetter('Milliseconds', 3),
EEEE: dateStrGetter('Day'),
EEE: dateStrGetter('Day', true),
a: ampmGetter,
Z: timeZoneGetter
};
var DATE_FORMATS_SPLIT = /((?:[^yMdHhmsaZE']+)|(?:'(?:[^']|'')*')|(?:E+|y+|M+|d+|H+|h+|m+|s+|a|Z))(.*)/,
NUMBER_STRING = /^\-?\d+$/;
/**
* @ngdoc filter
* @name ng.filter:date
* @function
*
* @description
* Formats `date` to a string based on the requested `format`.
*
* `format` string can be composed of the following elements:
*
* * `'yyyy'`: 4 digit representation of year (e.g. AD 1 => 0001, AD 2010 => 2010)
* * `'yy'`: 2 digit representation of year, padded (00-99). (e.g. AD 2001 => 01, AD 2010 => 10)
* * `'y'`: 1 digit representation of year, e.g. (AD 1 => 1, AD 199 => 199)
* * `'MMMM'`: Month in year (January-December)
* * `'MMM'`: Month in year (Jan-Dec)
* * `'MM'`: Month in year, padded (01-12)
* * `'M'`: Month in year (1-12)
* * `'dd'`: Day in month, padded (01-31)
* * `'d'`: Day in month (1-31)
* * `'EEEE'`: Day in Week,(Sunday-Saturday)
* * `'EEE'`: Day in Week, (Sun-Sat)
* * `'HH'`: Hour in day, padded (00-23)
* * `'H'`: Hour in day (0-23)
* * `'hh'`: Hour in am/pm, padded (01-12)
* * `'h'`: Hour in am/pm, (1-12)
* * `'mm'`: Minute in hour, padded (00-59)
* * `'m'`: Minute in hour (0-59)
* * `'ss'`: Second in minute, padded (00-59)
* * `'s'`: Second in minute (0-59)
* * `'.sss' or ',sss'`: Millisecond in second, padded (000-999)
* * `'a'`: am/pm marker
* * `'Z'`: 4 digit (+sign) representation of the timezone offset (-1200-+1200)
*
* `format` string can also be one of the following predefined
* {@link guide/i18n localizable formats}:
*
* * `'medium'`: equivalent to `'MMM d, y h:mm:ss a'` for en_US locale
* (e.g. Sep 3, 2010 12:05:08 pm)
* * `'short'`: equivalent to `'M/d/yy h:mm a'` for en_US locale (e.g. 9/3/10 12:05 pm)
* * `'fullDate'`: equivalent to `'EEEE, MMMM d,y'` for en_US locale
* (e.g. Friday, September 3, 2010)
* * `'longDate'`: equivalent to `'MMMM d, y'` for en_US locale (e.g. September 3, 2010)
* * `'mediumDate'`: equivalent to `'MMM d, y'` for en_US locale (e.g. Sep 3, 2010)
* * `'shortDate'`: equivalent to `'M/d/yy'` for en_US locale (e.g. 9/3/10)
* * `'mediumTime'`: equivalent to `'h:mm:ss a'` for en_US locale (e.g. 12:05:08 pm)
* * `'shortTime'`: equivalent to `'h:mm a'` for en_US locale (e.g. 12:05 pm)
*
* `format` string can contain literal values. These need to be quoted with single quotes (e.g.
* `"h 'in the morning'"`). In order to output single quote, use two single quotes in a sequence
* (e.g. `"h 'o''clock'"`).
*
* @param {(Date|number|string)} date Date to format either as Date object, milliseconds (string or
* number) or various ISO 8601 datetime string formats (e.g. yyyy-MM-ddTHH:mm:ss.SSSZ and its
* shorter versions like yyyy-MM-ddTHH:mmZ, yyyy-MM-dd or yyyyMMddTHHmmssZ). If no timezone is
* specified in the string input, the time is considered to be in the local timezone.
* @param {string=} format Formatting rules (see Description). If not specified,
* `mediumDate` is used.
* @returns {string} Formatted string or the input if input is not recognized as date/millis.
*
* @example
<doc:example>
<doc:source>
<span ng-non-bindable>{{1288323623006 | date:'medium'}}</span>:
{{1288323623006 | date:'medium'}}<br>
<span ng-non-bindable>{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}</span>:
{{1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'}}<br>
<span ng-non-bindable>{{1288323623006 | date:'MM/dd/yyyy @ h:mma'}}</span>:
{{'1288323623006' | date:'MM/dd/yyyy @ h:mma'}}<br>
</doc:source>
<doc:scenario>
it('should format date', function() {
expect(binding("1288323623006 | date:'medium'")).
toMatch(/Oct 2\d, 2010 \d{1,2}:\d{2}:\d{2} (AM|PM)/);
expect(binding("1288323623006 | date:'yyyy-MM-dd HH:mm:ss Z'")).
toMatch(/2010\-10\-2\d \d{2}:\d{2}:\d{2} (\-|\+)?\d{4}/);
expect(binding("'1288323623006' | date:'MM/dd/yyyy @ h:mma'")).
toMatch(/10\/2\d\/2010 @ \d{1,2}:\d{2}(AM|PM)/);
});
</doc:scenario>
</doc:example>
*/
dateFilter.$inject = ['$locale'];
function dateFilter($locale) {
var R_ISO8601_STR = /^(\d{4})-?(\d\d)-?(\d\d)(?:T(\d\d)(?::?(\d\d)(?::?(\d\d)(?:\.(\d+))?)?)?(Z|([+-])(\d\d):?(\d\d))?)?$/;
// 1 2 3 4 5 6 7 8 9 10 11
function jsonStringToDate(string) {
var match;
if (match = string.match(R_ISO8601_STR)) {
var date = new Date(0),
tzHour = 0,
tzMin = 0,
dateSetter = match[8] ? date.setUTCFullYear : date.setFullYear,
timeSetter = match[8] ? date.setUTCHours : date.setHours;
if (match[9]) {
tzHour = int(match[9] + match[10]);
tzMin = int(match[9] + match[11]);
}
dateSetter.call(date, int(match[1]), int(match[2]) - 1, int(match[3]));
var h = int(match[4]||0) - tzHour;
var m = int(match[5]||0) - tzMin;
var s = int(match[6]||0);
var ms = Math.round(parseFloat('0.' + (match[7]||0)) * 1000);
timeSetter.call(date, h, m, s, ms);
return date;
}
return string;
}
return function(date, format) {
var text = '',
parts = [],
fn, match;
format = format || 'mediumDate';
format = $locale.DATETIME_FORMATS[format] || format;
if (isString(date)) {
if (NUMBER_STRING.test(date)) {
date = int(date);
} else {
date = jsonStringToDate(date);
}
}
if (isNumber(date)) {
date = new Date(date);
}
if (!isDate(date)) {
return date;
}
while(format) {
match = DATE_FORMATS_SPLIT.exec(format);
if (match) {
parts = concat(parts, match, 1);
format = parts.pop();
} else {
parts.push(format);
format = null;
}
}
forEach(parts, function(value){
fn = DATE_FORMATS[value];
text += fn ? fn(date, $locale.DATETIME_FORMATS)
: value.replace(/(^'|'$)/g, '').replace(/''/g, "'");
});
return text;
};
}
/**
* @ngdoc filter
* @name ng.filter:json
* @function
*
* @description
* Allows you to convert a JavaScript object into JSON string.
*
* This filter is mostly useful for debugging. When using the double curly {{value}} notation
* the binding is automatically converted to JSON.
*
* @param {*} object Any JavaScript object (including arrays and primitive types) to filter.
* @returns {string} JSON string.
*
*
* @example:
<doc:example>
<doc:source>
<pre>{{ {'name':'value'} | json }}</pre>
</doc:source>
<doc:scenario>
it('should jsonify filtered objects', function() {
expect(binding("{'name':'value'}")).toMatch(/\{\n "name": ?"value"\n}/);
});
</doc:scenario>
</doc:example>
*
*/
function jsonFilter() {
return function(object) {
return toJson(object, true);
};
}
/**
* @ngdoc filter
* @name ng.filter:lowercase
* @function
* @description
* Converts string to lowercase.
* @see angular.lowercase
*/
var lowercaseFilter = valueFn(lowercase);
/**
* @ngdoc filter
* @name ng.filter:uppercase
* @function
* @description
* Converts string to uppercase.
* @see angular.uppercase
*/
var uppercaseFilter = valueFn(uppercase);
/**
* @ngdoc function
* @name ng.filter:limitTo
* @function
*
* @description
* Creates a new array or string containing only a specified number of elements. The elements
* are taken from either the beginning or the end of the source array or string, as specified by
* the value and sign (positive or negative) of `limit`.
*
* @param {Array|string} input Source array or string to be limited.
* @param {string|number} limit The length of the returned array or string. If the `limit` number
* is positive, `limit` number of items from the beginning of the source array/string are copied.
* If the number is negative, `limit` number of items from the end of the source array/string
* are copied. The `limit` will be trimmed if it exceeds `array.length`
* @returns {Array|string} A new sub-array or substring of length `limit` or less if input array
* had less than `limit` elements.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.numbers = [1,2,3,4,5,6,7,8,9];
$scope.letters = "abcdefghi";
$scope.numLimit = 3;
$scope.letterLimit = 3;
}
</script>
<div ng-controller="Ctrl">
Limit {{numbers}} to: <input type="integer" ng-model="numLimit">
<p>Output numbers: {{ numbers | limitTo:numLimit }}</p>
Limit {{letters}} to: <input type="integer" ng-model="letterLimit">
<p>Output letters: {{ letters | limitTo:letterLimit }}</p>
</div>
</doc:source>
<doc:scenario>
it('should limit the number array to first three items', function() {
expect(element('.doc-example-live input[ng-model=numLimit]').val()).toBe('3');
expect(element('.doc-example-live input[ng-model=letterLimit]').val()).toBe('3');
expect(binding('numbers | limitTo:numLimit')).toEqual('[1,2,3]');
expect(binding('letters | limitTo:letterLimit')).toEqual('abc');
});
it('should update the output when -3 is entered', function() {
input('numLimit').enter(-3);
input('letterLimit').enter(-3);
expect(binding('numbers | limitTo:numLimit')).toEqual('[7,8,9]');
expect(binding('letters | limitTo:letterLimit')).toEqual('ghi');
});
it('should not exceed the maximum size of input array', function() {
input('numLimit').enter(100);
input('letterLimit').enter(100);
expect(binding('numbers | limitTo:numLimit')).toEqual('[1,2,3,4,5,6,7,8,9]');
expect(binding('letters | limitTo:letterLimit')).toEqual('abcdefghi');
});
</doc:scenario>
</doc:example>
*/
function limitToFilter(){
return function(input, limit) {
if (!isArray(input) && !isString(input)) return input;
limit = int(limit);
if (isString(input)) {
//NaN check on limit
if (limit) {
return limit >= 0 ? input.slice(0, limit) : input.slice(limit, input.length);
} else {
return "";
}
}
var out = [],
i, n;
// if abs(limit) exceeds maximum length, trim it
if (limit > input.length)
limit = input.length;
else if (limit < -input.length)
limit = -input.length;
if (limit > 0) {
i = 0;
n = limit;
} else {
i = input.length + limit;
n = input.length;
}
for (; i<n; i++) {
out.push(input[i]);
}
return out;
};
}
/**
* @ngdoc function
* @name ng.filter:orderBy
* @function
*
* @description
* Orders a specified `array` by the `expression` predicate.
*
* @param {Array} array The array to sort.
* @param {function(*)|string|Array.<(function(*)|string)>} expression A predicate to be
* used by the comparator to determine the order of elements.
*
* Can be one of:
*
* - `function`: Getter function. The result of this function will be sorted using the
* `<`, `=`, `>` operator.
* - `string`: An Angular expression which evaluates to an object to order by, such as 'name'
* to sort by a property called 'name'. Optionally prefixed with `+` or `-` to control
* ascending or descending sort order (for example, +name or -name).
* - `Array`: An array of function or string predicates. The first predicate in the array
* is used for sorting, but when two items are equivalent, the next predicate is used.
*
* @param {boolean=} reverse Reverse the order the array.
* @returns {Array} Sorted copy of the source array.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.friends =
[{name:'John', phone:'555-1212', age:10},
{name:'Mary', phone:'555-9876', age:19},
{name:'Mike', phone:'555-4321', age:21},
{name:'Adam', phone:'555-5678', age:35},
{name:'Julie', phone:'555-8765', age:29}]
$scope.predicate = '-age';
}
</script>
<div ng-controller="Ctrl">
<pre>Sorting predicate = {{predicate}}; reverse = {{reverse}}</pre>
<hr/>
[ <a href="" ng-click="predicate=''">unsorted</a> ]
<table class="friend">
<tr>
<th><a href="" ng-click="predicate = 'name'; reverse=false">Name</a>
(<a href="" ng-click="predicate = '-name'; reverse=false">^</a>)</th>
<th><a href="" ng-click="predicate = 'phone'; reverse=!reverse">Phone Number</a></th>
<th><a href="" ng-click="predicate = 'age'; reverse=!reverse">Age</a></th>
</tr>
<tr ng-repeat="friend in friends | orderBy:predicate:reverse">
<td>{{friend.name}}</td>
<td>{{friend.phone}}</td>
<td>{{friend.age}}</td>
</tr>
</table>
</div>
</doc:source>
<doc:scenario>
it('should be reverse ordered by aged', function() {
expect(binding('predicate')).toBe('-age');
expect(repeater('table.friend', 'friend in friends').column('friend.age')).
toEqual(['35', '29', '21', '19', '10']);
expect(repeater('table.friend', 'friend in friends').column('friend.name')).
toEqual(['Adam', 'Julie', 'Mike', 'Mary', 'John']);
});
it('should reorder the table when user selects different predicate', function() {
element('.doc-example-live a:contains("Name")').click();
expect(repeater('table.friend', 'friend in friends').column('friend.name')).
toEqual(['Adam', 'John', 'Julie', 'Mary', 'Mike']);
expect(repeater('table.friend', 'friend in friends').column('friend.age')).
toEqual(['35', '10', '29', '19', '21']);
element('.doc-example-live a:contains("Phone")').click();
expect(repeater('table.friend', 'friend in friends').column('friend.phone')).
toEqual(['555-9876', '555-8765', '555-5678', '555-4321', '555-1212']);
expect(repeater('table.friend', 'friend in friends').column('friend.name')).
toEqual(['Mary', 'Julie', 'Adam', 'Mike', 'John']);
});
</doc:scenario>
</doc:example>
*/
orderByFilter.$inject = ['$parse'];
function orderByFilter($parse){
return function(array, sortPredicate, reverseOrder) {
if (!isArray(array)) return array;
if (!sortPredicate) return array;
sortPredicate = isArray(sortPredicate) ? sortPredicate: [sortPredicate];
sortPredicate = map(sortPredicate, function(predicate){
var descending = false, get = predicate || identity;
if (isString(predicate)) {
if ((predicate.charAt(0) == '+' || predicate.charAt(0) == '-')) {
descending = predicate.charAt(0) == '-';
predicate = predicate.substring(1);
}
get = $parse(predicate);
}
return reverseComparator(function(a,b){
return compare(get(a),get(b));
}, descending);
});
var arrayCopy = [];
for ( var i = 0; i < array.length; i++) { arrayCopy.push(array[i]); }
return arrayCopy.sort(reverseComparator(comparator, reverseOrder));
function comparator(o1, o2){
for ( var i = 0; i < sortPredicate.length; i++) {
var comp = sortPredicate[i](o1, o2);
if (comp !== 0) return comp;
}
return 0;
}
function reverseComparator(comp, descending) {
return toBoolean(descending)
? function(a,b){return comp(b,a);}
: comp;
}
function compare(v1, v2){
var t1 = typeof v1;
var t2 = typeof v2;
if (t1 == t2) {
if (t1 == "string") {
v1 = v1.toLowerCase();
v2 = v2.toLowerCase();
}
if (v1 === v2) return 0;
return v1 < v2 ? -1 : 1;
} else {
return t1 < t2 ? -1 : 1;
}
}
};
}
function ngDirective(directive) {
if (isFunction(directive)) {
directive = {
link: directive
};
}
directive.restrict = directive.restrict || 'AC';
return valueFn(directive);
}
/**
* @ngdoc directive
* @name ng.directive:a
* @restrict E
*
* @description
* Modifies the default behavior of the html A tag so that the default action is prevented when
* the href attribute is empty.
*
* This change permits the easy creation of action links with the `ngClick` directive
* without changing the location or causing page reloads, e.g.:
* `<a href="" ng-click="list.addItem()">Add Item</a>`
*/
var htmlAnchorDirective = valueFn({
restrict: 'E',
compile: function(element, attr) {
if (msie <= 8) {
// turn <a href ng-click="..">link</a> into a stylable link in IE
// but only if it doesn't have name attribute, in which case it's an anchor
if (!attr.href && !attr.name) {
attr.$set('href', '');
}
// add a comment node to anchors to workaround IE bug that causes element content to be reset
// to new attribute content if attribute is updated with value containing @ and element also
// contains value with @
// see issue #1949
element.append(document.createComment('IE fix'));
}
return function(scope, element) {
element.on('click', function(event){
// if we have no href url, then don't navigate anywhere.
if (!element.attr('href')) {
event.preventDefault();
}
});
};
}
});
/**
* @ngdoc directive
* @name ng.directive:ngHref
* @restrict A
*
* @description
* Using Angular markup like `{{hash}}` in an href attribute will
* make the link go to the wrong URL if the user clicks it before
* Angular has a chance to replace the `{{hash}}` markup with its
* value. Until Angular replaces the markup the link will be broken
* and will most likely return a 404 error.
*
* The `ngHref` directive solves this problem.
*
* The wrong way to write it:
* <pre>
* <a href="http://www.gravatar.com/avatar/{{hash}}"/>
* </pre>
*
* The correct way to write it:
* <pre>
* <a ng-href="http://www.gravatar.com/avatar/{{hash}}"/>
* </pre>
*
* @element A
* @param {template} ngHref any string which can contain `{{}}` markup.
*
* @example
* This example shows various combinations of `href`, `ng-href` and `ng-click` attributes
* in links and their different behaviors:
<doc:example>
<doc:source>
<input ng-model="value" /><br />
<a id="link-1" href ng-click="value = 1">link 1</a> (link, don't reload)<br />
<a id="link-2" href="" ng-click="value = 2">link 2</a> (link, don't reload)<br />
<a id="link-3" ng-href="/{{'123'}}">link 3</a> (link, reload!)<br />
<a id="link-4" href="" name="xx" ng-click="value = 4">anchor</a> (link, don't reload)<br />
<a id="link-5" name="xxx" ng-click="value = 5">anchor</a> (no link)<br />
<a id="link-6" ng-href="{{value}}">link</a> (link, change location)
</doc:source>
<doc:scenario>
it('should execute ng-click but not reload when href without value', function() {
element('#link-1').click();
expect(input('value').val()).toEqual('1');
expect(element('#link-1').attr('href')).toBe("");
});
it('should execute ng-click but not reload when href empty string', function() {
element('#link-2').click();
expect(input('value').val()).toEqual('2');
expect(element('#link-2').attr('href')).toBe("");
});
it('should execute ng-click and change url when ng-href specified', function() {
expect(element('#link-3').attr('href')).toBe("/123");
element('#link-3').click();
expect(browser().window().path()).toEqual('/123');
});
it('should execute ng-click but not reload when href empty string and name specified', function() {
element('#link-4').click();
expect(input('value').val()).toEqual('4');
expect(element('#link-4').attr('href')).toBe('');
});
it('should execute ng-click but not reload when no href but name specified', function() {
element('#link-5').click();
expect(input('value').val()).toEqual('5');
expect(element('#link-5').attr('href')).toBe(undefined);
});
it('should only change url when only ng-href', function() {
input('value').enter('6');
expect(element('#link-6').attr('href')).toBe('6');
element('#link-6').click();
expect(browser().location().url()).toEqual('/6');
});
</doc:scenario>
</doc:example>
*/
/**
* @ngdoc directive
* @name ng.directive:ngSrc
* @restrict A
*
* @description
* Using Angular markup like `{{hash}}` in a `src` attribute doesn't
* work right: The browser will fetch from the URL with the literal
* text `{{hash}}` until Angular replaces the expression inside
* `{{hash}}`. The `ngSrc` directive solves this problem.
*
* The buggy way to write it:
* <pre>
* <img src="http://www.gravatar.com/avatar/{{hash}}"/>
* </pre>
*
* The correct way to write it:
* <pre>
* <img ng-src="http://www.gravatar.com/avatar/{{hash}}"/>
* </pre>
*
* @element IMG
* @param {template} ngSrc any string which can contain `{{}}` markup.
*/
/**
* @ngdoc directive
* @name ng.directive:ngSrcset
* @restrict A
*
* @description
* Using Angular markup like `{{hash}}` in a `srcset` attribute doesn't
* work right: The browser will fetch from the URL with the literal
* text `{{hash}}` until Angular replaces the expression inside
* `{{hash}}`. The `ngSrcset` directive solves this problem.
*
* The buggy way to write it:
* <pre>
* <img srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/>
* </pre>
*
* The correct way to write it:
* <pre>
* <img ng-srcset="http://www.gravatar.com/avatar/{{hash}} 2x"/>
* </pre>
*
* @element IMG
* @param {template} ngSrcset any string which can contain `{{}}` markup.
*/
/**
* @ngdoc directive
* @name ng.directive:ngDisabled
* @restrict A
*
* @description
*
* The following markup will make the button enabled on Chrome/Firefox but not on IE8 and older IEs:
* <pre>
* <div ng-init="scope = { isDisabled: false }">
* <button disabled="{{scope.isDisabled}}">Disabled</button>
* </div>
* </pre>
*
* The HTML specification does not require browsers to preserve the values of boolean attributes
* such as disabled. (Their presence means true and their absence means false.)
* This prevents the Angular compiler from retrieving the binding expression.
* The `ngDisabled` directive solves this problem for the `disabled` attribute.
*
* @example
<doc:example>
<doc:source>
Click me to toggle: <input type="checkbox" ng-model="checked"><br/>
<button ng-model="button" ng-disabled="checked">Button</button>
</doc:source>
<doc:scenario>
it('should toggle button', function() {
expect(element('.doc-example-live :button').prop('disabled')).toBeFalsy();
input('checked').check();
expect(element('.doc-example-live :button').prop('disabled')).toBeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element INPUT
* @param {expression} ngDisabled If the {@link guide/expression expression} is truthy,
* then special attribute "disabled" will be set on the element
*/
/**
* @ngdoc directive
* @name ng.directive:ngChecked
* @restrict A
*
* @description
* The HTML specification does not require browsers to preserve the values of boolean attributes
* such as checked. (Their presence means true and their absence means false.)
* This prevents the Angular compiler from retrieving the binding expression.
* The `ngChecked` directive solves this problem for the `checked` attribute.
* @example
<doc:example>
<doc:source>
Check me to check both: <input type="checkbox" ng-model="master"><br/>
<input id="checkSlave" type="checkbox" ng-checked="master">
</doc:source>
<doc:scenario>
it('should check both checkBoxes', function() {
expect(element('.doc-example-live #checkSlave').prop('checked')).toBeFalsy();
input('master').check();
expect(element('.doc-example-live #checkSlave').prop('checked')).toBeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element INPUT
* @param {expression} ngChecked If the {@link guide/expression expression} is truthy,
* then special attribute "checked" will be set on the element
*/
/**
* @ngdoc directive
* @name ng.directive:ngReadonly
* @restrict A
*
* @description
* The HTML specification does not require browsers to preserve the values of boolean attributes
* such as readonly. (Their presence means true and their absence means false.)
* This prevents the Angular compiler from retrieving the binding expression.
* The `ngReadonly` directive solves this problem for the `readonly` attribute.
* @example
<doc:example>
<doc:source>
Check me to make text readonly: <input type="checkbox" ng-model="checked"><br/>
<input type="text" ng-readonly="checked" value="I'm Angular"/>
</doc:source>
<doc:scenario>
it('should toggle readonly attr', function() {
expect(element('.doc-example-live :text').prop('readonly')).toBeFalsy();
input('checked').check();
expect(element('.doc-example-live :text').prop('readonly')).toBeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element INPUT
* @param {expression} ngReadonly If the {@link guide/expression expression} is truthy,
* then special attribute "readonly" will be set on the element
*/
/**
* @ngdoc directive
* @name ng.directive:ngSelected
* @restrict A
*
* @description
* The HTML specification does not require browsers to preserve the values of boolean attributes
* such as selected. (Their presence means true and their absence means false.)
* This prevents the Angular compiler from retrieving the binding expression.
* The `ngSelected` directive solves this problem for the `selected` atttribute.
* @example
<doc:example>
<doc:source>
Check me to select: <input type="checkbox" ng-model="selected"><br/>
<select>
<option>Hello!</option>
<option id="greet" ng-selected="selected">Greetings!</option>
</select>
</doc:source>
<doc:scenario>
it('should select Greetings!', function() {
expect(element('.doc-example-live #greet').prop('selected')).toBeFalsy();
input('selected').check();
expect(element('.doc-example-live #greet').prop('selected')).toBeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element OPTION
* @param {expression} ngSelected If the {@link guide/expression expression} is truthy,
* then special attribute "selected" will be set on the element
*/
/**
* @ngdoc directive
* @name ng.directive:ngOpen
* @restrict A
*
* @description
* The HTML specification does not require browsers to preserve the values of boolean attributes
* such as open. (Their presence means true and their absence means false.)
* This prevents the Angular compiler from retrieving the binding expression.
* The `ngOpen` directive solves this problem for the `open` attribute.
*
* @example
<doc:example>
<doc:source>
Check me check multiple: <input type="checkbox" ng-model="open"><br/>
<details id="details" ng-open="open">
<summary>Show/Hide me</summary>
</details>
</doc:source>
<doc:scenario>
it('should toggle open', function() {
expect(element('#details').prop('open')).toBeFalsy();
input('open').check();
expect(element('#details').prop('open')).toBeTruthy();
});
</doc:scenario>
</doc:example>
*
* @element DETAILS
* @param {expression} ngOpen If the {@link guide/expression expression} is truthy,
* then special attribute "open" will be set on the element
*/
var ngAttributeAliasDirectives = {};
// boolean attrs are evaluated
forEach(BOOLEAN_ATTR, function(propName, attrName) {
// binding to multiple is not supported
if (propName == "multiple") return;
var normalized = directiveNormalize('ng-' + attrName);
ngAttributeAliasDirectives[normalized] = function() {
return {
priority: 100,
compile: function() {
return function(scope, element, attr) {
scope.$watch(attr[normalized], function ngBooleanAttrWatchAction(value) {
attr.$set(attrName, !!value);
});
};
}
};
};
});
// ng-src, ng-srcset, ng-href are interpolated
forEach(['src', 'srcset', 'href'], function(attrName) {
var normalized = directiveNormalize('ng-' + attrName);
ngAttributeAliasDirectives[normalized] = function() {
return {
priority: 99, // it needs to run after the attributes are interpolated
link: function(scope, element, attr) {
attr.$observe(normalized, function(value) {
if (!value)
return;
attr.$set(attrName, value);
// on IE, if "ng:src" directive declaration is used and "src" attribute doesn't exist
// then calling element.setAttribute('src', 'foo') doesn't do anything, so we need
// to set the property as well to achieve the desired effect.
// we use attr[attrName] value since $set can sanitize the url.
if (msie) element.prop(attrName, attr[attrName]);
});
}
};
};
});
/* global -nullFormCtrl */
var nullFormCtrl = {
$addControl: noop,
$removeControl: noop,
$setValidity: noop,
$setDirty: noop,
$setPristine: noop
};
/**
* @ngdoc object
* @name ng.directive:form.FormController
*
* @property {boolean} $pristine True if user has not interacted with the form yet.
* @property {boolean} $dirty True if user has already interacted with the form.
* @property {boolean} $valid True if all of the containing forms and controls are valid.
* @property {boolean} $invalid True if at least one containing control or form is invalid.
*
* @property {Object} $error Is an object hash, containing references to all invalid controls or
* forms, where:
*
* - keys are validation tokens (error names) — such as `required`, `url` or `email`),
* - values are arrays of controls or forms that are invalid with given error.
*
* @description
* `FormController` keeps track of all its controls and nested forms as well as state of them,
* such as being valid/invalid or dirty/pristine.
*
* Each {@link ng.directive:form form} directive creates an instance
* of `FormController`.
*
*/
//asks for $scope to fool the BC controller module
FormController.$inject = ['$element', '$attrs', '$scope'];
function FormController(element, attrs) {
var form = this,
parentForm = element.parent().controller('form') || nullFormCtrl,
invalidCount = 0, // used to easily determine if we are valid
errors = form.$error = {},
controls = [];
// init state
form.$name = attrs.name || attrs.ngForm;
form.$dirty = false;
form.$pristine = true;
form.$valid = true;
form.$invalid = false;
parentForm.$addControl(form);
// Setup initial state of the control
element.addClass(PRISTINE_CLASS);
toggleValidCss(true);
// convenience method for easy toggling of classes
function toggleValidCss(isValid, validationErrorKey) {
validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
element.
removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey).
addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey);
}
/**
* @ngdoc function
* @name ng.directive:form.FormController#$addControl
* @methodOf ng.directive:form.FormController
*
* @description
* Register a control with the form.
*
* Input elements using ngModelController do this automatically when they are linked.
*/
form.$addControl = function(control) {
// Breaking change - before, inputs whose name was "hasOwnProperty" were quietly ignored
// and not added to the scope. Now we throw an error.
assertNotHasOwnProperty(control.$name, 'input');
controls.push(control);
if (control.$name) {
form[control.$name] = control;
}
};
/**
* @ngdoc function
* @name ng.directive:form.FormController#$removeControl
* @methodOf ng.directive:form.FormController
*
* @description
* Deregister a control from the form.
*
* Input elements using ngModelController do this automatically when they are destroyed.
*/
form.$removeControl = function(control) {
if (control.$name && form[control.$name] === control) {
delete form[control.$name];
}
forEach(errors, function(queue, validationToken) {
form.$setValidity(validationToken, true, control);
});
arrayRemove(controls, control);
};
/**
* @ngdoc function
* @name ng.directive:form.FormController#$setValidity
* @methodOf ng.directive:form.FormController
*
* @description
* Sets the validity of a form control.
*
* This method will also propagate to parent forms.
*/
form.$setValidity = function(validationToken, isValid, control) {
var queue = errors[validationToken];
if (isValid) {
if (queue) {
arrayRemove(queue, control);
if (!queue.length) {
invalidCount--;
if (!invalidCount) {
toggleValidCss(isValid);
form.$valid = true;
form.$invalid = false;
}
errors[validationToken] = false;
toggleValidCss(true, validationToken);
parentForm.$setValidity(validationToken, true, form);
}
}
} else {
if (!invalidCount) {
toggleValidCss(isValid);
}
if (queue) {
if (includes(queue, control)) return;
} else {
errors[validationToken] = queue = [];
invalidCount++;
toggleValidCss(false, validationToken);
parentForm.$setValidity(validationToken, false, form);
}
queue.push(control);
form.$valid = false;
form.$invalid = true;
}
};
/**
* @ngdoc function
* @name ng.directive:form.FormController#$setDirty
* @methodOf ng.directive:form.FormController
*
* @description
* Sets the form to a dirty state.
*
* This method can be called to add the 'ng-dirty' class and set the form to a dirty
* state (ng-dirty class). This method will also propagate to parent forms.
*/
form.$setDirty = function() {
element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS);
form.$dirty = true;
form.$pristine = false;
parentForm.$setDirty();
};
/**
* @ngdoc function
* @name ng.directive:form.FormController#$setPristine
* @methodOf ng.directive:form.FormController
*
* @description
* Sets the form to its pristine state.
*
* This method can be called to remove the 'ng-dirty' class and set the form to its pristine
* state (ng-pristine class). This method will also propagate to all the controls contained
* in this form.
*
* Setting a form back to a pristine state is often useful when we want to 'reuse' a form after
* saving or resetting it.
*/
form.$setPristine = function () {
element.removeClass(DIRTY_CLASS).addClass(PRISTINE_CLASS);
form.$dirty = false;
form.$pristine = true;
forEach(controls, function(control) {
control.$setPristine();
});
};
}
/**
* @ngdoc directive
* @name ng.directive:ngForm
* @restrict EAC
*
* @description
* Nestable alias of {@link ng.directive:form `form`} directive. HTML
* does not allow nesting of form elements. It is useful to nest forms, for example if the validity of a
* sub-group of controls needs to be determined.
*
* @param {string=} ngForm|name Name of the form. If specified, the form controller will be published into
* related scope, under this name.
*
*/
/**
* @ngdoc directive
* @name ng.directive:form
* @restrict E
*
* @description
* Directive that instantiates
* {@link ng.directive:form.FormController FormController}.
*
* If the `name` attribute is specified, the form controller is published onto the current scope under
* this name.
*
* # Alias: {@link ng.directive:ngForm `ngForm`}
*
* In Angular forms can be nested. This means that the outer form is valid when all of the child
* forms are valid as well. However, browsers do not allow nesting of `<form>` elements, so
* Angular provides the {@link ng.directive:ngForm `ngForm`} directive which behaves identically to
* `<form>` but can be nested. This allows you to have nested forms, which is very useful when
* using Angular validation directives in forms that are dynamically generated using the
* {@link ng.directive:ngRepeat `ngRepeat`} directive. Since you cannot dynamically generate the `name`
* attribute of input elements using interpolation, you have to wrap each set of repeated inputs in an
* `ngForm` directive and nest these in an outer `form` element.
*
*
* # CSS classes
* - `ng-valid` Is set if the form is valid.
* - `ng-invalid` Is set if the form is invalid.
* - `ng-pristine` Is set if the form is pristine.
* - `ng-dirty` Is set if the form is dirty.
*
*
* # Submitting a form and preventing the default action
*
* Since the role of forms in client-side Angular applications is different than in classical
* roundtrip apps, it is desirable for the browser not to translate the form submission into a full
* page reload that sends the data to the server. Instead some javascript logic should be triggered
* to handle the form submission in an application-specific way.
*
* For this reason, Angular prevents the default action (form submission to the server) unless the
* `<form>` element has an `action` attribute specified.
*
* You can use one of the following two ways to specify what javascript method should be called when
* a form is submitted:
*
* - {@link ng.directive:ngSubmit ngSubmit} directive on the form element
* - {@link ng.directive:ngClick ngClick} directive on the first
* button or input field of type submit (input[type=submit])
*
* To prevent double execution of the handler, use only one of the {@link ng.directive:ngSubmit ngSubmit}
* or {@link ng.directive:ngClick ngClick} directives.
* This is because of the following form submission rules in the HTML specification:
*
* - If a form has only one input field then hitting enter in this field triggers form submit
* (`ngSubmit`)
* - if a form has 2+ input fields and no buttons or input[type=submit] then hitting enter
* doesn't trigger submit
* - if a form has one or more input fields and one or more buttons or input[type=submit] then
* hitting enter in any of the input fields will trigger the click handler on the *first* button or
* input[type=submit] (`ngClick`) *and* a submit handler on the enclosing form (`ngSubmit`)
*
* @param {string=} name Name of the form. If specified, the form controller will be published into
* related scope, under this name.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.userType = 'guest';
}
</script>
<form name="myForm" ng-controller="Ctrl">
userType: <input name="input" ng-model="userType" required>
<span class="error" ng-show="myForm.input.$error.required">Required!</span><br>
<tt>userType = {{userType}}</tt><br>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('userType')).toEqual('guest');
expect(binding('myForm.input.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('userType').enter('');
expect(binding('userType')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
var formDirectiveFactory = function(isNgForm) {
return ['$timeout', function($timeout) {
var formDirective = {
name: 'form',
restrict: isNgForm ? 'EAC' : 'E',
controller: FormController,
compile: function() {
return {
pre: function(scope, formElement, attr, controller) {
if (!attr.action) {
// we can't use jq events because if a form is destroyed during submission the default
// action is not prevented. see #1238
//
// IE 9 is not affected because it doesn't fire a submit event and try to do a full
// page reload if the form was destroyed by submission of the form via a click handler
// on a button in the form. Looks like an IE9 specific bug.
var preventDefaultListener = function(event) {
event.preventDefault
? event.preventDefault()
: event.returnValue = false; // IE
};
addEventListenerFn(formElement[0], 'submit', preventDefaultListener);
// unregister the preventDefault listener so that we don't not leak memory but in a
// way that will achieve the prevention of the default action.
formElement.on('$destroy', function() {
$timeout(function() {
removeEventListenerFn(formElement[0], 'submit', preventDefaultListener);
}, 0, false);
});
}
var parentFormCtrl = formElement.parent().controller('form'),
alias = attr.name || attr.ngForm;
if (alias) {
setter(scope, alias, controller, alias);
}
if (parentFormCtrl) {
formElement.on('$destroy', function() {
parentFormCtrl.$removeControl(controller);
if (alias) {
setter(scope, alias, undefined, alias);
}
extend(controller, nullFormCtrl); //stop propagating child destruction handlers upwards
});
}
}
};
}
};
return formDirective;
}];
};
var formDirective = formDirectiveFactory();
var ngFormDirective = formDirectiveFactory(true);
/* global
-VALID_CLASS,
-INVALID_CLASS,
-PRISTINE_CLASS,
-DIRTY_CLASS
*/
var URL_REGEXP = /^(ftp|http|https):\/\/(\w+:{0,1}\w*@)?(\S+)(:[0-9]+)?(\/|\/([\w#!:.?+=&%@!\-\/]))?$/;
var EMAIL_REGEXP = /^[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,6}$/;
var NUMBER_REGEXP = /^\s*(\-|\+)?(\d+|(\d*(\.\d*)))\s*$/;
var inputType = {
/**
* @ngdoc inputType
* @name ng.directive:input.text
*
* @description
* Standard HTML text input with angular data binding.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Adds `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
* @param {boolean=} [ngTrim=true] If set to false Angular will not automatically trim the input.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.text = 'guest';
$scope.word = /^\s*\w*\s*$/;
}
</script>
<form name="myForm" ng-controller="Ctrl">
Single word: <input type="text" name="input" ng-model="text"
ng-pattern="word" required ng-trim="false">
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.pattern">
Single word only!</span>
<tt>text = {{text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('text')).toEqual('guest');
expect(binding('myForm.input.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('text').enter('');
expect(binding('text')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
it('should be invalid if multi word', function() {
input('text').enter('hello world');
expect(binding('myForm.input.$valid')).toEqual('false');
});
it('should not be trimmed', function() {
input('text').enter('untrimmed ');
expect(binding('text')).toEqual('untrimmed ');
expect(binding('myForm.input.$valid')).toEqual('true');
});
</doc:scenario>
</doc:example>
*/
'text': textInputType,
/**
* @ngdoc inputType
* @name ng.directive:input.number
*
* @description
* Text input with number validation and transformation. Sets the `number` validation
* error if not a valid number.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} min Sets the `min` validation error key if the value entered is less than `min`.
* @param {string=} max Sets the `max` validation error key if the value entered is greater than `max`.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.value = 12;
}
</script>
<form name="myForm" ng-controller="Ctrl">
Number: <input type="number" name="input" ng-model="value"
min="0" max="99" required>
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.number">
Not valid number!</span>
<tt>value = {{value}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('value')).toEqual('12');
expect(binding('myForm.input.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('value').enter('');
expect(binding('value')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
it('should be invalid if over max', function() {
input('value').enter('123');
expect(binding('value')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
'number': numberInputType,
/**
* @ngdoc inputType
* @name ng.directive:input.url
*
* @description
* Text input with URL validation. Sets the `url` validation error key if the content is not a
* valid URL.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.text = 'http://google.com';
}
</script>
<form name="myForm" ng-controller="Ctrl">
URL: <input type="url" name="input" ng-model="text" required>
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.url">
Not valid url!</span>
<tt>text = {{text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<tt>myForm.$error.url = {{!!myForm.$error.url}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('text')).toEqual('http://google.com');
expect(binding('myForm.input.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('text').enter('');
expect(binding('text')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
it('should be invalid if not url', function() {
input('text').enter('xxx');
expect(binding('myForm.input.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
'url': urlInputType,
/**
* @ngdoc inputType
* @name ng.directive:input.email
*
* @description
* Text input with email validation. Sets the `email` validation error key if not a valid email
* address.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.text = '[email protected]';
}
</script>
<form name="myForm" ng-controller="Ctrl">
Email: <input type="email" name="input" ng-model="text" required>
<span class="error" ng-show="myForm.input.$error.required">
Required!</span>
<span class="error" ng-show="myForm.input.$error.email">
Not valid email!</span>
<tt>text = {{text}}</tt><br/>
<tt>myForm.input.$valid = {{myForm.input.$valid}}</tt><br/>
<tt>myForm.input.$error = {{myForm.input.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
<tt>myForm.$error.email = {{!!myForm.$error.email}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('text')).toEqual('[email protected]');
expect(binding('myForm.input.$valid')).toEqual('true');
});
it('should be invalid if empty', function() {
input('text').enter('');
expect(binding('text')).toEqual('');
expect(binding('myForm.input.$valid')).toEqual('false');
});
it('should be invalid if not email', function() {
input('text').enter('xxx');
expect(binding('myForm.input.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
'email': emailInputType,
/**
* @ngdoc inputType
* @name ng.directive:input.radio
*
* @description
* HTML radio button.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string} value The value to which the expression should be set when selected.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.color = 'blue';
}
</script>
<form name="myForm" ng-controller="Ctrl">
<input type="radio" ng-model="color" value="red"> Red <br/>
<input type="radio" ng-model="color" value="green"> Green <br/>
<input type="radio" ng-model="color" value="blue"> Blue <br/>
<tt>color = {{color}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should change state', function() {
expect(binding('color')).toEqual('blue');
input('color').select('red');
expect(binding('color')).toEqual('red');
});
</doc:scenario>
</doc:example>
*/
'radio': radioInputType,
/**
* @ngdoc inputType
* @name ng.directive:input.checkbox
*
* @description
* HTML checkbox.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} ngTrueValue The value to which the expression should be set when selected.
* @param {string=} ngFalseValue The value to which the expression should be set when not selected.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.value1 = true;
$scope.value2 = 'YES'
}
</script>
<form name="myForm" ng-controller="Ctrl">
Value1: <input type="checkbox" ng-model="value1"> <br/>
Value2: <input type="checkbox" ng-model="value2"
ng-true-value="YES" ng-false-value="NO"> <br/>
<tt>value1 = {{value1}}</tt><br/>
<tt>value2 = {{value2}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should change state', function() {
expect(binding('value1')).toEqual('true');
expect(binding('value2')).toEqual('YES');
input('value1').check();
input('value2').check();
expect(binding('value1')).toEqual('false');
expect(binding('value2')).toEqual('NO');
});
</doc:scenario>
</doc:example>
*/
'checkbox': checkboxInputType,
'hidden': noop,
'button': noop,
'submit': noop,
'reset': noop
};
function textInputType(scope, element, attr, ctrl, $sniffer, $browser) {
var listener = function() {
var value = element.val();
// By default we will trim the value
// If the attribute ng-trim exists we will avoid trimming
// e.g. <input ng-model="foo" ng-trim="false">
if (toBoolean(attr.ngTrim || 'T')) {
value = trim(value);
}
if (ctrl.$viewValue !== value) {
scope.$apply(function() {
ctrl.$setViewValue(value);
});
}
};
// if the browser does support "input" event, we are fine - except on IE9 which doesn't fire the
// input event on backspace, delete or cut
if ($sniffer.hasEvent('input')) {
element.on('input', listener);
} else {
var timeout;
var deferListener = function() {
if (!timeout) {
timeout = $browser.defer(function() {
listener();
timeout = null;
});
}
};
element.on('keydown', function(event) {
var key = event.keyCode;
// ignore
// command modifiers arrows
if (key === 91 || (15 < key && key < 19) || (37 <= key && key <= 40)) return;
deferListener();
});
// if user paste into input using mouse, we need "change" event to catch it
element.on('change', listener);
// if user modifies input value using context menu in IE, we need "paste" and "cut" events to catch it
if ($sniffer.hasEvent('paste')) {
element.on('paste cut', deferListener);
}
}
ctrl.$render = function() {
element.val(ctrl.$isEmpty(ctrl.$viewValue) ? '' : ctrl.$viewValue);
};
// pattern validator
var pattern = attr.ngPattern,
patternValidator,
match;
var validate = function(regexp, value) {
if (ctrl.$isEmpty(value) || regexp.test(value)) {
ctrl.$setValidity('pattern', true);
return value;
} else {
ctrl.$setValidity('pattern', false);
return undefined;
}
};
if (pattern) {
match = pattern.match(/^\/(.*)\/([gim]*)$/);
if (match) {
pattern = new RegExp(match[1], match[2]);
patternValidator = function(value) {
return validate(pattern, value);
};
} else {
patternValidator = function(value) {
var patternObj = scope.$eval(pattern);
if (!patternObj || !patternObj.test) {
throw minErr('ngPattern')('noregexp',
'Expected {0} to be a RegExp but was {1}. Element: {2}', pattern,
patternObj, startingTag(element));
}
return validate(patternObj, value);
};
}
ctrl.$formatters.push(patternValidator);
ctrl.$parsers.push(patternValidator);
}
// min length validator
if (attr.ngMinlength) {
var minlength = int(attr.ngMinlength);
var minLengthValidator = function(value) {
if (!ctrl.$isEmpty(value) && value.length < minlength) {
ctrl.$setValidity('minlength', false);
return undefined;
} else {
ctrl.$setValidity('minlength', true);
return value;
}
};
ctrl.$parsers.push(minLengthValidator);
ctrl.$formatters.push(minLengthValidator);
}
// max length validator
if (attr.ngMaxlength) {
var maxlength = int(attr.ngMaxlength);
var maxLengthValidator = function(value) {
if (!ctrl.$isEmpty(value) && value.length > maxlength) {
ctrl.$setValidity('maxlength', false);
return undefined;
} else {
ctrl.$setValidity('maxlength', true);
return value;
}
};
ctrl.$parsers.push(maxLengthValidator);
ctrl.$formatters.push(maxLengthValidator);
}
}
function numberInputType(scope, element, attr, ctrl, $sniffer, $browser) {
textInputType(scope, element, attr, ctrl, $sniffer, $browser);
ctrl.$parsers.push(function(value) {
var empty = ctrl.$isEmpty(value);
if (empty || NUMBER_REGEXP.test(value)) {
ctrl.$setValidity('number', true);
return value === '' ? null : (empty ? value : parseFloat(value));
} else {
ctrl.$setValidity('number', false);
return undefined;
}
});
ctrl.$formatters.push(function(value) {
return ctrl.$isEmpty(value) ? '' : '' + value;
});
if (attr.min) {
var minValidator = function(value) {
var min = parseFloat(attr.min);
if (!ctrl.$isEmpty(value) && value < min) {
ctrl.$setValidity('min', false);
return undefined;
} else {
ctrl.$setValidity('min', true);
return value;
}
};
ctrl.$parsers.push(minValidator);
ctrl.$formatters.push(minValidator);
}
if (attr.max) {
var maxValidator = function(value) {
var max = parseFloat(attr.max);
if (!ctrl.$isEmpty(value) && value > max) {
ctrl.$setValidity('max', false);
return undefined;
} else {
ctrl.$setValidity('max', true);
return value;
}
};
ctrl.$parsers.push(maxValidator);
ctrl.$formatters.push(maxValidator);
}
ctrl.$formatters.push(function(value) {
if (ctrl.$isEmpty(value) || isNumber(value)) {
ctrl.$setValidity('number', true);
return value;
} else {
ctrl.$setValidity('number', false);
return undefined;
}
});
}
function urlInputType(scope, element, attr, ctrl, $sniffer, $browser) {
textInputType(scope, element, attr, ctrl, $sniffer, $browser);
var urlValidator = function(value) {
if (ctrl.$isEmpty(value) || URL_REGEXP.test(value)) {
ctrl.$setValidity('url', true);
return value;
} else {
ctrl.$setValidity('url', false);
return undefined;
}
};
ctrl.$formatters.push(urlValidator);
ctrl.$parsers.push(urlValidator);
}
function emailInputType(scope, element, attr, ctrl, $sniffer, $browser) {
textInputType(scope, element, attr, ctrl, $sniffer, $browser);
var emailValidator = function(value) {
if (ctrl.$isEmpty(value) || EMAIL_REGEXP.test(value)) {
ctrl.$setValidity('email', true);
return value;
} else {
ctrl.$setValidity('email', false);
return undefined;
}
};
ctrl.$formatters.push(emailValidator);
ctrl.$parsers.push(emailValidator);
}
function radioInputType(scope, element, attr, ctrl) {
// make the name unique, if not defined
if (isUndefined(attr.name)) {
element.attr('name', nextUid());
}
element.on('click', function() {
if (element[0].checked) {
scope.$apply(function() {
ctrl.$setViewValue(attr.value);
});
}
});
ctrl.$render = function() {
var value = attr.value;
element[0].checked = (value == ctrl.$viewValue);
};
attr.$observe('value', ctrl.$render);
}
function checkboxInputType(scope, element, attr, ctrl) {
var trueValue = attr.ngTrueValue,
falseValue = attr.ngFalseValue;
if (!isString(trueValue)) trueValue = true;
if (!isString(falseValue)) falseValue = false;
element.on('click', function() {
scope.$apply(function() {
ctrl.$setViewValue(element[0].checked);
});
});
ctrl.$render = function() {
element[0].checked = ctrl.$viewValue;
};
// Override the standard `$isEmpty` because a value of `false` means empty in a checkbox.
ctrl.$isEmpty = function(value) {
return value !== trueValue;
};
ctrl.$formatters.push(function(value) {
return value === trueValue;
});
ctrl.$parsers.push(function(value) {
return value ? trueValue : falseValue;
});
}
/**
* @ngdoc directive
* @name ng.directive:textarea
* @restrict E
*
* @description
* HTML textarea element control with angular data-binding. The data-binding and validation
* properties of this element are exactly the same as those of the
* {@link ng.directive:input input element}.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*/
/**
* @ngdoc directive
* @name ng.directive:input
* @restrict E
*
* @description
* HTML input element control with angular data-binding. Input control follows HTML5 input types
* and polyfills the HTML5 validation behavior for older browsers.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required Sets `required` validation error key if the value is not entered.
* @param {boolean=} ngRequired Sets `required` attribute if set to true
* @param {number=} ngMinlength Sets `minlength` validation error key if the value is shorter than
* minlength.
* @param {number=} ngMaxlength Sets `maxlength` validation error key if the value is longer than
* maxlength.
* @param {string=} ngPattern Sets `pattern` validation error key if the value does not match the
* RegExp pattern expression. Expected value is `/regexp/` for inline patterns or `regexp` for
* patterns defined as scope expressions.
* @param {string=} ngChange Angular expression to be executed when input changes due to user
* interaction with the input element.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.user = {name: 'guest', last: 'visitor'};
}
</script>
<div ng-controller="Ctrl">
<form name="myForm">
User name: <input type="text" name="userName" ng-model="user.name" required>
<span class="error" ng-show="myForm.userName.$error.required">
Required!</span><br>
Last name: <input type="text" name="lastName" ng-model="user.last"
ng-minlength="3" ng-maxlength="10">
<span class="error" ng-show="myForm.lastName.$error.minlength">
Too short!</span>
<span class="error" ng-show="myForm.lastName.$error.maxlength">
Too long!</span><br>
</form>
<hr>
<tt>user = {{user}}</tt><br/>
<tt>myForm.userName.$valid = {{myForm.userName.$valid}}</tt><br>
<tt>myForm.userName.$error = {{myForm.userName.$error}}</tt><br>
<tt>myForm.lastName.$valid = {{myForm.lastName.$valid}}</tt><br>
<tt>myForm.lastName.$error = {{myForm.lastName.$error}}</tt><br>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br>
<tt>myForm.$error.minlength = {{!!myForm.$error.minlength}}</tt><br>
<tt>myForm.$error.maxlength = {{!!myForm.$error.maxlength}}</tt><br>
</div>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('user')).toEqual('{"name":"guest","last":"visitor"}');
expect(binding('myForm.userName.$valid')).toEqual('true');
expect(binding('myForm.$valid')).toEqual('true');
});
it('should be invalid if empty when required', function() {
input('user.name').enter('');
expect(binding('user')).toEqual('{"last":"visitor"}');
expect(binding('myForm.userName.$valid')).toEqual('false');
expect(binding('myForm.$valid')).toEqual('false');
});
it('should be valid if empty when min length is set', function() {
input('user.last').enter('');
expect(binding('user')).toEqual('{"name":"guest","last":""}');
expect(binding('myForm.lastName.$valid')).toEqual('true');
expect(binding('myForm.$valid')).toEqual('true');
});
it('should be invalid if less than required min length', function() {
input('user.last').enter('xx');
expect(binding('user')).toEqual('{"name":"guest"}');
expect(binding('myForm.lastName.$valid')).toEqual('false');
expect(binding('myForm.lastName.$error')).toMatch(/minlength/);
expect(binding('myForm.$valid')).toEqual('false');
});
it('should be invalid if longer than max length', function() {
input('user.last').enter('some ridiculously long name');
expect(binding('user'))
.toEqual('{"name":"guest"}');
expect(binding('myForm.lastName.$valid')).toEqual('false');
expect(binding('myForm.lastName.$error')).toMatch(/maxlength/);
expect(binding('myForm.$valid')).toEqual('false');
});
</doc:scenario>
</doc:example>
*/
var inputDirective = ['$browser', '$sniffer', function($browser, $sniffer) {
return {
restrict: 'E',
require: '?ngModel',
link: function(scope, element, attr, ctrl) {
if (ctrl) {
(inputType[lowercase(attr.type)] || inputType.text)(scope, element, attr, ctrl, $sniffer,
$browser);
}
}
};
}];
var VALID_CLASS = 'ng-valid',
INVALID_CLASS = 'ng-invalid',
PRISTINE_CLASS = 'ng-pristine',
DIRTY_CLASS = 'ng-dirty';
/**
* @ngdoc object
* @name ng.directive:ngModel.NgModelController
*
* @property {string} $viewValue Actual string value in the view.
* @property {*} $modelValue The value in the model, that the control is bound to.
* @property {Array.<Function>} $parsers Array of functions to execute, as a pipeline, whenever
the control reads value from the DOM. Each function is called, in turn, passing the value
through to the next. Used to sanitize / convert the value as well as validation.
For validation, the parsers should update the validity state using
{@link ng.directive:ngModel.NgModelController#methods_$setValidity $setValidity()},
and return `undefined` for invalid values.
*
* @property {Array.<Function>} $formatters Array of functions to execute, as a pipeline, whenever
the model value changes. Each function is called, in turn, passing the value through to the
next. Used to format / convert values for display in the control and validation.
* <pre>
* function formatter(value) {
* if (value) {
* return value.toUpperCase();
* }
* }
* ngModel.$formatters.push(formatter);
* </pre>
* @property {Object} $error An object hash with all errors as keys.
*
* @property {boolean} $pristine True if user has not interacted with the control yet.
* @property {boolean} $dirty True if user has already interacted with the control.
* @property {boolean} $valid True if there is no error.
* @property {boolean} $invalid True if at least one error on the control.
*
* @description
*
* `NgModelController` provides API for the `ng-model` directive. The controller contains
* services for data-binding, validation, CSS updates, and value formatting and parsing. It
* purposefully does not contain any logic which deals with DOM rendering or listening to
* DOM events. Such DOM related logic should be provided by other directives which make use of
* `NgModelController` for data-binding.
*
* ## Custom Control Example
* This example shows how to use `NgModelController` with a custom control to achieve
* data-binding. Notice how different directives (`contenteditable`, `ng-model`, and `required`)
* collaborate together to achieve the desired result.
*
* Note that `contenteditable` is an HTML5 attribute, which tells the browser to let the element
* contents be edited in place by the user. This will not work on older browsers.
*
* <example module="customControl">
<file name="style.css">
[contenteditable] {
border: 1px solid black;
background-color: white;
min-height: 20px;
}
.ng-invalid {
border: 1px solid red;
}
</file>
<file name="script.js">
angular.module('customControl', []).
directive('contenteditable', function() {
return {
restrict: 'A', // only activate on element attribute
require: '?ngModel', // get a hold of NgModelController
link: function(scope, element, attrs, ngModel) {
if(!ngModel) return; // do nothing if no ng-model
// Specify how UI should be updated
ngModel.$render = function() {
element.html(ngModel.$viewValue || '');
};
// Listen for change events to enable binding
element.on('blur keyup change', function() {
scope.$apply(read);
});
read(); // initialize
// Write data to the model
function read() {
var html = element.html();
// When we clear the content editable the browser leaves a <br> behind
// If strip-br attribute is provided then we strip this out
if( attrs.stripBr && html == '<br>' ) {
html = '';
}
ngModel.$setViewValue(html);
}
}
};
});
</file>
<file name="index.html">
<form name="myForm">
<div contenteditable
name="myWidget" ng-model="userContent"
strip-br="true"
required>Change me!</div>
<span ng-show="myForm.myWidget.$error.required">Required!</span>
<hr>
<textarea ng-model="userContent"></textarea>
</form>
</file>
<file name="scenario.js">
it('should data-bind and become invalid', function() {
var contentEditable = element('[contenteditable]');
expect(contentEditable.text()).toEqual('Change me!');
input('userContent').enter('');
expect(contentEditable.text()).toEqual('');
expect(contentEditable.prop('className')).toMatch(/ng-invalid-required/);
});
</file>
* </example>
*
* ## Isolated Scope Pitfall
*
* Note that if you have a directive with an isolated scope, you cannot require `ngModel`
* since the model value will be looked up on the isolated scope rather than the outer scope.
* When the directive updates the model value, calling `ngModel.$setViewValue()` the property
* on the outer scope will not be updated. However you can get around this by using $parent.
*
* Here is an example of this situation. You'll notice that the first div is not updating the input.
* However the second div can update the input properly.
*
* <example module="badIsolatedDirective">
<file name="script.js">
angular.module('badIsolatedDirective', []).directive('isolate', function() {
return {
require: 'ngModel',
scope: { },
template: '<input ng-model="innerModel">',
link: function(scope, element, attrs, ngModel) {
scope.$watch('innerModel', function(value) {
console.log(value);
ngModel.$setViewValue(value);
});
}
};
});
</file>
<file name="index.html">
<input ng-model="someModel"/>
<div isolate ng-model="someModel"></div>
<div isolate ng-model="$parent.someModel"></div>
</file>
* </example>
*
*
*/
var NgModelController = ['$scope', '$exceptionHandler', '$attrs', '$element', '$parse',
function($scope, $exceptionHandler, $attr, $element, $parse) {
this.$viewValue = Number.NaN;
this.$modelValue = Number.NaN;
this.$parsers = [];
this.$formatters = [];
this.$viewChangeListeners = [];
this.$pristine = true;
this.$dirty = false;
this.$valid = true;
this.$invalid = false;
this.$name = $attr.name;
var ngModelGet = $parse($attr.ngModel),
ngModelSet = ngModelGet.assign;
if (!ngModelSet) {
throw minErr('ngModel')('nonassign', "Expression '{0}' is non-assignable. Element: {1}",
$attr.ngModel, startingTag($element));
}
/**
* @ngdoc function
* @name ng.directive:ngModel.NgModelController#$render
* @methodOf ng.directive:ngModel.NgModelController
*
* @description
* Called when the view needs to be updated. It is expected that the user of the ng-model
* directive will implement this method.
*/
this.$render = noop;
/**
* @ngdoc function
* @name { ng.directive:ngModel.NgModelController#$isEmpty
* @methodOf ng.directive:ngModel.NgModelController
*
* @description
* This is called when we need to determine if the value of the input is empty.
*
* For instance, the required directive does this to work out if the input has data or not.
* The default `$isEmpty` function checks whether the value is `undefined`, `''`, `null` or `NaN`.
*
* You can override this for input directives whose concept of being empty is different to the
* default. The `checkboxInputType` directive does this because in its case a value of `false`
* implies empty.
*/
this.$isEmpty = function(value) {
return isUndefined(value) || value === '' || value === null || value !== value;
};
var parentForm = $element.inheritedData('$formController') || nullFormCtrl,
invalidCount = 0, // used to easily determine if we are valid
$error = this.$error = {}; // keep invalid keys here
// Setup initial state of the control
$element.addClass(PRISTINE_CLASS);
toggleValidCss(true);
// convenience method for easy toggling of classes
function toggleValidCss(isValid, validationErrorKey) {
validationErrorKey = validationErrorKey ? '-' + snake_case(validationErrorKey, '-') : '';
$element.
removeClass((isValid ? INVALID_CLASS : VALID_CLASS) + validationErrorKey).
addClass((isValid ? VALID_CLASS : INVALID_CLASS) + validationErrorKey);
}
/**
* @ngdoc function
* @name ng.directive:ngModel.NgModelController#$setValidity
* @methodOf ng.directive:ngModel.NgModelController
*
* @description
* Change the validity state, and notifies the form when the control changes validity. (i.e. it
* does not notify form if given validator is already marked as invalid).
*
* This method should be called by validators - i.e. the parser or formatter functions.
*
* @param {string} validationErrorKey Name of the validator. the `validationErrorKey` will assign
* to `$error[validationErrorKey]=isValid` so that it is available for data-binding.
* The `validationErrorKey` should be in camelCase and will get converted into dash-case
* for class name. Example: `myError` will result in `ng-valid-my-error` and `ng-invalid-my-error`
* class and can be bound to as `{{someForm.someControl.$error.myError}}` .
* @param {boolean} isValid Whether the current state is valid (true) or invalid (false).
*/
this.$setValidity = function(validationErrorKey, isValid) {
// Purposeful use of ! here to cast isValid to boolean in case it is undefined
// jshint -W018
if ($error[validationErrorKey] === !isValid) return;
// jshint +W018
if (isValid) {
if ($error[validationErrorKey]) invalidCount--;
if (!invalidCount) {
toggleValidCss(true);
this.$valid = true;
this.$invalid = false;
}
} else {
toggleValidCss(false);
this.$invalid = true;
this.$valid = false;
invalidCount++;
}
$error[validationErrorKey] = !isValid;
toggleValidCss(isValid, validationErrorKey);
parentForm.$setValidity(validationErrorKey, isValid, this);
};
/**
* @ngdoc function
* @name ng.directive:ngModel.NgModelController#$setPristine
* @methodOf ng.directive:ngModel.NgModelController
*
* @description
* Sets the control to its pristine state.
*
* This method can be called to remove the 'ng-dirty' class and set the control to its pristine
* state (ng-pristine class).
*/
this.$setPristine = function () {
this.$dirty = false;
this.$pristine = true;
$element.removeClass(DIRTY_CLASS).addClass(PRISTINE_CLASS);
};
/**
* @ngdoc function
* @name ng.directive:ngModel.NgModelController#$setViewValue
* @methodOf ng.directive:ngModel.NgModelController
*
* @description
* Read a value from view.
*
* This method should be called from within a DOM event handler.
* For example {@link ng.directive:input input} or
* {@link ng.directive:select select} directives call it.
*
* It internally calls all `$parsers` (including validators) and updates the `$modelValue` and the actual model path.
* Lastly it calls all registered change listeners.
*
* @param {string} value Value from the view.
*/
this.$setViewValue = function(value) {
this.$viewValue = value;
// change to dirty
if (this.$pristine) {
this.$dirty = true;
this.$pristine = false;
$element.removeClass(PRISTINE_CLASS).addClass(DIRTY_CLASS);
parentForm.$setDirty();
}
forEach(this.$parsers, function(fn) {
value = fn(value);
});
if (this.$modelValue !== value) {
this.$modelValue = value;
ngModelSet($scope, value);
forEach(this.$viewChangeListeners, function(listener) {
try {
listener();
} catch(e) {
$exceptionHandler(e);
}
});
}
};
// model -> value
var ctrl = this;
$scope.$watch(function ngModelWatch() {
var value = ngModelGet($scope);
// if scope model value and ngModel value are out of sync
if (ctrl.$modelValue !== value) {
var formatters = ctrl.$formatters,
idx = formatters.length;
ctrl.$modelValue = value;
while(idx--) {
value = formatters[idx](value);
}
if (ctrl.$viewValue !== value) {
ctrl.$viewValue = value;
ctrl.$render();
}
}
});
}];
/**
* @ngdoc directive
* @name ng.directive:ngModel
*
* @element input
*
* @description
* The `ngModel` directive binds an `input`,`select`, `textarea` (or custom form control) to a
* property on the scope using {@link ng.directive:ngModel.NgModelController NgModelController},
* which is created and exposed by this directive.
*
* `ngModel` is responsible for:
*
* - Binding the view into the model, which other directives such as `input`, `textarea` or `select`
* require.
* - Providing validation behavior (i.e. required, number, email, url).
* - Keeping the state of the control (valid/invalid, dirty/pristine, validation errors).
* - Setting related css classes on the element (`ng-valid`, `ng-invalid`, `ng-dirty`, `ng-pristine`).
* - Registering the control with its parent {@link ng.directive:form form}.
*
* Note: `ngModel` will try to bind to the property given by evaluating the expression on the
* current scope. If the property doesn't already exist on this scope, it will be created
* implicitly and added to the scope.
*
* For best practices on using `ngModel`, see:
*
* - {@link https://github.com/angular/angular.js/wiki/Understanding-Scopes}
*
* For basic examples, how to use `ngModel`, see:
*
* - {@link ng.directive:input input}
* - {@link ng.directive:input.text text}
* - {@link ng.directive:input.checkbox checkbox}
* - {@link ng.directive:input.radio radio}
* - {@link ng.directive:input.number number}
* - {@link ng.directive:input.email email}
* - {@link ng.directive:input.url url}
* - {@link ng.directive:select select}
* - {@link ng.directive:textarea textarea}
*
*/
var ngModelDirective = function() {
return {
require: ['ngModel', '^?form'],
controller: NgModelController,
link: function(scope, element, attr, ctrls) {
// notify others, especially parent forms
var modelCtrl = ctrls[0],
formCtrl = ctrls[1] || nullFormCtrl;
formCtrl.$addControl(modelCtrl);
scope.$on('$destroy', function() {
formCtrl.$removeControl(modelCtrl);
});
}
};
};
/**
* @ngdoc directive
* @name ng.directive:ngChange
*
* @description
* Evaluate given expression when user changes the input.
* The expression is not evaluated when the value change is coming from the model.
*
* Note, this directive requires `ngModel` to be present.
*
* @element input
* @param {expression} ngChange {@link guide/expression Expression} to evaluate upon change
* in input value.
*
* @example
* <doc:example>
* <doc:source>
* <script>
* function Controller($scope) {
* $scope.counter = 0;
* $scope.change = function() {
* $scope.counter++;
* };
* }
* </script>
* <div ng-controller="Controller">
* <input type="checkbox" ng-model="confirmed" ng-change="change()" id="ng-change-example1" />
* <input type="checkbox" ng-model="confirmed" id="ng-change-example2" />
* <label for="ng-change-example2">Confirmed</label><br />
* debug = {{confirmed}}<br />
* counter = {{counter}}
* </div>
* </doc:source>
* <doc:scenario>
* it('should evaluate the expression if changing from view', function() {
* expect(binding('counter')).toEqual('0');
* element('#ng-change-example1').click();
* expect(binding('counter')).toEqual('1');
* expect(binding('confirmed')).toEqual('true');
* });
*
* it('should not evaluate the expression if changing from model', function() {
* element('#ng-change-example2').click();
* expect(binding('counter')).toEqual('0');
* expect(binding('confirmed')).toEqual('true');
* });
* </doc:scenario>
* </doc:example>
*/
var ngChangeDirective = valueFn({
require: 'ngModel',
link: function(scope, element, attr, ctrl) {
ctrl.$viewChangeListeners.push(function() {
scope.$eval(attr.ngChange);
});
}
});
var requiredDirective = function() {
return {
require: '?ngModel',
link: function(scope, elm, attr, ctrl) {
if (!ctrl) return;
attr.required = true; // force truthy in case we are on non input element
var validator = function(value) {
if (attr.required && ctrl.$isEmpty(value)) {
ctrl.$setValidity('required', false);
return;
} else {
ctrl.$setValidity('required', true);
return value;
}
};
ctrl.$formatters.push(validator);
ctrl.$parsers.unshift(validator);
attr.$observe('required', function() {
validator(ctrl.$viewValue);
});
}
};
};
/**
* @ngdoc directive
* @name ng.directive:ngList
*
* @description
* Text input that converts between a delimited string and an array of strings. The delimiter
* can be a fixed string (by default a comma) or a regular expression.
*
* @element input
* @param {string=} ngList optional delimiter that should be used to split the value. If
* specified in form `/something/` then the value will be converted into a regular expression.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.names = ['igor', 'misko', 'vojta'];
}
</script>
<form name="myForm" ng-controller="Ctrl">
List: <input name="namesInput" ng-model="names" ng-list required>
<span class="error" ng-show="myForm.namesInput.$error.required">
Required!</span>
<br>
<tt>names = {{names}}</tt><br/>
<tt>myForm.namesInput.$valid = {{myForm.namesInput.$valid}}</tt><br/>
<tt>myForm.namesInput.$error = {{myForm.namesInput.$error}}</tt><br/>
<tt>myForm.$valid = {{myForm.$valid}}</tt><br/>
<tt>myForm.$error.required = {{!!myForm.$error.required}}</tt><br/>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('names')).toEqual('["igor","misko","vojta"]');
expect(binding('myForm.namesInput.$valid')).toEqual('true');
expect(element('span.error').css('display')).toBe('none');
});
it('should be invalid if empty', function() {
input('names').enter('');
expect(binding('names')).toEqual('');
expect(binding('myForm.namesInput.$valid')).toEqual('false');
expect(element('span.error').css('display')).not().toBe('none');
});
</doc:scenario>
</doc:example>
*/
var ngListDirective = function() {
return {
require: 'ngModel',
link: function(scope, element, attr, ctrl) {
var match = /\/(.*)\//.exec(attr.ngList),
separator = match && new RegExp(match[1]) || attr.ngList || ',';
var parse = function(viewValue) {
// If the viewValue is invalid (say required but empty) it will be `undefined`
if (isUndefined(viewValue)) return;
var list = [];
if (viewValue) {
forEach(viewValue.split(separator), function(value) {
if (value) list.push(trim(value));
});
}
return list;
};
ctrl.$parsers.push(parse);
ctrl.$formatters.push(function(value) {
if (isArray(value)) {
return value.join(', ');
}
return undefined;
});
// Override the standard $isEmpty because an empty array means the input is empty.
ctrl.$isEmpty = function(value) {
return !value || !value.length;
};
}
};
};
var CONSTANT_VALUE_REGEXP = /^(true|false|\d+)$/;
/**
* @ngdoc directive
* @name ng.directive:ngValue
*
* @description
* Binds the given expression to the value of `input[select]` or `input[radio]`, so
* that when the element is selected, the `ngModel` of that element is set to the
* bound value.
*
* `ngValue` is useful when dynamically generating lists of radio buttons using `ng-repeat`, as
* shown below.
*
* @element input
* @param {string=} ngValue angular expression, whose value will be bound to the `value` attribute
* of the `input` element
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.names = ['pizza', 'unicorns', 'robots'];
$scope.my = { favorite: 'unicorns' };
}
</script>
<form ng-controller="Ctrl">
<h2>Which is your favorite?</h2>
<label ng-repeat="name in names" for="{{name}}">
{{name}}
<input type="radio"
ng-model="my.favorite"
ng-value="name"
id="{{name}}"
name="favorite">
</label>
</span>
<div>You chose {{my.favorite}}</div>
</form>
</doc:source>
<doc:scenario>
it('should initialize to model', function() {
expect(binding('my.favorite')).toEqual('unicorns');
});
it('should bind the values to the inputs', function() {
input('my.favorite').select('pizza');
expect(binding('my.favorite')).toEqual('pizza');
});
</doc:scenario>
</doc:example>
*/
var ngValueDirective = function() {
return {
priority: 100,
compile: function(tpl, tplAttr) {
if (CONSTANT_VALUE_REGEXP.test(tplAttr.ngValue)) {
return function ngValueConstantLink(scope, elm, attr) {
attr.$set('value', scope.$eval(attr.ngValue));
};
} else {
return function ngValueLink(scope, elm, attr) {
scope.$watch(attr.ngValue, function valueWatchAction(value) {
attr.$set('value', value);
});
};
}
}
};
};
/**
* @ngdoc directive
* @name ng.directive:ngBind
* @restrict AC
*
* @description
* The `ngBind` attribute tells Angular to replace the text content of the specified HTML element
* with the value of a given expression, and to update the text content when the value of that
* expression changes.
*
* Typically, you don't use `ngBind` directly, but instead you use the double curly markup like
* `{{ expression }}` which is similar but less verbose.
*
* It is preferrable to use `ngBind` instead of `{{ expression }}` when a template is momentarily
* displayed by the browser in its raw state before Angular compiles it. Since `ngBind` is an
* element attribute, it makes the bindings invisible to the user while the page is loading.
*
* An alternative solution to this problem would be using the
* {@link ng.directive:ngCloak ngCloak} directive.
*
*
* @element ANY
* @param {expression} ngBind {@link guide/expression Expression} to evaluate.
*
* @example
* Enter a name in the Live Preview text box; the greeting below the text box changes instantly.
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.name = 'Whirled';
}
</script>
<div ng-controller="Ctrl">
Enter name: <input type="text" ng-model="name"><br>
Hello <span ng-bind="name"></span>!
</div>
</doc:source>
<doc:scenario>
it('should check ng-bind', function() {
expect(using('.doc-example-live').binding('name')).toBe('Whirled');
using('.doc-example-live').input('name').enter('world');
expect(using('.doc-example-live').binding('name')).toBe('world');
});
</doc:scenario>
</doc:example>
*/
var ngBindDirective = ngDirective(function(scope, element, attr) {
element.addClass('ng-binding').data('$binding', attr.ngBind);
scope.$watch(attr.ngBind, function ngBindWatchAction(value) {
// We are purposefully using == here rather than === because we want to
// catch when value is "null or undefined"
// jshint -W041
element.text(value == undefined ? '' : value);
});
});
/**
* @ngdoc directive
* @name ng.directive:ngBindTemplate
*
* @description
* The `ngBindTemplate` directive specifies that the element
* text content should be replaced with the interpolation of the template
* in the `ngBindTemplate` attribute.
* Unlike `ngBind`, the `ngBindTemplate` can contain multiple `{{` `}}`
* expressions. This directive is needed since some HTML elements
* (such as TITLE and OPTION) cannot contain SPAN elements.
*
* @element ANY
* @param {string} ngBindTemplate template of form
* <tt>{{</tt> <tt>expression</tt> <tt>}}</tt> to eval.
*
* @example
* Try it here: enter text in text box and watch the greeting change.
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.salutation = 'Hello';
$scope.name = 'World';
}
</script>
<div ng-controller="Ctrl">
Salutation: <input type="text" ng-model="salutation"><br>
Name: <input type="text" ng-model="name"><br>
<pre ng-bind-template="{{salutation}} {{name}}!"></pre>
</div>
</doc:source>
<doc:scenario>
it('should check ng-bind', function() {
expect(using('.doc-example-live').binding('salutation')).
toBe('Hello');
expect(using('.doc-example-live').binding('name')).
toBe('World');
using('.doc-example-live').input('salutation').enter('Greetings');
using('.doc-example-live').input('name').enter('user');
expect(using('.doc-example-live').binding('salutation')).
toBe('Greetings');
expect(using('.doc-example-live').binding('name')).
toBe('user');
});
</doc:scenario>
</doc:example>
*/
var ngBindTemplateDirective = ['$interpolate', function($interpolate) {
return function(scope, element, attr) {
// TODO: move this to scenario runner
var interpolateFn = $interpolate(element.attr(attr.$attr.ngBindTemplate));
element.addClass('ng-binding').data('$binding', interpolateFn);
attr.$observe('ngBindTemplate', function(value) {
element.text(value);
});
};
}];
/**
* @ngdoc directive
* @name ng.directive:ngBindHtml
*
* @description
* Creates a binding that will innerHTML the result of evaluating the `expression` into the current
* element in a secure way. By default, the innerHTML-ed content will be sanitized using the {@link
* ngSanitize.$sanitize $sanitize} service. To utilize this functionality, ensure that `$sanitize`
* is available, for example, by including {@link ngSanitize} in your module's dependencies (not in
* core Angular.) You may also bypass sanitization for values you know are safe. To do so, bind to
* an explicitly trusted value via {@link ng.$sce#methods_trustAsHtml $sce.trustAsHtml}. See the example
* under {@link ng.$sce#Example Strict Contextual Escaping (SCE)}.
*
* Note: If a `$sanitize` service is unavailable and the bound value isn't explicitly trusted, you
* will have an exception (instead of an exploit.)
*
* @element ANY
* @param {expression} ngBindHtml {@link guide/expression Expression} to evaluate.
*
* @example
* Try it here: enter text in text box and watch the greeting change.
<doc:example module="ngBindHtmlExample" deps="angular-sanitize.js" >
<doc:source>
<script>
angular.module('ngBindHtmlExample', ['ngSanitize'])
.controller('ngBindHtmlCtrl', ['$scope', function ngBindHtmlCtrl($scope) {
$scope.myHTML = 'I am an <code>HTML</code>string with <a href="#">links!</a> and other <em>stuff</em>';
}]);
</script>
<div ng-controller="ngBindHtmlCtrl">
<p ng-bind-html="myHTML"></p>
</div>
</doc:source>
<doc:scenario>
it('should check ng-bind-html', function() {
expect(using('.doc-example-live').binding('myHTML')).
toBe('I am an <code>HTML</code>string with <a href="#">links!</a> and other <em>stuff</em>');
});
</doc:scenario>
</doc:example>
*/
var ngBindHtmlDirective = ['$sce', '$parse', function($sce, $parse) {
return function(scope, element, attr) {
element.addClass('ng-binding').data('$binding', attr.ngBindHtml);
var parsed = $parse(attr.ngBindHtml);
function getStringValue() { return (parsed(scope) || '').toString(); }
scope.$watch(getStringValue, function ngBindHtmlWatchAction(value) {
element.html($sce.getTrustedHtml(parsed(scope)) || '');
});
};
}];
function classDirective(name, selector) {
name = 'ngClass' + name;
return function() {
return {
restrict: 'AC',
link: function(scope, element, attr) {
var oldVal;
scope.$watch(attr[name], ngClassWatchAction, true);
attr.$observe('class', function(value) {
ngClassWatchAction(scope.$eval(attr[name]));
});
if (name !== 'ngClass') {
scope.$watch('$index', function($index, old$index) {
// jshint bitwise: false
var mod = $index & 1;
if (mod !== old$index & 1) {
if (mod === selector) {
addClass(scope.$eval(attr[name]));
} else {
removeClass(scope.$eval(attr[name]));
}
}
});
}
function ngClassWatchAction(newVal) {
if (selector === true || scope.$index % 2 === selector) {
if (oldVal && !equals(newVal,oldVal)) {
removeClass(oldVal);
}
addClass(newVal);
}
oldVal = copy(newVal);
}
function removeClass(classVal) {
attr.$removeClass(flattenClasses(classVal));
}
function addClass(classVal) {
attr.$addClass(flattenClasses(classVal));
}
function flattenClasses(classVal) {
if(isArray(classVal)) {
return classVal.join(' ');
} else if (isObject(classVal)) {
var classes = [], i = 0;
forEach(classVal, function(v, k) {
if (v) {
classes.push(k);
}
});
return classes.join(' ');
}
return classVal;
}
}
};
};
}
/**
* @ngdoc directive
* @name ng.directive:ngClass
* @restrict AC
*
* @description
* The `ngClass` directive allows you to dynamically set CSS classes on an HTML element by databinding
* an expression that represents all classes to be added.
*
* The directive won't add duplicate classes if a particular class was already set.
*
* When the expression changes, the previously added classes are removed and only then the
* new classes are added.
*
* @animations
* add - happens just before the class is applied to the element
* remove - happens just before the class is removed from the element
*
* @element ANY
* @param {expression} ngClass {@link guide/expression Expression} to eval. The result
* of the evaluation can be a string representing space delimited class
* names, an array, or a map of class names to boolean values. In the case of a map, the
* names of the properties whose values are truthy will be added as css classes to the
* element.
*
* @example Example that demonstrates basic bindings via ngClass directive.
<example>
<file name="index.html">
<p ng-class="{strike: strike, bold: bold, red: red}">Map Syntax Example</p>
<input type="checkbox" ng-model="bold"> bold
<input type="checkbox" ng-model="strike"> strike
<input type="checkbox" ng-model="red"> red
<hr>
<p ng-class="style">Using String Syntax</p>
<input type="text" ng-model="style" placeholder="Type: bold strike red">
<hr>
<p ng-class="[style1, style2, style3]">Using Array Syntax</p>
<input ng-model="style1" placeholder="Type: bold"><br>
<input ng-model="style2" placeholder="Type: strike"><br>
<input ng-model="style3" placeholder="Type: red"><br>
</file>
<file name="style.css">
.strike {
text-decoration: line-through;
}
.bold {
font-weight: bold;
}
.red {
color: red;
}
</file>
<file name="scenario.js">
it('should let you toggle the class', function() {
expect(element('.doc-example-live p:first').prop('className')).not().toMatch(/bold/);
expect(element('.doc-example-live p:first').prop('className')).not().toMatch(/red/);
input('bold').check();
expect(element('.doc-example-live p:first').prop('className')).toMatch(/bold/);
input('red').check();
expect(element('.doc-example-live p:first').prop('className')).toMatch(/red/);
});
it('should let you toggle string example', function() {
expect(element('.doc-example-live p:nth-of-type(2)').prop('className')).toBe('');
input('style').enter('red');
expect(element('.doc-example-live p:nth-of-type(2)').prop('className')).toBe('red');
});
it('array example should have 3 classes', function() {
expect(element('.doc-example-live p:last').prop('className')).toBe('');
input('style1').enter('bold');
input('style2').enter('strike');
input('style3').enter('red');
expect(element('.doc-example-live p:last').prop('className')).toBe('bold strike red');
});
</file>
</example>
## Animations
The example below demonstrates how to perform animations using ngClass.
<example animations="true">
<file name="index.html">
<input type="button" value="set" ng-click="myVar='my-class'">
<input type="button" value="clear" ng-click="myVar=''">
<br>
<span class="base-class" ng-class="myVar">Sample Text</span>
</file>
<file name="style.css">
.base-class {
-webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
}
.base-class.my-class {
color: red;
font-size:3em;
}
</file>
<file name="scenario.js">
it('should check ng-class', function() {
expect(element('.doc-example-live span').prop('className')).not().
toMatch(/my-class/);
using('.doc-example-live').element(':button:first').click();
expect(element('.doc-example-live span').prop('className')).
toMatch(/my-class/);
using('.doc-example-live').element(':button:last').click();
expect(element('.doc-example-live span').prop('className')).not().
toMatch(/my-class/);
});
</file>
</example>
## ngClass and pre-existing CSS3 Transitions/Animations
The ngClass directive still supports CSS3 Transitions/Animations even if they do not follow the ngAnimate CSS naming structure.
Upon animation ngAnimate will apply supplementary CSS classes to track the start and end of an animation, but this will not hinder
any pre-existing CSS transitions already on the element. To get an idea of what happens during a class-based animation, be sure
to view the step by step details of {@link ngAnimate.$animate#methods_addclass $animate.addClass} and
{@link ngAnimate.$animate#methods_removeclass $animate.removeClass}.
*/
var ngClassDirective = classDirective('', true);
/**
* @ngdoc directive
* @name ng.directive:ngClassOdd
* @restrict AC
*
* @description
* The `ngClassOdd` and `ngClassEven` directives work exactly as
* {@link ng.directive:ngClass ngClass}, except they work in
* conjunction with `ngRepeat` and take effect only on odd (even) rows.
*
* This directive can be applied only within the scope of an
* {@link ng.directive:ngRepeat ngRepeat}.
*
* @element ANY
* @param {expression} ngClassOdd {@link guide/expression Expression} to eval. The result
* of the evaluation can be a string representing space delimited class names or an array.
*
* @example
<example>
<file name="index.html">
<ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
<li ng-repeat="name in names">
<span ng-class-odd="'odd'" ng-class-even="'even'">
{{name}}
</span>
</li>
</ol>
</file>
<file name="style.css">
.odd {
color: red;
}
.even {
color: blue;
}
</file>
<file name="scenario.js">
it('should check ng-class-odd and ng-class-even', function() {
expect(element('.doc-example-live li:first span').prop('className')).
toMatch(/odd/);
expect(element('.doc-example-live li:last span').prop('className')).
toMatch(/even/);
});
</file>
</example>
*/
var ngClassOddDirective = classDirective('Odd', 0);
/**
* @ngdoc directive
* @name ng.directive:ngClassEven
* @restrict AC
*
* @description
* The `ngClassOdd` and `ngClassEven` directives work exactly as
* {@link ng.directive:ngClass ngClass}, except they work in
* conjunction with `ngRepeat` and take effect only on odd (even) rows.
*
* This directive can be applied only within the scope of an
* {@link ng.directive:ngRepeat ngRepeat}.
*
* @element ANY
* @param {expression} ngClassEven {@link guide/expression Expression} to eval. The
* result of the evaluation can be a string representing space delimited class names or an array.
*
* @example
<example>
<file name="index.html">
<ol ng-init="names=['John', 'Mary', 'Cate', 'Suz']">
<li ng-repeat="name in names">
<span ng-class-odd="'odd'" ng-class-even="'even'">
{{name}}
</span>
</li>
</ol>
</file>
<file name="style.css">
.odd {
color: red;
}
.even {
color: blue;
}
</file>
<file name="scenario.js">
it('should check ng-class-odd and ng-class-even', function() {
expect(element('.doc-example-live li:first span').prop('className')).
toMatch(/odd/);
expect(element('.doc-example-live li:last span').prop('className')).
toMatch(/even/);
});
</file>
</example>
*/
var ngClassEvenDirective = classDirective('Even', 1);
/**
* @ngdoc directive
* @name ng.directive:ngCloak
* @restrict AC
*
* @description
* The `ngCloak` directive is used to prevent the Angular html template from being briefly
* displayed by the browser in its raw (uncompiled) form while your application is loading. Use this
* directive to avoid the undesirable flicker effect caused by the html template display.
*
* The directive can be applied to the `<body>` element, but the preferred usage is to apply
* multiple `ngCloak` directives to small portions of the page to permit progressive rendering
* of the browser view.
*
* `ngCloak` works in cooperation with the following css rule embedded within `angular.js` and
* `angular.min.js`.
* For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
*
* <pre>
* [ng\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak], .ng-cloak, .x-ng-cloak {
* display: none !important;
* }
* </pre>
*
* When this css rule is loaded by the browser, all html elements (including their children) that
* are tagged with the `ngCloak` directive are hidden. When Angular encounters this directive
* during the compilation of the template it deletes the `ngCloak` element attribute, making
* the compiled element visible.
*
* For the best result, the `angular.js` script must be loaded in the head section of the html
* document; alternatively, the css rule above must be included in the external stylesheet of the
* application.
*
* Legacy browsers, like IE7, do not provide attribute selector support (added in CSS 2.1) so they
* cannot match the `[ng\:cloak]` selector. To work around this limitation, you must add the css
* class `ngCloak` in addition to the `ngCloak` directive as shown in the example below.
*
* @element ANY
*
* @example
<doc:example>
<doc:source>
<div id="template1" ng-cloak>{{ 'hello' }}</div>
<div id="template2" ng-cloak class="ng-cloak">{{ 'hello IE7' }}</div>
</doc:source>
<doc:scenario>
it('should remove the template directive and css class', function() {
expect(element('.doc-example-live #template1').attr('ng-cloak')).
not().toBeDefined();
expect(element('.doc-example-live #template2').attr('ng-cloak')).
not().toBeDefined();
});
</doc:scenario>
</doc:example>
*
*/
var ngCloakDirective = ngDirective({
compile: function(element, attr) {
attr.$set('ngCloak', undefined);
element.removeClass('ng-cloak');
}
});
/**
* @ngdoc directive
* @name ng.directive:ngController
*
* @description
* The `ngController` directive attaches a controller class to the view. This is a key aspect of how angular
* supports the principles behind the Model-View-Controller design pattern.
*
* MVC components in angular:
*
* * Model — The Model is scope properties; scopes are attached to the DOM where scope properties
* are accessed through bindings.
* * View — The template (HTML with data bindings) that is rendered into the View.
* * Controller — The `ngController` directive specifies a Controller class; the class contains business
* logic behind the application to decorate the scope with functions and values
*
* Note that you can also attach controllers to the DOM by declaring it in a route definition
* via the {@link ngRoute.$route $route} service. A common mistake is to declare the controller
* again using `ng-controller` in the template itself. This will cause the controller to be attached
* and executed twice.
*
* @element ANY
* @scope
* @param {expression} ngController Name of a globally accessible constructor function or an
* {@link guide/expression expression} that on the current scope evaluates to a
* constructor function. The controller instance can be published into a scope property
* by specifying `as propertyName`.
*
* @example
* Here is a simple form for editing user contact information. Adding, removing, clearing, and
* greeting are methods declared on the controller (see source tab). These methods can
* easily be called from the angular markup. Notice that the scope becomes the `this` for the
* controller's instance. This allows for easy access to the view data from the controller. Also
* notice that any changes to the data are automatically reflected in the View without the need
* for a manual update. The example is shown in two different declaration styles you may use
* according to preference.
<doc:example>
<doc:source>
<script>
function SettingsController1() {
this.name = "John Smith";
this.contacts = [
{type: 'phone', value: '408 555 1212'},
{type: 'email', value: '[email protected]'} ];
};
SettingsController1.prototype.greet = function() {
alert(this.name);
};
SettingsController1.prototype.addContact = function() {
this.contacts.push({type: 'email', value: '[email protected]'});
};
SettingsController1.prototype.removeContact = function(contactToRemove) {
var index = this.contacts.indexOf(contactToRemove);
this.contacts.splice(index, 1);
};
SettingsController1.prototype.clearContact = function(contact) {
contact.type = 'phone';
contact.value = '';
};
</script>
<div id="ctrl-as-exmpl" ng-controller="SettingsController1 as settings">
Name: <input type="text" ng-model="settings.name"/>
[ <a href="" ng-click="settings.greet()">greet</a> ]<br/>
Contact:
<ul>
<li ng-repeat="contact in settings.contacts">
<select ng-model="contact.type">
<option>phone</option>
<option>email</option>
</select>
<input type="text" ng-model="contact.value"/>
[ <a href="" ng-click="settings.clearContact(contact)">clear</a>
| <a href="" ng-click="settings.removeContact(contact)">X</a> ]
</li>
<li>[ <a href="" ng-click="settings.addContact()">add</a> ]</li>
</ul>
</div>
</doc:source>
<doc:scenario>
it('should check controller as', function() {
expect(element('#ctrl-as-exmpl>:input').val()).toBe('John Smith');
expect(element('#ctrl-as-exmpl li:nth-child(1) input').val())
.toBe('408 555 1212');
expect(element('#ctrl-as-exmpl li:nth-child(2) input').val())
.toBe('[email protected]');
element('#ctrl-as-exmpl li:first a:contains("clear")').click();
expect(element('#ctrl-as-exmpl li:first input').val()).toBe('');
element('#ctrl-as-exmpl li:last a:contains("add")').click();
expect(element('#ctrl-as-exmpl li:nth-child(3) input').val())
.toBe('[email protected]');
});
</doc:scenario>
</doc:example>
<doc:example>
<doc:source>
<script>
function SettingsController2($scope) {
$scope.name = "John Smith";
$scope.contacts = [
{type:'phone', value:'408 555 1212'},
{type:'email', value:'[email protected]'} ];
$scope.greet = function() {
alert(this.name);
};
$scope.addContact = function() {
this.contacts.push({type:'email', value:'[email protected]'});
};
$scope.removeContact = function(contactToRemove) {
var index = this.contacts.indexOf(contactToRemove);
this.contacts.splice(index, 1);
};
$scope.clearContact = function(contact) {
contact.type = 'phone';
contact.value = '';
};
}
</script>
<div id="ctrl-exmpl" ng-controller="SettingsController2">
Name: <input type="text" ng-model="name"/>
[ <a href="" ng-click="greet()">greet</a> ]<br/>
Contact:
<ul>
<li ng-repeat="contact in contacts">
<select ng-model="contact.type">
<option>phone</option>
<option>email</option>
</select>
<input type="text" ng-model="contact.value"/>
[ <a href="" ng-click="clearContact(contact)">clear</a>
| <a href="" ng-click="removeContact(contact)">X</a> ]
</li>
<li>[ <a href="" ng-click="addContact()">add</a> ]</li>
</ul>
</div>
</doc:source>
<doc:scenario>
it('should check controller', function() {
expect(element('#ctrl-exmpl>:input').val()).toBe('John Smith');
expect(element('#ctrl-exmpl li:nth-child(1) input').val())
.toBe('408 555 1212');
expect(element('#ctrl-exmpl li:nth-child(2) input').val())
.toBe('[email protected]');
element('#ctrl-exmpl li:first a:contains("clear")').click();
expect(element('#ctrl-exmpl li:first input').val()).toBe('');
element('#ctrl-exmpl li:last a:contains("add")').click();
expect(element('#ctrl-exmpl li:nth-child(3) input').val())
.toBe('[email protected]');
});
</doc:scenario>
</doc:example>
*/
var ngControllerDirective = [function() {
return {
scope: true,
controller: '@'
};
}];
/**
* @ngdoc directive
* @name ng.directive:ngCsp
*
* @element html
* @description
* Enables [CSP (Content Security Policy)](https://developer.mozilla.org/en/Security/CSP) support.
*
* This is necessary when developing things like Google Chrome Extensions.
*
* CSP forbids apps to use `eval` or `Function(string)` generated functions (among other things).
* For us to be compatible, we just need to implement the "getterFn" in $parse without violating
* any of these restrictions.
*
* AngularJS uses `Function(string)` generated functions as a speed optimization. Applying the `ngCsp`
* directive will cause Angular to use CSP compatibility mode. When this mode is on AngularJS will
* evaluate all expressions up to 30% slower than in non-CSP mode, but no security violations will
* be raised.
*
* CSP forbids JavaScript to inline stylesheet rules. In non CSP mode Angular automatically
* includes some CSS rules (e.g. {@link ng.directive:ngCloak ngCloak}).
* To make those directives work in CSP mode, include the `angular-csp.css` manually.
*
* In order to use this feature put the `ngCsp` directive on the root element of the application.
*
* *Note: This directive is only available in the `ng-csp` and `data-ng-csp` attribute form.*
*
* @example
* This example shows how to apply the `ngCsp` directive to the `html` tag.
<pre>
<!doctype html>
<html ng-app ng-csp>
...
...
</html>
</pre>
*/
// ngCsp is not implemented as a proper directive any more, because we need it be processed while we bootstrap
// the system (before $parse is instantiated), for this reason we just have a csp() fn that looks for ng-csp attribute
// anywhere in the current doc
/**
* @ngdoc directive
* @name ng.directive:ngClick
*
* @description
* The ngClick directive allows you to specify custom behavior when
* an element is clicked.
*
* @element ANY
* @param {expression} ngClick {@link guide/expression Expression} to evaluate upon
* click. (Event object is available as `$event`)
*
* @example
<doc:example>
<doc:source>
<button ng-click="count = count + 1" ng-init="count=0">
Increment
</button>
count: {{count}}
</doc:source>
<doc:scenario>
it('should check ng-click', function() {
expect(binding('count')).toBe('0');
element('.doc-example-live :button').click();
expect(binding('count')).toBe('1');
});
</doc:scenario>
</doc:example>
*/
/*
* A directive that allows creation of custom onclick handlers that are defined as angular
* expressions and are compiled and executed within the current scope.
*
* Events that are handled via these handler are always configured not to propagate further.
*/
var ngEventDirectives = {};
forEach(
'click dblclick mousedown mouseup mouseover mouseout mousemove mouseenter mouseleave keydown keyup keypress submit focus blur copy cut paste'.split(' '),
function(name) {
var directiveName = directiveNormalize('ng-' + name);
ngEventDirectives[directiveName] = ['$parse', function($parse) {
return {
compile: function($element, attr) {
var fn = $parse(attr[directiveName]);
return function(scope, element, attr) {
element.on(lowercase(name), function(event) {
scope.$apply(function() {
fn(scope, {$event:event});
});
});
};
}
};
}];
}
);
/**
* @ngdoc directive
* @name ng.directive:ngDblclick
*
* @description
* The `ngDblclick` directive allows you to specify custom behavior on a dblclick event.
*
* @element ANY
* @param {expression} ngDblclick {@link guide/expression Expression} to evaluate upon
* a dblclick. (The Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMousedown
*
* @description
* The ngMousedown directive allows you to specify custom behavior on mousedown event.
*
* @element ANY
* @param {expression} ngMousedown {@link guide/expression Expression} to evaluate upon
* mousedown. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMouseup
*
* @description
* Specify custom behavior on mouseup event.
*
* @element ANY
* @param {expression} ngMouseup {@link guide/expression Expression} to evaluate upon
* mouseup. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMouseover
*
* @description
* Specify custom behavior on mouseover event.
*
* @element ANY
* @param {expression} ngMouseover {@link guide/expression Expression} to evaluate upon
* mouseover. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMouseenter
*
* @description
* Specify custom behavior on mouseenter event.
*
* @element ANY
* @param {expression} ngMouseenter {@link guide/expression Expression} to evaluate upon
* mouseenter. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMouseleave
*
* @description
* Specify custom behavior on mouseleave event.
*
* @element ANY
* @param {expression} ngMouseleave {@link guide/expression Expression} to evaluate upon
* mouseleave. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngMousemove
*
* @description
* Specify custom behavior on mousemove event.
*
* @element ANY
* @param {expression} ngMousemove {@link guide/expression Expression} to evaluate upon
* mousemove. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngKeydown
*
* @description
* Specify custom behavior on keydown event.
*
* @element ANY
* @param {expression} ngKeydown {@link guide/expression Expression} to evaluate upon
* keydown. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngKeyup
*
* @description
* Specify custom behavior on keyup event.
*
* @element ANY
* @param {expression} ngKeyup {@link guide/expression Expression} to evaluate upon
* keyup. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngKeypress
*
* @description
* Specify custom behavior on keypress event.
*
* @element ANY
* @param {expression} ngKeypress {@link guide/expression Expression} to evaluate upon
* keypress. (Event object is available as `$event` and can be interrogated for keyCode, altKey, etc.)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngSubmit
*
* @description
* Enables binding angular expressions to onsubmit events.
*
* Additionally it prevents the default action (which for form means sending the request to the
* server and reloading the current page) **but only if the form does not contain an `action`
* attribute**.
*
* @element form
* @param {expression} ngSubmit {@link guide/expression Expression} to eval. (Event object is available as `$event`)
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.list = [];
$scope.text = 'hello';
$scope.submit = function() {
if (this.text) {
this.list.push(this.text);
this.text = '';
}
};
}
</script>
<form ng-submit="submit()" ng-controller="Ctrl">
Enter text and hit enter:
<input type="text" ng-model="text" name="text" />
<input type="submit" id="submit" value="Submit" />
<pre>list={{list}}</pre>
</form>
</doc:source>
<doc:scenario>
it('should check ng-submit', function() {
expect(binding('list')).toBe('[]');
element('.doc-example-live #submit').click();
expect(binding('list')).toBe('["hello"]');
expect(input('text').val()).toBe('');
});
it('should ignore empty strings', function() {
expect(binding('list')).toBe('[]');
element('.doc-example-live #submit').click();
element('.doc-example-live #submit').click();
expect(binding('list')).toBe('["hello"]');
});
</doc:scenario>
</doc:example>
*/
/**
* @ngdoc directive
* @name ng.directive:ngFocus
*
* @description
* Specify custom behavior on focus event.
*
* @element window, input, select, textarea, a
* @param {expression} ngFocus {@link guide/expression Expression} to evaluate upon
* focus. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngBlur
*
* @description
* Specify custom behavior on blur event.
*
* @element window, input, select, textarea, a
* @param {expression} ngBlur {@link guide/expression Expression} to evaluate upon
* blur. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngCopy
*
* @description
* Specify custom behavior on copy event.
*
* @element window, input, select, textarea, a
* @param {expression} ngCopy {@link guide/expression Expression} to evaluate upon
* copy. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngCut
*
* @description
* Specify custom behavior on cut event.
*
* @element window, input, select, textarea, a
* @param {expression} ngCut {@link guide/expression Expression} to evaluate upon
* cut. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngPaste
*
* @description
* Specify custom behavior on paste event.
*
* @element window, input, select, textarea, a
* @param {expression} ngPaste {@link guide/expression Expression} to evaluate upon
* paste. (Event object is available as `$event`)
*
* @example
* See {@link ng.directive:ngClick ngClick}
*/
/**
* @ngdoc directive
* @name ng.directive:ngIf
* @restrict A
*
* @description
* The `ngIf` directive removes or recreates a portion of the DOM tree based on an
* {expression}. If the expression assigned to `ngIf` evaluates to a false
* value then the element is removed from the DOM, otherwise a clone of the
* element is reinserted into the DOM.
*
* `ngIf` differs from `ngShow` and `ngHide` in that `ngIf` completely removes and recreates the
* element in the DOM rather than changing its visibility via the `display` css property. A common
* case when this difference is significant is when using css selectors that rely on an element's
* position within the DOM, such as the `:first-child` or `:last-child` pseudo-classes.
*
* Note that when an element is removed using `ngIf` its scope is destroyed and a new scope
* is created when the element is restored. The scope created within `ngIf` inherits from
* its parent scope using
* {@link https://github.com/angular/angular.js/wiki/The-Nuances-of-Scope-Prototypal-Inheritance prototypal inheritance}.
* An important implication of this is if `ngModel` is used within `ngIf` to bind to
* a javascript primitive defined in the parent scope. In this case any modifications made to the
* variable within the child scope will override (hide) the value in the parent scope.
*
* Also, `ngIf` recreates elements using their compiled state. An example of this behavior
* is if an element's class attribute is directly modified after it's compiled, using something like
* jQuery's `.addClass()` method, and the element is later removed. When `ngIf` recreates the element
* the added class will be lost because the original compiled state is used to regenerate the element.
*
* Additionally, you can provide animations via the `ngAnimate` module to animate the `enter`
* and `leave` effects.
*
* @animations
* enter - happens just after the ngIf contents change and a new DOM element is created and injected into the ngIf container
* leave - happens just before the ngIf contents are removed from the DOM
*
* @element ANY
* @scope
* @priority 600
* @param {expression} ngIf If the {@link guide/expression expression} is falsy then
* the element is removed from the DOM tree. If it is truthy a copy of the compiled
* element is added to the DOM tree.
*
* @example
<example animations="true">
<file name="index.html">
Click me: <input type="checkbox" ng-model="checked" ng-init="checked=true" /><br/>
Show when checked:
<span ng-if="checked" class="animate-if">
I'm removed when the checkbox is unchecked.
</span>
</file>
<file name="animations.css">
.animate-if {
background:white;
border:1px solid black;
padding:10px;
}
/*
The transition styles can also be placed on the CSS base class above
*/
.animate-if.ng-enter, .animate-if.ng-leave {
-webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
}
.animate-if.ng-enter,
.animate-if.ng-leave.ng-leave-active {
opacity:0;
}
.animate-if.ng-leave,
.animate-if.ng-enter.ng-enter-active {
opacity:1;
}
</file>
</example>
*/
var ngIfDirective = ['$animate', function($animate) {
return {
transclude: 'element',
priority: 600,
terminal: true,
restrict: 'A',
$$tlb: true,
compile: function (element, attr, transclude) {
return function ($scope, $element, $attr) {
var block, childScope;
$scope.$watch($attr.ngIf, function ngIfWatchAction(value) {
if (toBoolean(value)) {
childScope = $scope.$new();
transclude(childScope, function (clone) {
block = {
startNode: clone[0],
endNode: clone[clone.length++] = document.createComment(' end ngIf: ' + $attr.ngIf + ' ')
};
$animate.enter(clone, $element.parent(), $element);
});
} else {
if (childScope) {
childScope.$destroy();
childScope = null;
}
if (block) {
$animate.leave(getBlockElements(block));
block = null;
}
}
});
};
}
};
}];
/**
* @ngdoc directive
* @name ng.directive:ngInclude
* @restrict ECA
*
* @description
* Fetches, compiles and includes an external HTML fragment.
*
* By default, the template URL is restricted to the same domain and protocol as the
* application document. This is done by calling {@link ng.$sce#methods_getTrustedResourceUrl
* $sce.getTrustedResourceUrl} on it. To load templates from other domains or protocols
* you may either {@link ng.$sceDelegateProvider#methods_resourceUrlWhitelist whitelist them} or
* {@link ng.$sce#methods_trustAsResourceUrl wrap them} as trusted values. Refer to Angular's {@link
* ng.$sce Strict Contextual Escaping}.
*
* In addition, the browser's
* {@link https://code.google.com/p/browsersec/wiki/Part2#Same-origin_policy_for_XMLHttpRequest
* Same Origin Policy} and {@link http://www.w3.org/TR/cors/ Cross-Origin Resource Sharing
* (CORS)} policy may further restrict whether the template is successfully loaded.
* For example, `ngInclude` won't work for cross-domain requests on all browsers and for `file://`
* access on some browsers.
*
* @animations
* enter - animation is used to bring new content into the browser.
* leave - animation is used to animate existing content away.
*
* The enter and leave animation occur concurrently.
*
* @scope
* @priority 400
*
* @param {string} ngInclude|src angular expression evaluating to URL. If the source is a string constant,
* make sure you wrap it in quotes, e.g. `src="'myPartialTemplate.html'"`.
* @param {string=} onload Expression to evaluate when a new partial is loaded.
*
* @param {string=} autoscroll Whether `ngInclude` should call {@link ng.$anchorScroll
* $anchorScroll} to scroll the viewport after the content is loaded.
*
* - If the attribute is not set, disable scrolling.
* - If the attribute is set without value, enable scrolling.
* - Otherwise enable scrolling only if the expression evaluates to truthy value.
*
* @example
<example animations="true">
<file name="index.html">
<div ng-controller="Ctrl">
<select ng-model="template" ng-options="t.name for t in templates">
<option value="">(blank)</option>
</select>
url of the template: <tt>{{template.url}}</tt>
<hr/>
<div class="slide-animate-container">
<div class="slide-animate" ng-include="template.url"></div>
</div>
</div>
</file>
<file name="script.js">
function Ctrl($scope) {
$scope.templates =
[ { name: 'template1.html', url: 'template1.html'}
, { name: 'template2.html', url: 'template2.html'} ];
$scope.template = $scope.templates[0];
}
</file>
<file name="template1.html">
Content of template1.html
</file>
<file name="template2.html">
Content of template2.html
</file>
<file name="animations.css">
.slide-animate-container {
position:relative;
background:white;
border:1px solid black;
height:40px;
overflow:hidden;
}
.slide-animate {
padding:10px;
}
.slide-animate.ng-enter, .slide-animate.ng-leave {
-webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
position:absolute;
top:0;
left:0;
right:0;
bottom:0;
display:block;
padding:10px;
}
.slide-animate.ng-enter {
top:-50px;
}
.slide-animate.ng-enter.ng-enter-active {
top:0;
}
.slide-animate.ng-leave {
top:0;
}
.slide-animate.ng-leave.ng-leave-active {
top:50px;
}
</file>
<file name="scenario.js">
it('should load template1.html', function() {
expect(element('.doc-example-live [ng-include]').text()).
toMatch(/Content of template1.html/);
});
it('should load template2.html', function() {
select('template').option('1');
expect(element('.doc-example-live [ng-include]').text()).
toMatch(/Content of template2.html/);
});
it('should change to blank', function() {
select('template').option('');
expect(element('.doc-example-live [ng-include]')).toBe(undefined);
});
</file>
</example>
*/
/**
* @ngdoc event
* @name ng.directive:ngInclude#$includeContentRequested
* @eventOf ng.directive:ngInclude
* @eventType emit on the scope ngInclude was declared in
* @description
* Emitted every time the ngInclude content is requested.
*/
/**
* @ngdoc event
* @name ng.directive:ngInclude#$includeContentLoaded
* @eventOf ng.directive:ngInclude
* @eventType emit on the current ngInclude scope
* @description
* Emitted every time the ngInclude content is reloaded.
*/
var ngIncludeDirective = ['$http', '$templateCache', '$anchorScroll', '$compile', '$animate', '$sce',
function($http, $templateCache, $anchorScroll, $compile, $animate, $sce) {
return {
restrict: 'ECA',
priority: 400,
terminal: true,
transclude: 'element',
compile: function(element, attr, transclusion) {
var srcExp = attr.ngInclude || attr.src,
onloadExp = attr.onload || '',
autoScrollExp = attr.autoscroll;
return function(scope, $element) {
var changeCounter = 0,
currentScope,
currentElement;
var cleanupLastIncludeContent = function() {
if (currentScope) {
currentScope.$destroy();
currentScope = null;
}
if(currentElement) {
$animate.leave(currentElement);
currentElement = null;
}
};
scope.$watch($sce.parseAsResourceUrl(srcExp), function ngIncludeWatchAction(src) {
var afterAnimation = function() {
if (isDefined(autoScrollExp) && (!autoScrollExp || scope.$eval(autoScrollExp))) {
$anchorScroll();
}
};
var thisChangeId = ++changeCounter;
if (src) {
$http.get(src, {cache: $templateCache}).success(function(response) {
if (thisChangeId !== changeCounter) return;
var newScope = scope.$new();
transclusion(newScope, function(clone) {
cleanupLastIncludeContent();
currentScope = newScope;
currentElement = clone;
currentElement.html(response);
$animate.enter(currentElement, null, $element, afterAnimation);
$compile(currentElement.contents())(currentScope);
currentScope.$emit('$includeContentLoaded');
scope.$eval(onloadExp);
});
}).error(function() {
if (thisChangeId === changeCounter) cleanupLastIncludeContent();
});
scope.$emit('$includeContentRequested');
} else {
cleanupLastIncludeContent();
}
});
};
}
};
}];
/**
* @ngdoc directive
* @name ng.directive:ngInit
* @restrict AC
*
* @description
* The `ngInit` directive allows you to evaluate an expression in the
* current scope.
*
* <div class="alert alert-error">
* The only appropriate use of `ngInit` for aliasing special properties of
* {@link api/ng.directive:ngRepeat `ngRepeat`}, as seen in the demo below. Besides this case, you
* should use {@link guide/controller controllers} rather than `ngInit`
* to initialize values on a scope.
* </div>
*
* @element ANY
* @param {expression} ngInit {@link guide/expression Expression} to eval.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.list = [['a', 'b'], ['c', 'd']];
}
</script>
<div ng-controller="Ctrl">
<div ng-repeat="innerList in list" ng-init="outerIndex = $index">
<div ng-repeat="value in innerList" ng-init="innerIndex = $index">
<span class="example-init">list[ {{outerIndex}} ][ {{innerIndex}} ] = {{value}};</span>
</div>
</div>
</div>
</doc:source>
<doc:scenario>
it('should alias index positions', function() {
expect(element('.example-init').text())
.toBe('list[ 0 ][ 0 ] = a;' +
'list[ 0 ][ 1 ] = b;' +
'list[ 1 ][ 0 ] = c;' +
'list[ 1 ][ 1 ] = d;');
});
</doc:scenario>
</doc:example>
*/
var ngInitDirective = ngDirective({
compile: function() {
return {
pre: function(scope, element, attrs) {
scope.$eval(attrs.ngInit);
}
};
}
});
/**
* @ngdoc directive
* @name ng.directive:ngNonBindable
* @restrict AC
* @priority 1000
*
* @description
* The `ngNonBindable` directive tells Angular not to compile or bind the contents of the current
* DOM element. This is useful if the element contains what appears to be Angular directives and
* bindings but which should be ignored by Angular. This could be the case if you have a site that
* displays snippets of code, for instance.
*
* @element ANY
*
* @example
* In this example there are two locations where a simple interpolation binding (`{{}}`) is present,
* but the one wrapped in `ngNonBindable` is left alone.
*
* @example
<doc:example>
<doc:source>
<div>Normal: {{1 + 2}}</div>
<div ng-non-bindable>Ignored: {{1 + 2}}</div>
</doc:source>
<doc:scenario>
it('should check ng-non-bindable', function() {
expect(using('.doc-example-live').binding('1 + 2')).toBe('3');
expect(using('.doc-example-live').element('div:last').text()).
toMatch(/1 \+ 2/);
});
</doc:scenario>
</doc:example>
*/
var ngNonBindableDirective = ngDirective({ terminal: true, priority: 1000 });
/**
* @ngdoc directive
* @name ng.directive:ngPluralize
* @restrict EA
*
* @description
* # Overview
* `ngPluralize` is a directive that displays messages according to en-US localization rules.
* These rules are bundled with angular.js, but can be overridden
* (see {@link guide/i18n Angular i18n} dev guide). You configure ngPluralize directive
* by specifying the mappings between
* {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html
* plural categories} and the strings to be displayed.
*
* # Plural categories and explicit number rules
* There are two
* {@link http://unicode.org/repos/cldr-tmp/trunk/diff/supplemental/language_plural_rules.html
* plural categories} in Angular's default en-US locale: "one" and "other".
*
* While a plural category may match many numbers (for example, in en-US locale, "other" can match
* any number that is not 1), an explicit number rule can only match one number. For example, the
* explicit number rule for "3" matches the number 3. There are examples of plural categories
* and explicit number rules throughout the rest of this documentation.
*
* # Configuring ngPluralize
* You configure ngPluralize by providing 2 attributes: `count` and `when`.
* You can also provide an optional attribute, `offset`.
*
* The value of the `count` attribute can be either a string or an {@link guide/expression
* Angular expression}; these are evaluated on the current scope for its bound value.
*
* The `when` attribute specifies the mappings between plural categories and the actual
* string to be displayed. The value of the attribute should be a JSON object.
*
* The following example shows how to configure ngPluralize:
*
* <pre>
* <ng-pluralize count="personCount"
when="{'0': 'Nobody is viewing.',
* 'one': '1 person is viewing.',
* 'other': '{} people are viewing.'}">
* </ng-pluralize>
*</pre>
*
* In the example, `"0: Nobody is viewing."` is an explicit number rule. If you did not
* specify this rule, 0 would be matched to the "other" category and "0 people are viewing"
* would be shown instead of "Nobody is viewing". You can specify an explicit number rule for
* other numbers, for example 12, so that instead of showing "12 people are viewing", you can
* show "a dozen people are viewing".
*
* You can use a set of closed braces(`{}`) as a placeholder for the number that you want substituted
* into pluralized strings. In the previous example, Angular will replace `{}` with
* <span ng-non-bindable>`{{personCount}}`</span>. The closed braces `{}` is a placeholder
* for <span ng-non-bindable>{{numberExpression}}</span>.
*
* # Configuring ngPluralize with offset
* The `offset` attribute allows further customization of pluralized text, which can result in
* a better user experience. For example, instead of the message "4 people are viewing this document",
* you might display "John, Kate and 2 others are viewing this document".
* The offset attribute allows you to offset a number by any desired value.
* Let's take a look at an example:
*
* <pre>
* <ng-pluralize count="personCount" offset=2
* when="{'0': 'Nobody is viewing.',
* '1': '{{person1}} is viewing.',
* '2': '{{person1}} and {{person2}} are viewing.',
* 'one': '{{person1}}, {{person2}} and one other person are viewing.',
* 'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
* </ng-pluralize>
* </pre>
*
* Notice that we are still using two plural categories(one, other), but we added
* three explicit number rules 0, 1 and 2.
* When one person, perhaps John, views the document, "John is viewing" will be shown.
* When three people view the document, no explicit number rule is found, so
* an offset of 2 is taken off 3, and Angular uses 1 to decide the plural category.
* In this case, plural category 'one' is matched and "John, Marry and one other person are viewing"
* is shown.
*
* Note that when you specify offsets, you must provide explicit number rules for
* numbers from 0 up to and including the offset. If you use an offset of 3, for example,
* you must provide explicit number rules for 0, 1, 2 and 3. You must also provide plural strings for
* plural categories "one" and "other".
*
* @param {string|expression} count The variable to be bounded to.
* @param {string} when The mapping between plural category to its corresponding strings.
* @param {number=} offset Offset to deduct from the total number.
*
* @example
<doc:example>
<doc:source>
<script>
function Ctrl($scope) {
$scope.person1 = 'Igor';
$scope.person2 = 'Misko';
$scope.personCount = 1;
}
</script>
<div ng-controller="Ctrl">
Person 1:<input type="text" ng-model="person1" value="Igor" /><br/>
Person 2:<input type="text" ng-model="person2" value="Misko" /><br/>
Number of People:<input type="text" ng-model="personCount" value="1" /><br/>
<!--- Example with simple pluralization rules for en locale --->
Without Offset:
<ng-pluralize count="personCount"
when="{'0': 'Nobody is viewing.',
'one': '1 person is viewing.',
'other': '{} people are viewing.'}">
</ng-pluralize><br>
<!--- Example with offset --->
With Offset(2):
<ng-pluralize count="personCount" offset=2
when="{'0': 'Nobody is viewing.',
'1': '{{person1}} is viewing.',
'2': '{{person1}} and {{person2}} are viewing.',
'one': '{{person1}}, {{person2}} and one other person are viewing.',
'other': '{{person1}}, {{person2}} and {} other people are viewing.'}">
</ng-pluralize>
</div>
</doc:source>
<doc:scenario>
it('should show correct pluralized string', function() {
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('1 person is viewing.');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Igor is viewing.');
using('.doc-example-live').input('personCount').enter('0');
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('Nobody is viewing.');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Nobody is viewing.');
using('.doc-example-live').input('personCount').enter('2');
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('2 people are viewing.');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Igor and Misko are viewing.');
using('.doc-example-live').input('personCount').enter('3');
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('3 people are viewing.');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Igor, Misko and one other person are viewing.');
using('.doc-example-live').input('personCount').enter('4');
expect(element('.doc-example-live ng-pluralize:first').text()).
toBe('4 people are viewing.');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Igor, Misko and 2 other people are viewing.');
});
it('should show data-binded names', function() {
using('.doc-example-live').input('personCount').enter('4');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Igor, Misko and 2 other people are viewing.');
using('.doc-example-live').input('person1').enter('Di');
using('.doc-example-live').input('person2').enter('Vojta');
expect(element('.doc-example-live ng-pluralize:last').text()).
toBe('Di, Vojta and 2 other people are viewing.');
});
</doc:scenario>
</doc:example>
*/
var ngPluralizeDirective = ['$locale', '$interpolate', function($locale, $interpolate) {
var BRACE = /{}/g;
return {
restrict: 'EA',
link: function(scope, element, attr) {
var numberExp = attr.count,
whenExp = attr.$attr.when && element.attr(attr.$attr.when), // we have {{}} in attrs
offset = attr.offset || 0,
whens = scope.$eval(whenExp) || {},
whensExpFns = {},
startSymbol = $interpolate.startSymbol(),
endSymbol = $interpolate.endSymbol(),
isWhen = /^when(Minus)?(.+)$/;
forEach(attr, function(expression, attributeName) {
if (isWhen.test(attributeName)) {
whens[lowercase(attributeName.replace('when', '').replace('Minus', '-'))] =
element.attr(attr.$attr[attributeName]);
}
});
forEach(whens, function(expression, key) {
whensExpFns[key] =
$interpolate(expression.replace(BRACE, startSymbol + numberExp + '-' +
offset + endSymbol));
});
scope.$watch(function ngPluralizeWatch() {
var value = parseFloat(scope.$eval(numberExp));
if (!isNaN(value)) {
//if explicit number rule such as 1, 2, 3... is defined, just use it. Otherwise,
//check it against pluralization rules in $locale service
if (!(value in whens)) value = $locale.pluralCat(value - offset);
return whensExpFns[value](scope, element, true);
} else {
return '';
}
}, function ngPluralizeWatchAction(newVal) {
element.text(newVal);
});
}
};
}];
/**
* @ngdoc directive
* @name ng.directive:ngRepeat
*
* @description
* The `ngRepeat` directive instantiates a template once per item from a collection. Each template
* instance gets its own scope, where the given loop variable is set to the current collection item,
* and `$index` is set to the item index or key.
*
* Special properties are exposed on the local scope of each template instance, including:
*
* | Variable | Type | Details |
* |-----------|-----------------|-----------------------------------------------------------------------------|
* | `$index` | {@type number} | iterator offset of the repeated element (0..length-1) |
* | `$first` | {@type boolean} | true if the repeated element is first in the iterator. |
* | `$middle` | {@type boolean} | true if the repeated element is between the first and last in the iterator. |
* | `$last` | {@type boolean} | true if the repeated element is last in the iterator. |
* | `$even` | {@type boolean} | true if the iterator position `$index` is even (otherwise false). |
* | `$odd` | {@type boolean} | true if the iterator position `$index` is odd (otherwise false). |
*
*
* # Special repeat start and end points
* To repeat a series of elements instead of just one parent element, ngRepeat (as well as other ng directives) supports extending
* the range of the repeater by defining explicit start and end points by using **ng-repeat-start** and **ng-repeat-end** respectively.
* The **ng-repeat-start** directive works the same as **ng-repeat**, but will repeat all the HTML code (including the tag it's defined on)
* up to and including the ending HTML tag where **ng-repeat-end** is placed.
*
* The example below makes use of this feature:
* <pre>
* <header ng-repeat-start="item in items">
* Header {{ item }}
* </header>
* <div class="body">
* Body {{ item }}
* </div>
* <footer ng-repeat-end>
* Footer {{ item }}
* </footer>
* </pre>
*
* And with an input of {@type ['A','B']} for the items variable in the example above, the output will evaluate to:
* <pre>
* <header>
* Header A
* </header>
* <div class="body">
* Body A
* </div>
* <footer>
* Footer A
* </footer>
* <header>
* Header B
* </header>
* <div class="body">
* Body B
* </div>
* <footer>
* Footer B
* </footer>
* </pre>
*
* The custom start and end points for ngRepeat also support all other HTML directive syntax flavors provided in AngularJS (such
* as **data-ng-repeat-start**, **x-ng-repeat-start** and **ng:repeat-start**).
*
* @animations
* enter - when a new item is added to the list or when an item is revealed after a filter
* leave - when an item is removed from the list or when an item is filtered out
* move - when an adjacent item is filtered out causing a reorder or when the item contents are reordered
*
* @element ANY
* @scope
* @priority 1000
* @param {repeat_expression} ngRepeat The expression indicating how to enumerate a collection. These
* formats are currently supported:
*
* * `variable in expression` – where variable is the user defined loop variable and `expression`
* is a scope expression giving the collection to enumerate.
*
* For example: `album in artist.albums`.
*
* * `(key, value) in expression` – where `key` and `value` can be any user defined identifiers,
* and `expression` is the scope expression giving the collection to enumerate.
*
* For example: `(name, age) in {'adam':10, 'amalie':12}`.
*
* * `variable in expression track by tracking_expression` – You can also provide an optional tracking function
* which can be used to associate the objects in the collection with the DOM elements. If no tracking function
* is specified the ng-repeat associates elements by identity in the collection. It is an error to have
* more than one tracking function to resolve to the same key. (This would mean that two distinct objects are
* mapped to the same DOM element, which is not possible.) Filters should be applied to the expression,
* before specifying a tracking expression.
*
* For example: `item in items` is equivalent to `item in items track by $id(item)'. This implies that the DOM elements
* will be associated by item identity in the array.
*
* For example: `item in items track by $id(item)`. A built in `$id()` function can be used to assign a unique
* `$$hashKey` property to each item in the array. This property is then used as a key to associated DOM elements
* with the corresponding item in the array by identity. Moving the same object in array would move the DOM
* element in the same way ian the DOM.
*
* For example: `item in items track by item.id` is a typical pattern when the items come from the database. In this
* case the object identity does not matter. Two objects are considered equivalent as long as their `id`
* property is same.
*
* For example: `item in items | filter:searchText track by item.id` is a pattern that might be used to apply a filter
* to items in conjunction with a tracking expression.
*
* @example
* This example initializes the scope to a list of names and
* then uses `ngRepeat` to display every person:
<example animations="true">
<file name="index.html">
<div ng-init="friends = [
{name:'John', age:25, gender:'boy'},
{name:'Jessie', age:30, gender:'girl'},
{name:'Johanna', age:28, gender:'girl'},
{name:'Joy', age:15, gender:'girl'},
{name:'Mary', age:28, gender:'girl'},
{name:'Peter', age:95, gender:'boy'},
{name:'Sebastian', age:50, gender:'boy'},
{name:'Erika', age:27, gender:'girl'},
{name:'Patrick', age:40, gender:'boy'},
{name:'Samantha', age:60, gender:'girl'}
]">
I have {{friends.length}} friends. They are:
<input type="search" ng-model="q" placeholder="filter friends..." />
<ul class="example-animate-container">
<li class="animate-repeat" ng-repeat="friend in friends | filter:q">
[{{$index + 1}}] {{friend.name}} who is {{friend.age}} years old.
</li>
</ul>
</div>
</file>
<file name="animations.css">
.example-animate-container {
background:white;
border:1px solid black;
list-style:none;
margin:0;
padding:0 10px;
}
.animate-repeat {
line-height:40px;
list-style:none;
box-sizing:border-box;
}
.animate-repeat.ng-move,
.animate-repeat.ng-enter,
.animate-repeat.ng-leave {
-webkit-transition:all linear 0.5s;
transition:all linear 0.5s;
}
.animate-repeat.ng-leave.ng-leave-active,
.animate-repeat.ng-move,
.animate-repeat.ng-enter {
opacity:0;
max-height:0;
}
.animate-repeat.ng-leave,
.animate-repeat.ng-move.ng-move-active,
.animate-repeat.ng-enter.ng-enter-active {
opacity:1;
max-height:40px;
}
</file>
<file name="scenario.js">
it('should render initial data set', function() {
var r = using('.doc-example-live').repeater('ul li');
expect(r.count()).toBe(10);
expect(r.row(0)).toEqual(["1","John","25"]);
expect(r.row(1)).toEqual(["2","Jessie","30"]);
expect(r.row(9)).toEqual(["10","Samantha","60"]);
expect(binding('friends.length')).toBe("10");
});
it('should update repeater when filter predicate changes', function() {
var r = using('.doc-example-live').repeater('ul li');
expect(r.count()).toBe(10);
input('q').enter('ma');
expect(r.count()).toBe(2);
expect(r.row(0)).toEqual(["1","Mary","28"]);
expect(r.row(1)).toEqual(["2","Samantha","60"]);
});
</file>
</example>
*/
var ngRepeatDirective = ['$parse', '$animate', function($parse, $animate) {
var NG_REMOVED = '$$NG_REMOVED';
var ngRepeatMinErr = minErr('ngRepeat');
return {
transclude: 'element',
priority: 1000,
terminal: true,
$$tlb: true,
compile: function(element, attr, linker) {
return function($scope, $element, $attr){
var expression = $attr.ngRepeat;
var match = expression.match(/^\s*(.+)\s+in\s+(.*?)\s*(\s+track\s+by\s+(.+)\s*)?$/),
trackByExp, trackByExpGetter, trackByIdExpFn, trackByIdArrayFn, trackByIdObjFn,
lhs, rhs, valueIdentifier, keyIdentifier,
hashFnLocals = {$id: hashKey};
if (!match) {
throw ngRepeatMinErr('iexp', "Expected expression in form of '_item_ in _collection_[ track by _id_]' but got '{0}'.",
expression);
}
lhs = match[1];
rhs = match[2];
trackByExp = match[4];
if (trackByExp) {
trackByExpGetter = $parse(trackByExp);
trackByIdExpFn = function(key, value, index) {
// assign key, value, and $index to the locals so that they can be used in hash functions
if (keyIdentifier) hashFnLocals[keyIdentifier] = key;
hashFnLocals[valueIdentifier] = value;
hashFnLocals.$index = index;
return trackByExpGetter($scope, hashFnLocals);
};
} else {
trackByIdArrayFn = function(key, value) {
return hashKey(value);
};
trackByIdObjFn = function(key) {
return key;
};
}
match = lhs.match(/^(?:([\$\w]+)|\(([\$\w]+)\s*,\s*([\$\w]+)\))$/);
if (!match) {
throw ngRepeatMinErr('iidexp', "'_item_' in '_item_ in _collection_' should be an identifier or '(_key_, _value_)' expression, but got '{0}'.",
lhs);
}
valueIdentifier = match[3] || match[1];
keyIdentifier = match[2];
// Store a list of elements from previous run. This is a hash where key is the item from the
// iterator, and the value is objects with following properties.
// - scope: bound scope
// - element: previous element.
// - index: position
var lastBlockMap = {};
//watch props
$scope.$watchCollection(rhs, function ngRepeatAction(collection){
var index, length,
previousNode = $element[0], // current position of the node
nextNode,
// Same as lastBlockMap but it has the current state. It will become the
// lastBlockMap on the next iteration.
nextBlockMap = {},
arrayLength,
childScope,
key, value, // key/value of iteration
trackById,
trackByIdFn,
collectionKeys,
block, // last object information {scope, element, id}
nextBlockOrder = [],
elementsToRemove;
if (isArrayLike(collection)) {
collectionKeys = collection;
trackByIdFn = trackByIdExpFn || trackByIdArrayFn;
} else {
trackByIdFn = trackByIdExpFn || trackByIdObjFn;
// if object, extract keys, sort them and use to determine order of iteration over obj props
collectionKeys = [];
for (key in collection) {
if (collection.hasOwnProperty(key) && key.charAt(0) != '$') {
collectionKeys.push(key);
}
}
collectionKeys.sort();
}
arrayLength = collectionKeys.length;
// locate existing items
length = nextBlockOrder.length = collectionKeys.length;
for(index = 0; index < length; index++) {
key = (collection === collectionKeys) ? index : collectionKeys[index];
value = collection[key];
trackById = trackByIdFn(key, value, index);
assertNotHasOwnProperty(trackById, '`track by` id');
if(lastBlockMap.hasOwnProperty(trackById)) {
block = lastBlockMap[trackById];
delete lastBlockMap[trackById];
nextBlockMap[trackById] = block;
nextBlockOrder[index] = block;
} else if (nextBlockMap.hasOwnProperty(trackById)) {
// restore lastBlockMap
forEach(nextBlockOrder, function(block) {
if (block && block.startNode) lastBlockMap[block.id] = block;
});
// This is a duplicate and we need to throw an error
throw ngRepeatMinErr('dupes', "Duplicates in a repeater are not allowed. Use 'track by' expression to specify unique keys. Repeater: {0}, Duplicate key: {1}",
expression, trackById);
} else {
// new never before seen block
nextBlockOrder[index] = { id: trackById };
nextBlockMap[trackById] = false;
}
}
// remove existing items
for (key in lastBlockMap) {
// lastBlockMap is our own object so we don't need to use special hasOwnPropertyFn
if (lastBlockMap.hasOwnProperty(key)) {
block = lastBlockMap[key];
elementsToRemove = getBlockElements(block);
$animate.leave(elementsToRemove);
forEach(elementsToRemove, function(element) { element[NG_REMOVED] = true; });
block.scope.$destroy();
}
}
// we are not using forEach for perf reasons (trying to avoid #call)
for (index = 0, length = collectionKeys.length; index < length; index++) {
key = (collection === collectionKeys) ? index : collectionKeys[index];
value = collection[key];
block = nextBlockOrder[index];
if (nextBlockOrder[index - 1]) previousNode = nextBlockOrder[index - 1].endNode;
if (block.startNode) {
// if we have already seen this object, then we need to reuse the
// associated scope/element
childScope = block.scope;
nextNode = previousNode;
do {
nextNode = nextNode.nextSibling;
} while(nextNode && nextNode[NG_REMOVED]);
if (block.startNode != nextNode) {
// existing item which got moved
$animate.move(getBlockElements(block), null, jqLite(previousNode));
}
previousNode = block.endNode;
} else {
// new item which we don't know about
childScope = $scope.$new();
}
childScope[valueIdentifier] = value;
if (keyIdentifier) childScope[keyIdentifier] = key;
childScope.$index = index;
childScope.$first = (index === 0);
childScope.$last = (index === (arrayLength - 1));
childScope.$middle = !(childScope.$first || childScope.$last);
// jshint bitwise: false
childScope.$odd = !(childScope.$even = (index&1) === 0);
// jshint bitwise: true
if (!block.startNode) {
linker(childScope, function(clone) {
clone[clone.length++] = document.createComment(' end ngRepeat: ' + expression + ' ');
$animate.enter(clone, null, jqLite(previousNode));
previousNode = clone;
block.scope = childScope;
block.startNode = previousNode && previousNode.endNode ? previousNode.endNode : clone[0];
block.endNode = clone[clone.length - 1];
nextBlockMap[block.id] = block;
});
}
}
lastBlockMap = nextBlockMap;
});
};
}
};
}];
/**
* @ngdoc directive
* @name ng.directive:ngShow
*
* @description
* The `ngShow` directive shows or hides the given HTML element based on the expression
* provided to the ngShow attribute. The element is shown or hidden by removing or adding
* the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
* in AngularJS and sets the display style to none (using an !important flag).
* For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
*
* <pre>
* <!-- when $scope.myValue is truthy (element is visible) -->
* <div ng-show="myValue"></div>
*
* <!-- when $scope.myValue is falsy (element is hidden) -->
* <div ng-show="myValue" class="ng-hide"></div>
* </pre>
*
* When the ngShow expression evaluates to false then the ng-hide CSS class is added to the class attribute
* on the element causing it to become hidden. When true, the ng-hide CSS class is removed
* from the element causing the element not to appear hidden.
*
* ## Why is !important used?
*
* You may be wondering why !important is used for the .ng-hide CSS class. This is because the `.ng-hide` selector
* can be easily overridden by heavier selectors. For example, something as simple
* as changing the display style on a HTML list item would make hidden elements appear visible.
* This also becomes a bigger issue when dealing with CSS frameworks.
*
* By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
* specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
* styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
*
* ### Overriding .ng-hide
*
* If you wish to change the hide behavior with ngShow/ngHide then this can be achieved by
* restating the styles for the .ng-hide class in CSS:
* <pre>
* .ng-hide {
* //!annotate CSS Specificity|Not to worry, this will override the AngularJS default...
* display:block!important;
*
* //this is just another form of hiding an element
* position:absolute;
* top:-9999px;
* left:-9999px;
* }
* </pre>
*
* Just remember to include the important flag so the CSS override will function.
*
* ## A note about animations with ngShow
*
* Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
* is true and false. This system works like the animation system present with ngClass except that
* you must also include the !important flag to override the display property
* so that you can perform an animation when the element is hidden during the time of the animation.
*
* <pre>
* //
* //a working example can be found at the bottom of this page
* //
* .my-element.ng-hide-add, .my-element.ng-hide-remove {
* transition:0.5s linear all;
* display:block!important;
* }
*
* .my-element.ng-hide-add { ... }
* .my-element.ng-hide-add.ng-hide-add-active { ... }
* .my-element.ng-hide-remove { ... }
* .my-element.ng-hide-remove.ng-hide-remove-active { ... }
* </pre>
*
* @animations
* addClass: .ng-hide - happens after the ngShow expression evaluates to a truthy value and the just before contents are set to visible
* removeClass: .ng-hide - happens after the ngShow expression evaluates to a non truthy value and just before the contents are set to hidden
*
* @element ANY
* @param {expression} ngShow If the {@link guide/expression expression} is truthy
* then the element is shown or hidden respectively.
*
* @example
<example animations="true">
<file name="index.html">
Click me: <input type="checkbox" ng-model="checked"><br/>
<div>
Show:
<div class="check-element animate-show" ng-show="checked">
<span class="icon-thumbs-up"></span> I show up when your checkbox is checked.
</div>
</div>
<div>
Hide:
<div class="check-element animate-show" ng-hide="checked">
<span class="icon-thumbs-down"></span> I hide when your checkbox is checked.
</div>
</div>
</file>
<file name="animations.css">
.animate-show {
-webkit-transition:all linear 0.5s;
transition:all linear 0.5s;
line-height:20px;
opacity:1;
padding:10px;
border:1px solid black;
background:white;
}
.animate-show.ng-hide-add,
.animate-show.ng-hide-remove {
display:block!important;
}
.animate-show.ng-hide {
line-height:0;
opacity:0;
padding:0 10px;
}
.check-element {
padding:10px;
border:1px solid black;
background:white;
}
</file>
<file name="scenario.js">
it('should check ng-show / ng-hide', function() {
expect(element('.doc-example-live span:first:hidden').count()).toEqual(1);
expect(element('.doc-example-live span:last:visible').count()).toEqual(1);
input('checked').check();
expect(element('.doc-example-live span:first:visible').count()).toEqual(1);
expect(element('.doc-example-live span:last:hidden').count()).toEqual(1);
});
</file>
</example>
*/
var ngShowDirective = ['$animate', function($animate) {
return function(scope, element, attr) {
scope.$watch(attr.ngShow, function ngShowWatchAction(value){
$animate[toBoolean(value) ? 'removeClass' : 'addClass'](element, 'ng-hide');
});
};
}];
/**
* @ngdoc directive
* @name ng.directive:ngHide
*
* @description
* The `ngHide` directive shows or hides the given HTML element based on the expression
* provided to the ngHide attribute. The element is shown or hidden by removing or adding
* the `ng-hide` CSS class onto the element. The `.ng-hide` CSS class is predefined
* in AngularJS and sets the display style to none (using an !important flag).
* For CSP mode please add `angular-csp.css` to your html file (see {@link ng.directive:ngCsp ngCsp}).
*
* <pre>
* <!-- when $scope.myValue is truthy (element is hidden) -->
* <div ng-hide="myValue"></div>
*
* <!-- when $scope.myValue is falsy (element is visible) -->
* <div ng-hide="myValue" class="ng-hide"></div>
* </pre>
*
* When the ngHide expression evaluates to true then the .ng-hide CSS class is added to the class attribute
* on the element causing it to become hidden. When false, the ng-hide CSS class is removed
* from the element causing the element not to appear hidden.
*
* ## Why is !important used?
*
* You may be wondering why !important is used for the .ng-hide CSS class. This is because the `.ng-hide` selector
* can be easily overridden by heavier selectors. For example, something as simple
* as changing the display style on a HTML list item would make hidden elements appear visible.
* This also becomes a bigger issue when dealing with CSS frameworks.
*
* By using !important, the show and hide behavior will work as expected despite any clash between CSS selector
* specificity (when !important isn't used with any conflicting styles). If a developer chooses to override the
* styling to change how to hide an element then it is just a matter of using !important in their own CSS code.
*
* ### Overriding .ng-hide
*
* If you wish to change the hide behavior with ngShow/ngHide then this can be achieved by
* restating the styles for the .ng-hide class in CSS:
* <pre>
* .ng-hide {
* //!annotate CSS Specificity|Not to worry, this will override the AngularJS default...
* display:block!important;
*
* //this is just another form of hiding an element
* position:absolute;
* top:-9999px;
* left:-9999px;
* }
* </pre>
*
* Just remember to include the important flag so the CSS override will function.
*
* ## A note about animations with ngHide
*
* Animations in ngShow/ngHide work with the show and hide events that are triggered when the directive expression
* is true and false. This system works like the animation system present with ngClass, except that
* you must also include the !important flag to override the display property so
* that you can perform an animation when the element is hidden during the time of the animation.
*
* <pre>
* //
* //a working example can be found at the bottom of this page
* //
* .my-element.ng-hide-add, .my-element.ng-hide-remove {
* transition:0.5s linear all;
* display:block!important;
* }
*
* .my-element.ng-hide-add { ... }
* .my-element.ng-hide-add.ng-hide-add-active { ... }
* .my-element.ng-hide-remove { ... }
* .my-element.ng-hide-remove.ng-hide-remove-active { ... }
* </pre>
*
* @animations
* removeClass: .ng-hide - happens after the ngHide expression evaluates to a truthy value and just before the contents are set to hidden
* addClass: .ng-hide - happens after the ngHide expression evaluates to a non truthy value and just before the contents are set to visible
*
* @element ANY
* @param {expression} ngHide If the {@link guide/expression expression} is truthy then
* the element is shown or hidden respectively.
*
* @example
<example animations="true">
<file name="index.html">
Click me: <input type="checkbox" ng-model="checked"><br/>
<div>
Show:
<div class="check-element animate-hide" ng-show="checked">
<span class="icon-thumbs-up"></span> I show up when your checkbox is checked.
</div>
</div>
<div>
Hide:
<div class="check-element animate-hide" ng-hide="checked">
<span class="icon-thumbs-down"></span> I hide when your checkbox is checked.
</div>
</div>
</file>
<file name="animations.css">
.animate-hide {
-webkit-transition:all linear 0.5s;
transition:all linear 0.5s;
line-height:20px;
opacity:1;
padding:10px;
border:1px solid black;
background:white;
}
.animate-hide.ng-hide-add,
.animate-hide.ng-hide-remove {
display:block!important;
}
.animate-hide.ng-hide {
line-height:0;
opacity:0;
padding:0 10px;
}
.check-element {
padding:10px;
border:1px solid black;
background:white;
}
</file>
<file name="scenario.js">
it('should check ng-show / ng-hide', function() {
expect(element('.doc-example-live .check-element:first:hidden').count()).toEqual(1);
expect(element('.doc-example-live .check-element:last:visible').count()).toEqual(1);
input('checked').check();
expect(element('.doc-example-live .check-element:first:visible').count()).toEqual(1);
expect(element('.doc-example-live .check-element:last:hidden').count()).toEqual(1);
});
</file>
</example>
*/
var ngHideDirective = ['$animate', function($animate) {
return function(scope, element, attr) {
scope.$watch(attr.ngHide, function ngHideWatchAction(value){
$animate[toBoolean(value) ? 'addClass' : 'removeClass'](element, 'ng-hide');
});
};
}];
/**
* @ngdoc directive
* @name ng.directive:ngStyle
* @restrict AC
*
* @description
* The `ngStyle` directive allows you to set CSS style on an HTML element conditionally.
*
* @element ANY
* @param {expression} ngStyle {@link guide/expression Expression} which evals to an
* object whose keys are CSS style names and values are corresponding values for those CSS
* keys.
*
* @example
<example>
<file name="index.html">
<input type="button" value="set" ng-click="myStyle={color:'red'}">
<input type="button" value="clear" ng-click="myStyle={}">
<br/>
<span ng-style="myStyle">Sample Text</span>
<pre>myStyle={{myStyle}}</pre>
</file>
<file name="style.css">
span {
color: black;
}
</file>
<file name="scenario.js">
it('should check ng-style', function() {
expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)');
element('.doc-example-live :button[value=set]').click();
expect(element('.doc-example-live span').css('color')).toBe('rgb(255, 0, 0)');
element('.doc-example-live :button[value=clear]').click();
expect(element('.doc-example-live span').css('color')).toBe('rgb(0, 0, 0)');
});
</file>
</example>
*/
var ngStyleDirective = ngDirective(function(scope, element, attr) {
scope.$watch(attr.ngStyle, function ngStyleWatchAction(newStyles, oldStyles) {
if (oldStyles && (newStyles !== oldStyles)) {
forEach(oldStyles, function(val, style) { element.css(style, '');});
}
if (newStyles) element.css(newStyles);
}, true);
});
/**
* @ngdoc directive
* @name ng.directive:ngSwitch
* @restrict EA
*
* @description
* The ngSwitch directive is used to conditionally swap DOM structure on your template based on a scope expression.
* Elements within ngSwitch but without ngSwitchWhen or ngSwitchDefault directives will be preserved at the location
* as specified in the template.
*
* The directive itself works similar to ngInclude, however, instead of downloading template code (or loading it
* from the template cache), ngSwitch simply choses one of the nested elements and makes it visible based on which element
* matches the value obtained from the evaluated expression. In other words, you define a container element
* (where you place the directive), place an expression on the **on="..." attribute**
* (or the **ng-switch="..." attribute**), define any inner elements inside of the directive and place
* a when attribute per element. The when attribute is used to inform ngSwitch which element to display when the on
* expression is evaluated. If a matching expression is not found via a when attribute then an element with the default
* attribute is displayed.
*
* @animations
* enter - happens after the ngSwitch contents change and the matched child element is placed inside the container
* leave - happens just after the ngSwitch contents change and just before the former contents are removed from the DOM
*
* @usage
* <ANY ng-switch="expression">
* <ANY ng-switch-when="matchValue1">...</ANY>
* <ANY ng-switch-when="matchValue2">...</ANY>
* <ANY ng-switch-default>...</ANY>
* </ANY>
*
* @scope
* @priority 800
* @param {*} ngSwitch|on expression to match against <tt>ng-switch-when</tt>.
* @paramDescription
* On child elements add:
*
* * `ngSwitchWhen`: the case statement to match against. If match then this
* case will be displayed. If the same match appears multiple times, all the
* elements will be displayed.
* * `ngSwitchDefault`: the default case when no other case match. If there
* are multiple default cases, all of them will be displayed when no other
* case match.
*
*
* @example
<example animations="true">
<file name="index.html">
<div ng-controller="Ctrl">
<select ng-model="selection" ng-options="item for item in items">
</select>
<tt>selection={{selection}}</tt>
<hr/>
<div class="animate-switch-container"
ng-switch on="selection">
<div class="animate-switch" ng-switch-when="settings">Settings Div</div>
<div class="animate-switch" ng-switch-when="home">Home Span</div>
<div class="animate-switch" ng-switch-default>default</div>
</div>
</div>
</file>
<file name="script.js">
function Ctrl($scope) {
$scope.items = ['settings', 'home', 'other'];
$scope.selection = $scope.items[0];
}
</file>
<file name="animations.css">
.animate-switch-container {
position:relative;
background:white;
border:1px solid black;
height:40px;
overflow:hidden;
}
.animate-switch {
padding:10px;
}
.animate-switch.ng-animate {
-webkit-transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
transition:all cubic-bezier(0.250, 0.460, 0.450, 0.940) 0.5s;
position:absolute;
top:0;
left:0;
right:0;
bottom:0;
}
.animate-switch.ng-leave.ng-leave-active,
.animate-switch.ng-enter {
top:-50px;
}
.animate-switch.ng-leave,
.animate-switch.ng-enter.ng-enter-active {
top:0;
}
</file>
<file name="scenario.js">
it('should start in settings', function() {
expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Settings Div/);
});
it('should change to home', function() {
select('selection').option('home');
expect(element('.doc-example-live [ng-switch]').text()).toMatch(/Home Span/);
});
it('should select default', function() {
select('selection').option('other');
expect(element('.doc-example-live [ng-switch]').text()).toMatch(/default/);
});
</file>
</example>
*/
var ngSwitchDirective = ['$animate', function($animate) {
return {
restrict: 'EA',
require: 'ngSwitch',
// asks for $scope to fool the BC controller module
controller: ['$scope', function ngSwitchController() {
this.cases = {};
}],
link: function(scope, element, attr, ngSwitchController) {
var watchExpr = attr.ngSwitch || attr.on,
selectedTranscludes,
selectedElements,
selectedScopes = [];
scope.$watch(watchExpr, function ngSwitchWatchAction(value) {
for (var i= 0, ii=selectedScopes.length; i<ii; i++) {
selectedScopes[i].$destroy();
$animate.leave(selectedElements[i]);
}
selectedElements = [];
selectedScopes = [];
if ((selectedTranscludes = ngSwitchController.cases['!' + value] || ngSwitchController.cases['?'])) {
scope.$eval(attr.change);
forEach(selectedTranscludes, function(selectedTransclude) {
var selectedScope = scope.$new();
selectedScopes.push(selectedScope);
selectedTransclude.transclude(selectedScope, function(caseElement) {
var anchor = selectedTransclude.element;
selectedElements.push(caseElement);
$animate.enter(caseElement, anchor.parent(), anchor);
});
});
}
});
}
};
}];
var ngSwitchWhenDirective = ngDirective({
transclude: 'element',
priority: 800,
require: '^ngSwitch',
compile: function(element, attrs, transclude) {
return function(scope, element, attr, ctrl) {
ctrl.cases['!' + attrs.ngSwitchWhen] = (ctrl.cases['!' + attrs.ngSwitchWhen] || []);
ctrl.cases['!' + attrs.ngSwitchWhen].push({ transclude: transclude, element: element });
};
}
});
var ngSwitchDefaultDirective = ngDirective({
transclude: 'element',
priority: 800,
require: '^ngSwitch',
compile: function(element, attrs, transclude) {
return function(scope, element, attr, ctrl) {
ctrl.cases['?'] = (ctrl.cases['?'] || []);
ctrl.cases['?'].push({ transclude: transclude, element: element });
};
}
});
/**
* @ngdoc directive
* @name ng.directive:ngTransclude
* @restrict AC
*
* @description
* Directive that marks the insertion point for the transcluded DOM of the nearest parent directive that uses transclusion.
*
* Any existing content of the element that this directive is placed on will be removed before the transcluded content is inserted.
*
* @element ANY
*
* @example
<doc:example module="transclude">
<doc:source>
<script>
function Ctrl($scope) {
$scope.title = 'Lorem Ipsum';
$scope.text = 'Neque porro quisquam est qui dolorem ipsum quia dolor...';
}
angular.module('transclude', [])
.directive('pane', function(){
return {
restrict: 'E',
transclude: true,
scope: { title:'@' },
template: '<div style="border: 1px solid black;">' +
'<div style="background-color: gray">{{title}}</div>' +
'<div ng-transclude></div>' +
'</div>'
};
});
</script>
<div ng-controller="Ctrl">
<input ng-model="title"><br>
<textarea ng-model="text"></textarea> <br/>
<pane title="{{title}}">{{text}}</pane>
</div>
</doc:source>
<doc:scenario>
it('should have transcluded', function() {
input('title').enter('TITLE');
input('text').enter('TEXT');
expect(binding('title')).toEqual('TITLE');
expect(binding('text')).toEqual('TEXT');
});
</doc:scenario>
</doc:example>
*
*/
var ngTranscludeDirective = ngDirective({
controller: ['$element', '$transclude', function($element, $transclude) {
if (!$transclude) {
throw minErr('ngTransclude')('orphan',
'Illegal use of ngTransclude directive in the template! ' +
'No parent directive that requires a transclusion found. ' +
'Element: {0}',
startingTag($element));
}
// remember the transclusion fn but call it during linking so that we don't process transclusion before directives on
// the parent element even when the transclusion replaces the current element. (we can't use priority here because
// that applies only to compile fns and not controllers
this.$transclude = $transclude;
}],
link: function($scope, $element, $attrs, controller) {
controller.$transclude(function(clone) {
$element.html('');
$element.append(clone);
});
}
});
/**
* @ngdoc directive
* @name ng.directive:script
* @restrict E
*
* @description
* Load content of a script tag, with type `text/ng-template`, into `$templateCache`, so that the
* template can be used by `ngInclude`, `ngView` or directive templates.
*
* @param {'text/ng-template'} type must be set to `'text/ng-template'`
*
* @example
<doc:example>
<doc:source>
<script type="text/ng-template" id="/tpl.html">
Content of the template.
</script>
<a ng-click="currentTpl='/tpl.html'" id="tpl-link">Load inlined template</a>
<div id="tpl-content" ng-include src="currentTpl"></div>
</doc:source>
<doc:scenario>
it('should load template defined inside script tag', function() {
element('#tpl-link').click();
expect(element('#tpl-content').text()).toMatch(/Content of the template/);
});
</doc:scenario>
</doc:example>
*/
var scriptDirective = ['$templateCache', function($templateCache) {
return {
restrict: 'E',
terminal: true,
compile: function(element, attr) {
if (attr.type == 'text/ng-template') {
var templateUrl = attr.id,
// IE is not consistent, in scripts we have to read .text but in other nodes we have to read .textContent
text = element[0].text;
$templateCache.put(templateUrl, text);
}
}
};
}];
var ngOptionsMinErr = minErr('ngOptions');
/**
* @ngdoc directive
* @name ng.directive:select
* @restrict E
*
* @description
* HTML `SELECT` element with angular data-binding.
*
* # `ngOptions`
*
* The `ngOptions` attribute can be used to dynamically generate a list of `<option>`
* elements for the `<select>` element using the array or object obtained by evaluating the
* `ngOptions` comprehension_expression.
*
* When an item in the `<select>` menu is selected, the array element or object property
* represented by the selected option will be bound to the model identified by the `ngModel`
* directive.
*
* Optionally, a single hard-coded `<option>` element, with the value set to an empty string, can
* be nested into the `<select>` element. This element will then represent the `null` or "not selected"
* option. See example below for demonstration.
*
* Note: `ngOptions` provides iterator facility for `<option>` element which should be used instead
* of {@link ng.directive:ngRepeat ngRepeat} when you want the
* `select` model to be bound to a non-string value. This is because an option element can only
* be bound to string values at present.
*
* @param {string} ngModel Assignable angular expression to data-bind to.
* @param {string=} name Property name of the form under which the control is published.
* @param {string=} required The control is considered valid only if value is entered.
* @param {string=} ngRequired Adds `required` attribute and `required` validation constraint to
* the element when the ngRequired expression evaluates to true. Use `ngRequired` instead of
* `required` when you want to data-bind to the `required` attribute.
* @param {comprehension_expression=} ngOptions in one of the following forms:
*
* * for array data sources:
* * `label` **`for`** `value` **`in`** `array`
* * `select` **`as`** `label` **`for`** `value` **`in`** `array`
* * `label` **`group by`** `group` **`for`** `value` **`in`** `array`
* * `select` **`as`** `label` **`group by`** `group` **`for`** `value` **`in`** `array` **`track by`** `trackexpr`
* * for object data sources:
* * `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
* * `select` **`as`** `label` **`for (`**`key` **`,`** `value`**`) in`** `object`
* * `label` **`group by`** `group` **`for (`**`key`**`,`** `value`**`) in`** `object`
* * `select` **`as`** `label` **`group by`** `group`
* **`for` `(`**`key`**`,`** `value`**`) in`** `object`
*
* Where:
*
* * `array` / `object`: an expression which evaluates to an array / object to iterate over.
* * `value`: local variable which will refer to each item in the `array` or each property value
* of `object` during iteration.
* * `key`: local variable which will refer to a property name in `object` during iteration.
* * `label`: The result of this expression will be the label for `<option>` element. The
* `expression` will most likely refer to the `value` variable (e.g. `value.propertyName`).
* * `select`: The result of this expression will be bound to the model of the parent `<select>`
* element. If not specified, `select` expression will default to `value`.
* * `group`: The result of this expression will be used to group options using the `<optgroup>`
* DOM element.
* * `trackexpr`: Used when working with an array of objects. The result of this expression will be
* used to identify the objects in the array. The `trackexpr` will most likely refer to the
* `value` variable (e.g. `value.propertyName`).
*
* @example
<doc:example>
<doc:source>
<script>
function MyCntrl($scope) {
$scope.colors = [
{name:'black', shade:'dark'},
{name:'white', shade:'light'},
{name:'red', shade:'dark'},
{name:'blue', shade:'dark'},
{name:'yellow', shade:'light'}
];
$scope.color = $scope.colors[2]; // red
}
</script>
<div ng-controller="MyCntrl">
<ul>
<li ng-repeat="color in colors">
Name: <input ng-model="color.name">
[<a href ng-click="colors.splice($index, 1)">X</a>]
</li>
<li>
[<a href ng-click="colors.push({})">add</a>]
</li>
</ul>
<hr/>
Color (null not allowed):
<select ng-model="color" ng-options="c.name for c in colors"></select><br>
Color (null allowed):
<span class="nullable">
<select ng-model="color" ng-options="c.name for c in colors">
<option value="">-- choose color --</option>
</select>
</span><br/>
Color grouped by shade:
<select ng-model="color" ng-options="c.name group by c.shade for c in colors">
</select><br/>
Select <a href ng-click="color={name:'not in list'}">bogus</a>.<br>
<hr/>
Currently selected: {{ {selected_color:color} }}
<div style="border:solid 1px black; height:20px"
ng-style="{'background-color':color.name}">
</div>
</div>
</doc:source>
<doc:scenario>
it('should check ng-options', function() {
expect(binding('{selected_color:color}')).toMatch('red');
select('color').option('0');
expect(binding('{selected_color:color}')).toMatch('black');
using('.nullable').select('color').option('');
expect(binding('{selected_color:color}')).toMatch('null');
});
</doc:scenario>
</doc:example>
*/
var ngOptionsDirective = valueFn({ terminal: true });
// jshint maxlen: false
var selectDirective = ['$compile', '$parse', function($compile, $parse) {
//0000111110000000000022220000000000000000000000333300000000000000444444444444444000000000555555555555555000000066666666666666600000000000000007777000000000000000000088888
var NG_OPTIONS_REGEXP = /^\s*(.*?)(?:\s+as\s+(.*?))?(?:\s+group\s+by\s+(.*))?\s+for\s+(?:([\$\w][\$\w]*)|(?:\(\s*([\$\w][\$\w]*)\s*,\s*([\$\w][\$\w]*)\s*\)))\s+in\s+(.*?)(?:\s+track\s+by\s+(.*?))?$/,
nullModelCtrl = {$setViewValue: noop};
// jshint maxlen: 100
return {
restrict: 'E',
require: ['select', '?ngModel'],
controller: ['$element', '$scope', '$attrs', function($element, $scope, $attrs) {
var self = this,
optionsMap = {},
ngModelCtrl = nullModelCtrl,
nullOption,
unknownOption;
self.databound = $attrs.ngModel;
self.init = function(ngModelCtrl_, nullOption_, unknownOption_) {
ngModelCtrl = ngModelCtrl_;
nullOption = nullOption_;
unknownOption = unknownOption_;
};
self.addOption = function(value) {
assertNotHasOwnProperty(value, '"option value"');
optionsMap[value] = true;
if (ngModelCtrl.$viewValue == value) {
$element.val(value);
if (unknownOption.parent()) unknownOption.remove();
}
};
self.removeOption = function(value) {
if (this.hasOption(value)) {
delete optionsMap[value];
if (ngModelCtrl.$viewValue == value) {
this.renderUnknownOption(value);
}
}
};
self.renderUnknownOption = function(val) {
var unknownVal = '? ' + hashKey(val) + ' ?';
unknownOption.val(unknownVal);
$element.prepend(unknownOption);
$element.val(unknownVal);
unknownOption.prop('selected', true); // needed for IE
};
self.hasOption = function(value) {
return optionsMap.hasOwnProperty(value);
};
$scope.$on('$destroy', function() {
// disable unknown option so that we don't do work when the whole select is being destroyed
self.renderUnknownOption = noop;
});
}],
link: function(scope, element, attr, ctrls) {
// if ngModel is not defined, we don't need to do anything
if (!ctrls[1]) return;
var selectCtrl = ctrls[0],
ngModelCtrl = ctrls[1],
multiple = attr.multiple,
optionsExp = attr.ngOptions,
nullOption = false, // if false, user will not be able to select it (used by ngOptions)
emptyOption,
// we can't just jqLite('<option>') since jqLite is not smart enough
// to create it in <select> and IE barfs otherwise.
optionTemplate = jqLite(document.createElement('option')),
optGroupTemplate =jqLite(document.createElement('optgroup')),
unknownOption = optionTemplate.clone();
// find "null" option
for(var i = 0, children = element.children(), ii = children.length; i < ii; i++) {
if (children[i].value === '') {
emptyOption = nullOption = children.eq(i);
break;
}
}
selectCtrl.init(ngModelCtrl, nullOption, unknownOption);
// required validator
if (multiple && (attr.required || attr.ngRequired)) {
var requiredValidator = function(value) {
ngModelCtrl.$setValidity('required', !attr.required || (value && value.length));
return value;
};
ngModelCtrl.$parsers.push(requiredValidator);
ngModelCtrl.$formatters.unshift(requiredValidator);
attr.$observe('required', function() {
requiredValidator(ngModelCtrl.$viewValue);
});
}
if (optionsExp) setupAsOptions(scope, element, ngModelCtrl);
else if (multiple) setupAsMultiple(scope, element, ngModelCtrl);
else setupAsSingle(scope, element, ngModelCtrl, selectCtrl);
////////////////////////////
function setupAsSingle(scope, selectElement, ngModelCtrl, selectCtrl) {
ngModelCtrl.$render = function() {
var viewValue = ngModelCtrl.$viewValue;
if (selectCtrl.hasOption(viewValue)) {
if (unknownOption.parent()) unknownOption.remove();
selectElement.val(viewValue);
if (viewValue === '') emptyOption.prop('selected', true); // to make IE9 happy
} else {
if (isUndefined(viewValue) && emptyOption) {
selectElement.val('');
} else {
selectCtrl.renderUnknownOption(viewValue);
}
}
};
selectElement.on('change', function() {
scope.$apply(function() {
if (unknownOption.parent()) unknownOption.remove();
ngModelCtrl.$setViewValue(selectElement.val());
});
});
}
function setupAsMultiple(scope, selectElement, ctrl) {
var lastView;
ctrl.$render = function() {
var items = new HashMap(ctrl.$viewValue);
forEach(selectElement.find('option'), function(option) {
option.selected = isDefined(items.get(option.value));
});
};
// we have to do it on each watch since ngModel watches reference, but
// we need to work of an array, so we need to see if anything was inserted/removed
scope.$watch(function selectMultipleWatch() {
if (!equals(lastView, ctrl.$viewValue)) {
lastView = copy(ctrl.$viewValue);
ctrl.$render();
}
});
selectElement.on('change', function() {
scope.$apply(function() {
var array = [];
forEach(selectElement.find('option'), function(option) {
if (option.selected) {
array.push(option.value);
}
});
ctrl.$setViewValue(array);
});
});
}
function setupAsOptions(scope, selectElement, ctrl) {
var match;
if (! (match = optionsExp.match(NG_OPTIONS_REGEXP))) {
throw ngOptionsMinErr('iexp',
"Expected expression in form of " +
"'_select_ (as _label_)? for (_key_,)?_value_ in _collection_'" +
" but got '{0}'. Element: {1}",
optionsExp, startingTag(selectElement));
}
var displayFn = $parse(match[2] || match[1]),
valueName = match[4] || match[6],
keyName = match[5],
groupByFn = $parse(match[3] || ''),
valueFn = $parse(match[2] ? match[1] : valueName),
valuesFn = $parse(match[7]),
track = match[8],
trackFn = track ? $parse(match[8]) : null,
// This is an array of array of existing option groups in DOM.
// We try to reuse these if possible
// - optionGroupsCache[0] is the options with no option group
// - optionGroupsCache[?][0] is the parent: either the SELECT or OPTGROUP element
optionGroupsCache = [[{element: selectElement, label:''}]];
if (nullOption) {
// compile the element since there might be bindings in it
$compile(nullOption)(scope);
// remove the class, which is added automatically because we recompile the element and it
// becomes the compilation root
nullOption.removeClass('ng-scope');
// we need to remove it before calling selectElement.html('') because otherwise IE will
// remove the label from the element. wtf?
nullOption.remove();
}
// clear contents, we'll add what's needed based on the model
selectElement.html('');
selectElement.on('change', function() {
scope.$apply(function() {
var optionGroup,
collection = valuesFn(scope) || [],
locals = {},
key, value, optionElement, index, groupIndex, length, groupLength, trackIndex;
if (multiple) {
value = [];
for (groupIndex = 0, groupLength = optionGroupsCache.length;
groupIndex < groupLength;
groupIndex++) {
// list of options for that group. (first item has the parent)
optionGroup = optionGroupsCache[groupIndex];
for(index = 1, length = optionGroup.length; index < length; index++) {
if ((optionElement = optionGroup[index].element)[0].selected) {
key = optionElement.val();
if (keyName) locals[keyName] = key;
if (trackFn) {
for (trackIndex = 0; trackIndex < collection.length; trackIndex++) {
locals[valueName] = collection[trackIndex];
if (trackFn(scope, locals) == key) break;
}
} else {
locals[valueName] = collection[key];
}
value.push(valueFn(scope, locals));
}
}
}
} else {
key = selectElement.val();
if (key == '?') {
value = undefined;
} else if (key === ''){
value = null;
} else {
if (trackFn) {
for (trackIndex = 0; trackIndex < collection.length; trackIndex++) {
locals[valueName] = collection[trackIndex];
if (trackFn(scope, locals) == key) {
value = valueFn(scope, locals);
break;
}
}
} else {
locals[valueName] = collection[key];
if (keyName) locals[keyName] = key;
value = valueFn(scope, locals);
}
}
}
ctrl.$setViewValue(value);
});
});
ctrl.$render = render;
// TODO(vojta): can't we optimize this ?
scope.$watch(render);
function render() {
// Temporary location for the option groups before we render them
var optionGroups = {'':[]},
optionGroupNames = [''],
optionGroupName,
optionGroup,
option,
existingParent, existingOptions, existingOption,
modelValue = ctrl.$modelValue,
values = valuesFn(scope) || [],
keys = keyName ? sortedKeys(values) : values,
key,
groupLength, length,
groupIndex, index,
locals = {},
selected,
selectedSet = false, // nothing is selected yet
lastElement,
element,
label;
if (multiple) {
if (trackFn && isArray(modelValue)) {
selectedSet = new HashMap([]);
for (var trackIndex = 0; trackIndex < modelValue.length; trackIndex++) {
locals[valueName] = modelValue[trackIndex];
selectedSet.put(trackFn(scope, locals), modelValue[trackIndex]);
}
} else {
selectedSet = new HashMap(modelValue);
}
}
// We now build up the list of options we need (we merge later)
for (index = 0; length = keys.length, index < length; index++) {
key = index;
if (keyName) {
key = keys[index];
if ( key.charAt(0) === '$' ) continue;
locals[keyName] = key;
}
locals[valueName] = values[key];
optionGroupName = groupByFn(scope, locals) || '';
if (!(optionGroup = optionGroups[optionGroupName])) {
optionGroup = optionGroups[optionGroupName] = [];
optionGroupNames.push(optionGroupName);
}
if (multiple) {
selected = isDefined(
selectedSet.remove(trackFn ? trackFn(scope, locals) : valueFn(scope, locals))
);
} else {
if (trackFn) {
var modelCast = {};
modelCast[valueName] = modelValue;
selected = trackFn(scope, modelCast) === trackFn(scope, locals);
} else {
selected = modelValue === valueFn(scope, locals);
}
selectedSet = selectedSet || selected; // see if at least one item is selected
}
label = displayFn(scope, locals); // what will be seen by the user
// doing displayFn(scope, locals) || '' overwrites zero values
label = isDefined(label) ? label : '';
optionGroup.push({
// either the index into array or key from object
id: trackFn ? trackFn(scope, locals) : (keyName ? keys[index] : index),
label: label,
selected: selected // determine if we should be selected
});
}
if (!multiple) {
if (nullOption || modelValue === null) {
// insert null option if we have a placeholder, or the model is null
optionGroups[''].unshift({id:'', label:'', selected:!selectedSet});
} else if (!selectedSet) {
// option could not be found, we have to insert the undefined item
optionGroups[''].unshift({id:'?', label:'', selected:true});
}
}
// Now we need to update the list of DOM nodes to match the optionGroups we computed above
for (groupIndex = 0, groupLength = optionGroupNames.length;
groupIndex < groupLength;
groupIndex++) {
// current option group name or '' if no group
optionGroupName = optionGroupNames[groupIndex];
// list of options for that group. (first item has the parent)
optionGroup = optionGroups[optionGroupName];
if (optionGroupsCache.length <= groupIndex) {
// we need to grow the optionGroups
existingParent = {
element: optGroupTemplate.clone().attr('label', optionGroupName),
label: optionGroup.label
};
existingOptions = [existingParent];
optionGroupsCache.push(existingOptions);
selectElement.append(existingParent.element);
} else {
existingOptions = optionGroupsCache[groupIndex];
existingParent = existingOptions[0]; // either SELECT (no group) or OPTGROUP element
// update the OPTGROUP label if not the same.
if (existingParent.label != optionGroupName) {
existingParent.element.attr('label', existingParent.label = optionGroupName);
}
}
lastElement = null; // start at the beginning
for(index = 0, length = optionGroup.length; index < length; index++) {
option = optionGroup[index];
if ((existingOption = existingOptions[index+1])) {
// reuse elements
lastElement = existingOption.element;
if (existingOption.label !== option.label) {
lastElement.text(existingOption.label = option.label);
}
if (existingOption.id !== option.id) {
lastElement.val(existingOption.id = option.id);
}
// lastElement.prop('selected') provided by jQuery has side-effects
if (lastElement[0].selected !== option.selected) {
lastElement.prop('selected', (existingOption.selected = option.selected));
}
} else {
// grow elements
// if it's a null option
if (option.id === '' && nullOption) {
// put back the pre-compiled element
element = nullOption;
} else {
// jQuery(v1.4.2) Bug: We should be able to chain the method calls, but
// in this version of jQuery on some browser the .text() returns a string
// rather then the element.
(element = optionTemplate.clone())
.val(option.id)
.attr('selected', option.selected)
.text(option.label);
}
existingOptions.push(existingOption = {
element: element,
label: option.label,
id: option.id,
selected: option.selected
});
if (lastElement) {
lastElement.after(element);
} else {
existingParent.element.append(element);
}
lastElement = element;
}
}
// remove any excessive OPTIONs in a group
index++; // increment since the existingOptions[0] is parent element not OPTION
while(existingOptions.length > index) {
existingOptions.pop().element.remove();
}
}
// remove any excessive OPTGROUPs from select
while(optionGroupsCache.length > groupIndex) {
optionGroupsCache.pop()[0].element.remove();
}
}
}
}
};
}];
var optionDirective = ['$interpolate', function($interpolate) {
var nullSelectCtrl = {
addOption: noop,
removeOption: noop
};
return {
restrict: 'E',
priority: 100,
compile: function(element, attr) {
if (isUndefined(attr.value)) {
var interpolateFn = $interpolate(element.text(), true);
if (!interpolateFn) {
attr.$set('value', element.text());
}
}
return function (scope, element, attr) {
var selectCtrlName = '$selectController',
parent = element.parent(),
selectCtrl = parent.data(selectCtrlName) ||
parent.parent().data(selectCtrlName); // in case we are in optgroup
if (selectCtrl && selectCtrl.databound) {
// For some reason Opera defaults to true and if not overridden this messes up the repeater.
// We don't want the view to drive the initialization of the model anyway.
element.prop('selected', false);
} else {
selectCtrl = nullSelectCtrl;
}
if (interpolateFn) {
scope.$watch(interpolateFn, function interpolateWatchAction(newVal, oldVal) {
attr.$set('value', newVal);
if (newVal !== oldVal) selectCtrl.removeOption(oldVal);
selectCtrl.addOption(newVal);
});
} else {
selectCtrl.addOption(attr.value);
}
element.on('$destroy', function() {
selectCtrl.removeOption(attr.value);
});
};
}
};
}];
var styleDirective = valueFn({
restrict: 'E',
terminal: true
});
/**
* Setup file for the Scenario.
* Must be first in the compilation/bootstrap list.
*/
// Public namespace
angular.scenario = angular.scenario || {};
/**
* Expose jQuery (e.g. for custom dsl extensions).
*/
angular.scenario.jQuery = _jQuery;
/**
* Defines a new output format.
*
* @param {string} name the name of the new output format
* @param {function()} fn function(context, runner) that generates the output
*/
angular.scenario.output = angular.scenario.output || function(name, fn) {
angular.scenario.output[name] = fn;
};
/**
* Defines a new DSL statement. If your factory function returns a Future
* it's returned, otherwise the result is assumed to be a map of functions
* for chaining. Chained functions are subject to the same rules.
*
* Note: All functions on the chain are bound to the chain scope so values
* set on "this" in your statement function are available in the chained
* functions.
*
* @param {string} name The name of the statement
* @param {function()} fn Factory function(), return a function for
* the statement.
*/
angular.scenario.dsl = angular.scenario.dsl || function(name, fn) {
angular.scenario.dsl[name] = function() {
/* jshint -W040 *//* The dsl binds `this` for us when calling chained functions */
function executeStatement(statement, args) {
var result = statement.apply(this, args);
if (angular.isFunction(result) || result instanceof angular.scenario.Future)
return result;
var self = this;
var chain = angular.extend({}, result);
angular.forEach(chain, function(value, name) {
if (angular.isFunction(value)) {
chain[name] = function() {
return executeStatement.call(self, value, arguments);
};
} else {
chain[name] = value;
}
});
return chain;
}
var statement = fn.apply(this, arguments);
return function() {
return executeStatement.call(this, statement, arguments);
};
};
};
/**
* Defines a new matcher for use with the expects() statement. The value
* this.actual (like in Jasmine) is available in your matcher to compare
* against. Your function should return a boolean. The future is automatically
* created for you.
*
* @param {string} name The name of the matcher
* @param {function()} fn The matching function(expected).
*/
angular.scenario.matcher = angular.scenario.matcher || function(name, fn) {
angular.scenario.matcher[name] = function(expected) {
var description = this.future.name +
(this.inverse ? ' not ' : ' ') + name +
' ' + angular.toJson(expected);
var self = this;
this.addFuture('expect ' + description,
function(done) {
var error;
self.actual = self.future.value;
if ((self.inverse && fn.call(self, expected)) ||
(!self.inverse && !fn.call(self, expected))) {
error = 'expected ' + description +
' but was ' + angular.toJson(self.actual);
}
done(error);
});
};
};
/**
* Initialize the scenario runner and run !
*
* Access global window and document object
* Access $runner through closure
*
* @param {Object=} config Config options
*/
angular.scenario.setUpAndRun = function(config) {
var href = window.location.href;
var body = _jQuery(document.body);
var output = [];
var objModel = new angular.scenario.ObjectModel($runner);
if (config && config.scenario_output) {
output = config.scenario_output.split(',');
}
angular.forEach(angular.scenario.output, function(fn, name) {
if (!output.length || indexOf(output,name) != -1) {
var context = body.append('<div></div>').find('div:last');
context.attr('id', name);
fn.call({}, context, $runner, objModel);
}
});
if (!/^http/.test(href) && !/^https/.test(href)) {
body.append('<p id="system-error"></p>');
body.find('#system-error').text(
'Scenario runner must be run using http or https. The protocol ' +
href.split(':')[0] + ':// is not supported.'
);
return;
}
var appFrame = body.append('<div id="application"></div>').find('#application');
var application = new angular.scenario.Application(appFrame);
$runner.on('RunnerEnd', function() {
appFrame.css('display', 'none');
appFrame.find('iframe').attr('src', 'about:blank');
});
$runner.on('RunnerError', function(error) {
if (window.console) {
console.log(formatException(error));
} else {
// Do something for IE
alert(error);
}
});
$runner.run(application);
};
/**
* Iterates through list with iterator function that must call the
* continueFunction to continue iterating.
*
* @param {Array} list list to iterate over
* @param {function()} iterator Callback function(value, continueFunction)
* @param {function()} done Callback function(error, result) called when
* iteration finishes or an error occurs.
*/
function asyncForEach(list, iterator, done) {
var i = 0;
function loop(error, index) {
if (index && index > i) {
i = index;
}
if (error || i >= list.length) {
done(error);
} else {
try {
iterator(list[i++], loop);
} catch (e) {
done(e);
}
}
}
loop();
}
/**
* Formats an exception into a string with the stack trace, but limits
* to a specific line length.
*
* @param {Object} error The exception to format, can be anything throwable
* @param {Number=} [maxStackLines=5] max lines of the stack trace to include
* default is 5.
*/
function formatException(error, maxStackLines) {
maxStackLines = maxStackLines || 5;
var message = error.toString();
if (error.stack) {
var stack = error.stack.split('\n');
if (stack[0].indexOf(message) === -1) {
maxStackLines++;
stack.unshift(error.message);
}
message = stack.slice(0, maxStackLines).join('\n');
}
return message;
}
/**
* Returns a function that gets the file name and line number from a
* location in the stack if available based on the call site.
*
* Note: this returns another function because accessing .stack is very
* expensive in Chrome.
*
* @param {Number} offset Number of stack lines to skip
*/
function callerFile(offset) {
var error = new Error();
return function() {
var line = (error.stack || '').split('\n')[offset];
// Clean up the stack trace line
if (line) {
if (line.indexOf('@') !== -1) {
// Firefox
line = line.substring(line.indexOf('@')+1);
} else {
// Chrome
line = line.substring(line.indexOf('(')+1).replace(')', '');
}
}
return line || '';
};
}
/**
* Don't use the jQuery trigger method since it works incorrectly.
*
* jQuery notifies listeners and then changes the state of a checkbox and
* does not create a real browser event. A real click changes the state of
* the checkbox and then notifies listeners.
*
* To work around this we instead use our own handler that fires a real event.
*/
(function(fn){
var parentTrigger = fn.trigger;
fn.trigger = function(type) {
if (/(click|change|keydown|blur|input|mousedown|mouseup)/.test(type)) {
var processDefaults = [];
this.each(function(index, node) {
processDefaults.push(browserTrigger(node, type));
});
// this is not compatible with jQuery - we return an array of returned values,
// so that scenario runner know whether JS code has preventDefault() of the event or not...
return processDefaults;
}
return parentTrigger.apply(this, arguments);
};
})(_jQuery.fn);
/**
* Finds all bindings with the substring match of name and returns an
* array of their values.
*
* @param {string} bindExp The name to match
* @return {Array.<string>} String of binding values
*/
_jQuery.fn.bindings = function(windowJquery, bindExp) {
var result = [], match,
bindSelector = '.ng-binding:visible';
if (angular.isString(bindExp)) {
bindExp = bindExp.replace(/\s/g, '');
match = function (actualExp) {
if (actualExp) {
actualExp = actualExp.replace(/\s/g, '');
if (actualExp == bindExp) return true;
if (actualExp.indexOf(bindExp) === 0) {
return actualExp.charAt(bindExp.length) == '|';
}
}
};
} else if (bindExp) {
match = function(actualExp) {
return actualExp && bindExp.exec(actualExp);
};
} else {
match = function(actualExp) {
return !!actualExp;
};
}
var selection = this.find(bindSelector);
if (this.is(bindSelector)) {
selection = selection.add(this);
}
function push(value) {
if (value === undefined) {
value = '';
} else if (typeof value != 'string') {
value = angular.toJson(value);
}
result.push('' + value);
}
selection.each(function() {
var element = windowJquery(this),
binding;
if (binding = element.data('$binding')) {
if (typeof binding == 'string') {
if (match(binding)) {
push(element.scope().$eval(binding));
}
} else {
if (!angular.isArray(binding)) {
binding = [binding];
}
for(var fns, j=0, jj=binding.length; j<jj; j++) {
fns = binding[j];
if (fns.parts) {
fns = fns.parts;
} else {
fns = [fns];
}
for (var scope, fn, i = 0, ii = fns.length; i < ii; i++) {
if(match((fn = fns[i]).exp)) {
push(fn(scope = scope || element.scope()));
}
}
}
}
}
});
return result;
};
(function() {
var msie = parseInt((/msie (\d+)/.exec(navigator.userAgent.toLowerCase()) || [])[1], 10);
function indexOf(array, obj) {
if (array.indexOf) return array.indexOf(obj);
for ( var i = 0; i < array.length; i++) {
if (obj === array[i]) return i;
}
return -1;
}
/**
* Triggers a browser event. Attempts to choose the right event if one is
* not specified.
*
* @param {Object} element Either a wrapped jQuery/jqLite node or a DOMElement
* @param {string} eventType Optional event type
* @param {Object=} eventData An optional object which contains additional event data (such as x,y
* coordinates, keys, etc...) that are passed into the event when triggered
*/
window.browserTrigger = function browserTrigger(element, eventType, eventData) {
if (element && !element.nodeName) element = element[0];
if (!element) return;
eventData = eventData || {};
var keys = eventData.keys;
var x = eventData.x;
var y = eventData.y;
var inputType = (element.type) ? element.type.toLowerCase() : null,
nodeName = element.nodeName.toLowerCase();
if (!eventType) {
eventType = {
'text': 'change',
'textarea': 'change',
'hidden': 'change',
'password': 'change',
'button': 'click',
'submit': 'click',
'reset': 'click',
'image': 'click',
'checkbox': 'click',
'radio': 'click',
'select-one': 'change',
'select-multiple': 'change',
'_default_': 'click'
}[inputType || '_default_'];
}
if (nodeName == 'option') {
element.parentNode.value = element.value;
element = element.parentNode;
eventType = 'change';
}
keys = keys || [];
function pressed(key) {
return indexOf(keys, key) !== -1;
}
if (msie < 9) {
if (inputType == 'radio' || inputType == 'checkbox') {
element.checked = !element.checked;
}
// WTF!!! Error: Unspecified error.
// Don't know why, but some elements when detached seem to be in inconsistent state and
// calling .fireEvent() on them will result in very unhelpful error (Error: Unspecified error)
// forcing the browser to compute the element position (by reading its CSS)
// puts the element in consistent state.
element.style.posLeft;
// TODO(vojta): create event objects with pressed keys to get it working on IE<9
var ret = element.fireEvent('on' + eventType);
if (inputType == 'submit') {
while(element) {
if (element.nodeName.toLowerCase() == 'form') {
element.fireEvent('onsubmit');
break;
}
element = element.parentNode;
}
}
return ret;
} else {
var evnt;
if(/transitionend/.test(eventType)) {
if(window.WebKitTransitionEvent) {
evnt = new WebKitTransitionEvent(eventType, eventData);
evnt.initEvent(eventType, false, true);
}
else {
try {
evnt = new TransitionEvent(eventType, eventData);
}
catch(e) {
evnt = document.createEvent('TransitionEvent');
evnt.initTransitionEvent(eventType, null, null, null, eventData.elapsedTime || 0);
}
}
}
else if(/animationend/.test(eventType)) {
if(window.WebKitAnimationEvent) {
evnt = new WebKitAnimationEvent(eventType, eventData);
evnt.initEvent(eventType, false, true);
}
else {
try {
evnt = new AnimationEvent(eventType, eventData);
}
catch(e) {
evnt = document.createEvent('AnimationEvent');
evnt.initAnimationEvent(eventType, null, null, null, eventData.elapsedTime || 0);
}
}
}
else {
evnt = document.createEvent('MouseEvents');
x = x || 0;
y = y || 0;
evnt.initMouseEvent(eventType, true, true, window, 0, x, y, x, y, pressed('ctrl'),
pressed('alt'), pressed('shift'), pressed('meta'), 0, element);
}
/* we're unable to change the timeStamp value directly so this
* is only here to allow for testing where the timeStamp value is
* read */
evnt.$manualTimeStamp = eventData.timeStamp;
if(!evnt) return;
var originalPreventDefault = evnt.preventDefault,
appWindow = element.ownerDocument.defaultView,
fakeProcessDefault = true,
finalProcessDefault,
angular = appWindow.angular || {};
// igor: temporary fix for https://bugzilla.mozilla.org/show_bug.cgi?id=684208
angular['ff-684208-preventDefault'] = false;
evnt.preventDefault = function() {
fakeProcessDefault = false;
return originalPreventDefault.apply(evnt, arguments);
};
element.dispatchEvent(evnt);
finalProcessDefault = !(angular['ff-684208-preventDefault'] || !fakeProcessDefault);
delete angular['ff-684208-preventDefault'];
return finalProcessDefault;
}
};
}());
/**
* Represents the application currently being tested and abstracts usage
* of iframes or separate windows.
*
* @param {Object} context jQuery wrapper around HTML context.
*/
angular.scenario.Application = function(context) {
this.context = context;
context.append(
'<h2>Current URL: <a href="about:blank">None</a></h2>' +
'<div id="test-frames"></div>'
);
};
/**
* Gets the jQuery collection of frames. Don't use this directly because
* frames may go stale.
*
* @private
* @return {Object} jQuery collection
*/
angular.scenario.Application.prototype.getFrame_ = function() {
return this.context.find('#test-frames iframe:last');
};
/**
* Gets the window of the test runner frame. Always favor executeAction()
* instead of this method since it prevents you from getting a stale window.
*
* @private
* @return {Object} the window of the frame
*/
angular.scenario.Application.prototype.getWindow_ = function() {
var contentWindow = this.getFrame_().prop('contentWindow');
if (!contentWindow)
throw 'Frame window is not accessible.';
return contentWindow;
};
/**
* Changes the location of the frame.
*
* @param {string} url The URL. If it begins with a # then only the
* hash of the page is changed.
* @param {function()} loadFn function($window, $document) Called when frame loads.
* @param {function()} errorFn function(error) Called if any error when loading.
*/
angular.scenario.Application.prototype.navigateTo = function(url, loadFn, errorFn) {
var self = this;
var frame = self.getFrame_();
//TODO(esprehn): Refactor to use rethrow()
errorFn = errorFn || function(e) { throw e; };
if (url === 'about:blank') {
errorFn('Sandbox Error: Navigating to about:blank is not allowed.');
} else if (url.charAt(0) === '#') {
url = frame.attr('src').split('#')[0] + url;
frame.attr('src', url);
self.executeAction(loadFn);
} else {
frame.remove();
self.context.find('#test-frames').append('<iframe>');
frame = self.getFrame_();
frame.load(function() {
frame.off();
try {
var $window = self.getWindow_();
if ($window.angular) {
// Disable animations
$window.angular.resumeBootstrap([['$provide', function($provide) {
return ['$animate', function($animate) {
$animate.enabled(false);
}];
}]]);
}
self.executeAction(loadFn);
} catch (e) {
errorFn(e);
}
}).attr('src', url);
// for IE compatibility set the name *after* setting the frame url
frame[0].contentWindow.name = "NG_DEFER_BOOTSTRAP!";
}
self.context.find('> h2 a').attr('href', url).text(url);
};
/**
* Executes a function in the context of the tested application. Will wait
* for all pending angular xhr requests before executing.
*
* @param {function()} action The callback to execute. function($window, $document)
* $document is a jQuery wrapped document.
*/
angular.scenario.Application.prototype.executeAction = function(action) {
var self = this;
var $window = this.getWindow_();
if (!$window.document) {
throw 'Sandbox Error: Application document not accessible.';
}
if (!$window.angular) {
return action.call(this, $window, _jQuery($window.document));
}
angularInit($window.document, function(element) {
var $injector = $window.angular.element(element).injector();
var $element = _jQuery(element);
$element.injector = function() {
return $injector;
};
$injector.invoke(function($browser){
$browser.notifyWhenNoOutstandingRequests(function() {
action.call(self, $window, $element);
});
});
});
};
/**
* The representation of define blocks. Don't used directly, instead use
* define() in your tests.
*
* @param {string} descName Name of the block
* @param {Object} parent describe or undefined if the root.
*/
angular.scenario.Describe = function(descName, parent) {
this.only = parent && parent.only;
this.beforeEachFns = [];
this.afterEachFns = [];
this.its = [];
this.children = [];
this.name = descName;
this.parent = parent;
this.id = angular.scenario.Describe.id++;
/**
* Calls all before functions.
*/
var beforeEachFns = this.beforeEachFns;
this.setupBefore = function() {
if (parent) parent.setupBefore.call(this);
angular.forEach(beforeEachFns, function(fn) { fn.call(this); }, this);
};
/**
* Calls all after functions.
*/
var afterEachFns = this.afterEachFns;
this.setupAfter = function() {
angular.forEach(afterEachFns, function(fn) { fn.call(this); }, this);
if (parent) parent.setupAfter.call(this);
};
};
// Shared Unique ID generator for every describe block
angular.scenario.Describe.id = 0;
// Shared Unique ID generator for every it (spec)
angular.scenario.Describe.specId = 0;
/**
* Defines a block to execute before each it or nested describe.
*
* @param {function()} body Body of the block.
*/
angular.scenario.Describe.prototype.beforeEach = function(body) {
this.beforeEachFns.push(body);
};
/**
* Defines a block to execute after each it or nested describe.
*
* @param {function()} body Body of the block.
*/
angular.scenario.Describe.prototype.afterEach = function(body) {
this.afterEachFns.push(body);
};
/**
* Creates a new describe block that's a child of this one.
*
* @param {string} name Name of the block. Appended to the parent block's name.
* @param {function()} body Body of the block.
*/
angular.scenario.Describe.prototype.describe = function(name, body) {
var child = new angular.scenario.Describe(name, this);
this.children.push(child);
body.call(child);
};
/**
* Same as describe() but makes ddescribe blocks the only to run.
*
* @param {string} name Name of the test.
* @param {function()} body Body of the block.
*/
angular.scenario.Describe.prototype.ddescribe = function(name, body) {
var child = new angular.scenario.Describe(name, this);
child.only = true;
this.children.push(child);
body.call(child);
};
/**
* Use to disable a describe block.
*/
angular.scenario.Describe.prototype.xdescribe = angular.noop;
/**
* Defines a test.
*
* @param {string} name Name of the test.
* @param {function()} body Body of the block.
*/
angular.scenario.Describe.prototype.it = function(name, body) {
this.its.push({
id: angular.scenario.Describe.specId++,
definition: this,
only: this.only,
name: name,
before: this.setupBefore,
body: body,
after: this.setupAfter
});
};
/**
* Same as it() but makes iit tests the only test to run.
*
* @param {string} name Name of the test.
* @param {function()} body Body of the block.
*/
angular.scenario.Describe.prototype.iit = function(name, body) {
this.it.apply(this, arguments);
this.its[this.its.length-1].only = true;
};
/**
* Use to disable a test block.
*/
angular.scenario.Describe.prototype.xit = angular.noop;
/**
* Gets an array of functions representing all the tests (recursively).
* that can be executed with SpecRunner's.
*
* @return {Array<Object>} Array of it blocks {
* definition : Object // parent Describe
* only: boolean
* name: string
* before: Function
* body: Function
* after: Function
* }
*/
angular.scenario.Describe.prototype.getSpecs = function() {
var specs = arguments[0] || [];
angular.forEach(this.children, function(child) {
child.getSpecs(specs);
});
angular.forEach(this.its, function(it) {
specs.push(it);
});
var only = [];
angular.forEach(specs, function(it) {
if (it.only) {
only.push(it);
}
});
return (only.length && only) || specs;
};
/**
* A future action in a spec.
*
* @param {string} name name of the future action
* @param {function()} behavior future callback(error, result)
* @param {function()} line Optional. function that returns the file/line number.
*/
angular.scenario.Future = function(name, behavior, line) {
this.name = name;
this.behavior = behavior;
this.fulfilled = false;
this.value = undefined;
this.parser = angular.identity;
this.line = line || function() { return ''; };
};
/**
* Executes the behavior of the closure.
*
* @param {function()} doneFn Callback function(error, result)
*/
angular.scenario.Future.prototype.execute = function(doneFn) {
var self = this;
this.behavior(function(error, result) {
self.fulfilled = true;
if (result) {
try {
result = self.parser(result);
} catch(e) {
error = e;
}
}
self.value = error || result;
doneFn(error, result);
});
};
/**
* Configures the future to convert it's final with a function fn(value)
*
* @param {function()} fn function(value) that returns the parsed value
*/
angular.scenario.Future.prototype.parsedWith = function(fn) {
this.parser = fn;
return this;
};
/**
* Configures the future to parse it's final value from JSON
* into objects.
*/
angular.scenario.Future.prototype.fromJson = function() {
return this.parsedWith(angular.fromJson);
};
/**
* Configures the future to convert it's final value from objects
* into JSON.
*/
angular.scenario.Future.prototype.toJson = function() {
return this.parsedWith(angular.toJson);
};
/**
* Maintains an object tree from the runner events.
*
* @param {Object} runner The scenario Runner instance to connect to.
*
* TODO(esprehn): Every output type creates one of these, but we probably
* want one global shared instance. Need to handle events better too
* so the HTML output doesn't need to do spec model.getSpec(spec.id)
* silliness.
*
* TODO(vojta) refactor on, emit methods (from all objects) - use inheritance
*/
angular.scenario.ObjectModel = function(runner) {
var self = this;
this.specMap = {};
this.listeners = [];
this.value = {
name: '',
children: {}
};
runner.on('SpecBegin', function(spec) {
var block = self.value,
definitions = [];
angular.forEach(self.getDefinitionPath(spec), function(def) {
if (!block.children[def.name]) {
block.children[def.name] = {
id: def.id,
name: def.name,
children: {},
specs: {}
};
}
block = block.children[def.name];
definitions.push(def.name);
});
var it = self.specMap[spec.id] =
block.specs[spec.name] =
new angular.scenario.ObjectModel.Spec(spec.id, spec.name, definitions);
// forward the event
self.emit('SpecBegin', it);
});
runner.on('SpecError', function(spec, error) {
var it = self.getSpec(spec.id);
it.status = 'error';
it.error = error;
// forward the event
self.emit('SpecError', it, error);
});
runner.on('SpecEnd', function(spec) {
var it = self.getSpec(spec.id);
complete(it);
// forward the event
self.emit('SpecEnd', it);
});
runner.on('StepBegin', function(spec, step) {
var it = self.getSpec(spec.id);
step = new angular.scenario.ObjectModel.Step(step.name);
it.steps.push(step);
// forward the event
self.emit('StepBegin', it, step);
});
runner.on('StepEnd', function(spec) {
var it = self.getSpec(spec.id);
var step = it.getLastStep();
if (step.name !== step.name)
throw 'Events fired in the wrong order. Step names don\'t match.';
complete(step);
// forward the event
self.emit('StepEnd', it, step);
});
runner.on('StepFailure', function(spec, step, error) {
var it = self.getSpec(spec.id),
modelStep = it.getLastStep();
modelStep.setErrorStatus('failure', error, step.line());
it.setStatusFromStep(modelStep);
// forward the event
self.emit('StepFailure', it, modelStep, error);
});
runner.on('StepError', function(spec, step, error) {
var it = self.getSpec(spec.id),
modelStep = it.getLastStep();
modelStep.setErrorStatus('error', error, step.line());
it.setStatusFromStep(modelStep);
// forward the event
self.emit('StepError', it, modelStep, error);
});
runner.on('RunnerBegin', function() {
self.emit('RunnerBegin');
});
runner.on('RunnerEnd', function() {
self.emit('RunnerEnd');
});
function complete(item) {
item.endTime = new Date().getTime();
item.duration = item.endTime - item.startTime;
item.status = item.status || 'success';
}
};
/**
* Adds a listener for an event.
*
* @param {string} eventName Name of the event to add a handler for
* @param {function()} listener Function that will be called when event is fired
*/
angular.scenario.ObjectModel.prototype.on = function(eventName, listener) {
eventName = eventName.toLowerCase();
this.listeners[eventName] = this.listeners[eventName] || [];
this.listeners[eventName].push(listener);
};
/**
* Emits an event which notifies listeners and passes extra
* arguments.
*
* @param {string} eventName Name of the event to fire.
*/
angular.scenario.ObjectModel.prototype.emit = function(eventName) {
var self = this,
args = Array.prototype.slice.call(arguments, 1);
eventName = eventName.toLowerCase();
if (this.listeners[eventName]) {
angular.forEach(this.listeners[eventName], function(listener) {
listener.apply(self, args);
});
}
};
/**
* Computes the path of definition describe blocks that wrap around
* this spec.
*
* @param spec Spec to compute the path for.
* @return {Array<Describe>} The describe block path
*/
angular.scenario.ObjectModel.prototype.getDefinitionPath = function(spec) {
var path = [];
var currentDefinition = spec.definition;
while (currentDefinition && currentDefinition.name) {
path.unshift(currentDefinition);
currentDefinition = currentDefinition.parent;
}
return path;
};
/**
* Gets a spec by id.
*
* @param {string} id The id of the spec to get the object for.
* @return {Object} the Spec instance
*/
angular.scenario.ObjectModel.prototype.getSpec = function(id) {
return this.specMap[id];
};
/**
* A single it block.
*
* @param {string} id Id of the spec
* @param {string} name Name of the spec
* @param {Array<string>=} definitionNames List of all describe block names that wrap this spec
*/
angular.scenario.ObjectModel.Spec = function(id, name, definitionNames) {
this.id = id;
this.name = name;
this.startTime = new Date().getTime();
this.steps = [];
this.fullDefinitionName = (definitionNames || []).join(' ');
};
/**
* Adds a new step to the Spec.
*
* @param {string} name Name of the step (really name of the future)
* @return {Object} the added step
*/
angular.scenario.ObjectModel.Spec.prototype.addStep = function(name) {
var step = new angular.scenario.ObjectModel.Step(name);
this.steps.push(step);
return step;
};
/**
* Gets the most recent step.
*
* @return {Object} the step
*/
angular.scenario.ObjectModel.Spec.prototype.getLastStep = function() {
return this.steps[this.steps.length-1];
};
/**
* Set status of the Spec from given Step
*
* @param {angular.scenario.ObjectModel.Step} step
*/
angular.scenario.ObjectModel.Spec.prototype.setStatusFromStep = function(step) {
if (!this.status || step.status == 'error') {
this.status = step.status;
this.error = step.error;
this.line = step.line;
}
};
/**
* A single step inside a Spec.
*
* @param {string} name Name of the step
*/
angular.scenario.ObjectModel.Step = function(name) {
this.name = name;
this.startTime = new Date().getTime();
};
/**
* Helper method for setting all error status related properties
*
* @param {string} status
* @param {string} error
* @param {string} line
*/
angular.scenario.ObjectModel.Step.prototype.setErrorStatus = function(status, error, line) {
this.status = status;
this.error = error;
this.line = line;
};
/**
* Runner for scenarios
*
* Has to be initialized before any test is loaded,
* because it publishes the API into window (global space).
*/
angular.scenario.Runner = function($window) {
this.listeners = [];
this.$window = $window;
this.rootDescribe = new angular.scenario.Describe();
this.currentDescribe = this.rootDescribe;
this.api = {
it: this.it,
iit: this.iit,
xit: angular.noop,
describe: this.describe,
ddescribe: this.ddescribe,
xdescribe: angular.noop,
beforeEach: this.beforeEach,
afterEach: this.afterEach
};
angular.forEach(this.api, angular.bind(this, function(fn, key) {
this.$window[key] = angular.bind(this, fn);
}));
};
/**
* Emits an event which notifies listeners and passes extra
* arguments.
*
* @param {string} eventName Name of the event to fire.
*/
angular.scenario.Runner.prototype.emit = function(eventName) {
var self = this;
var args = Array.prototype.slice.call(arguments, 1);
eventName = eventName.toLowerCase();
if (!this.listeners[eventName])
return;
angular.forEach(this.listeners[eventName], function(listener) {
listener.apply(self, args);
});
};
/**
* Adds a listener for an event.
*
* @param {string} eventName The name of the event to add a handler for
* @param {string} listener The fn(...) that takes the extra arguments from emit()
*/
angular.scenario.Runner.prototype.on = function(eventName, listener) {
eventName = eventName.toLowerCase();
this.listeners[eventName] = this.listeners[eventName] || [];
this.listeners[eventName].push(listener);
};
/**
* Defines a describe block of a spec.
*
* @see Describe.js
*
* @param {string} name Name of the block
* @param {function()} body Body of the block
*/
angular.scenario.Runner.prototype.describe = function(name, body) {
var self = this;
this.currentDescribe.describe(name, function() {
var parentDescribe = self.currentDescribe;
self.currentDescribe = this;
try {
body.call(this);
} finally {
self.currentDescribe = parentDescribe;
}
});
};
/**
* Same as describe, but makes ddescribe the only blocks to run.
*
* @see Describe.js
*
* @param {string} name Name of the block
* @param {function()} body Body of the block
*/
angular.scenario.Runner.prototype.ddescribe = function(name, body) {
var self = this;
this.currentDescribe.ddescribe(name, function() {
var parentDescribe = self.currentDescribe;
self.currentDescribe = this;
try {
body.call(this);
} finally {
self.currentDescribe = parentDescribe;
}
});
};
/**
* Defines a test in a describe block of a spec.
*
* @see Describe.js
*
* @param {string} name Name of the block
* @param {function()} body Body of the block
*/
angular.scenario.Runner.prototype.it = function(name, body) {
this.currentDescribe.it(name, body);
};
/**
* Same as it, but makes iit tests the only tests to run.
*
* @see Describe.js
*
* @param {string} name Name of the block
* @param {function()} body Body of the block
*/
angular.scenario.Runner.prototype.iit = function(name, body) {
this.currentDescribe.iit(name, body);
};
/**
* Defines a function to be called before each it block in the describe
* (and before all nested describes).
*
* @see Describe.js
*
* @param {function()} Callback to execute
*/
angular.scenario.Runner.prototype.beforeEach = function(body) {
this.currentDescribe.beforeEach(body);
};
/**
* Defines a function to be called after each it block in the describe
* (and before all nested describes).
*
* @see Describe.js
*
* @param {function()} Callback to execute
*/
angular.scenario.Runner.prototype.afterEach = function(body) {
this.currentDescribe.afterEach(body);
};
/**
* Creates a new spec runner.
*
* @private
* @param {Object} scope parent scope
*/
angular.scenario.Runner.prototype.createSpecRunner_ = function(scope) {
var child = scope.$new();
var Cls = angular.scenario.SpecRunner;
// Export all the methods to child scope manually as now we don't mess controllers with scopes
// TODO(vojta): refactor scenario runner so that these objects are not tightly coupled as current
for (var name in Cls.prototype)
child[name] = angular.bind(child, Cls.prototype[name]);
Cls.call(child);
return child;
};
/**
* Runs all the loaded tests with the specified runner class on the
* provided application.
*
* @param {angular.scenario.Application} application App to remote control.
*/
angular.scenario.Runner.prototype.run = function(application) {
var self = this;
var $root = angular.injector(['ng']).get('$rootScope');
angular.extend($root, this);
angular.forEach(angular.scenario.Runner.prototype, function(fn, name) {
$root[name] = angular.bind(self, fn);
});
$root.application = application;
$root.emit('RunnerBegin');
asyncForEach(this.rootDescribe.getSpecs(), function(spec, specDone) {
var dslCache = {};
var runner = self.createSpecRunner_($root);
angular.forEach(angular.scenario.dsl, function(fn, key) {
dslCache[key] = fn.call($root);
});
angular.forEach(angular.scenario.dsl, function(fn, key) {
self.$window[key] = function() {
var line = callerFile(3);
var scope = runner.$new();
// Make the dsl accessible on the current chain
scope.dsl = {};
angular.forEach(dslCache, function(fn, key) {
scope.dsl[key] = function() {
return dslCache[key].apply(scope, arguments);
};
});
// Make these methods work on the current chain
scope.addFuture = function() {
Array.prototype.push.call(arguments, line);
return angular.scenario.SpecRunner.
prototype.addFuture.apply(scope, arguments);
};
scope.addFutureAction = function() {
Array.prototype.push.call(arguments, line);
return angular.scenario.SpecRunner.
prototype.addFutureAction.apply(scope, arguments);
};
return scope.dsl[key].apply(scope, arguments);
};
});
runner.run(spec, function() {
runner.$destroy();
specDone.apply(this, arguments);
});
},
function(error) {
if (error) {
self.emit('RunnerError', error);
}
self.emit('RunnerEnd');
});
};
/**
* This class is the "this" of the it/beforeEach/afterEach method.
* Responsibilities:
* - "this" for it/beforeEach/afterEach
* - keep state for single it/beforeEach/afterEach execution
* - keep track of all of the futures to execute
* - run single spec (execute each future)
*/
angular.scenario.SpecRunner = function() {
this.futures = [];
this.afterIndex = 0;
};
/**
* Executes a spec which is an it block with associated before/after functions
* based on the describe nesting.
*
* @param {Object} spec A spec object
* @param {function()} specDone function that is called when the spec finishes,
* of the form `Function(error, index)`
*/
angular.scenario.SpecRunner.prototype.run = function(spec, specDone) {
var self = this;
this.spec = spec;
this.emit('SpecBegin', spec);
try {
spec.before.call(this);
spec.body.call(this);
this.afterIndex = this.futures.length;
spec.after.call(this);
} catch (e) {
this.emit('SpecError', spec, e);
this.emit('SpecEnd', spec);
specDone();
return;
}
var handleError = function(error, done) {
if (self.error) {
return done();
}
self.error = true;
done(null, self.afterIndex);
};
asyncForEach(
this.futures,
function(future, futureDone) {
self.step = future;
self.emit('StepBegin', spec, future);
try {
future.execute(function(error) {
if (error) {
self.emit('StepFailure', spec, future, error);
self.emit('StepEnd', spec, future);
return handleError(error, futureDone);
}
self.emit('StepEnd', spec, future);
self.$window.setTimeout(function() { futureDone(); }, 0);
});
} catch (e) {
self.emit('StepError', spec, future, e);
self.emit('StepEnd', spec, future);
handleError(e, futureDone);
}
},
function(e) {
if (e) {
self.emit('SpecError', spec, e);
}
self.emit('SpecEnd', spec);
// Call done in a timeout so exceptions don't recursively
// call this function
self.$window.setTimeout(function() { specDone(); }, 0);
}
);
};
/**
* Adds a new future action.
*
* Note: Do not pass line manually. It happens automatically.
*
* @param {string} name Name of the future
* @param {function()} behavior Behavior of the future
* @param {function()} line fn() that returns file/line number
*/
angular.scenario.SpecRunner.prototype.addFuture = function(name, behavior, line) {
var future = new angular.scenario.Future(name, angular.bind(this, behavior), line);
this.futures.push(future);
return future;
};
/**
* Adds a new future action to be executed on the application window.
*
* Note: Do not pass line manually. It happens automatically.
*
* @param {string} name Name of the future
* @param {function()} behavior Behavior of the future
* @param {function()} line fn() that returns file/line number
*/
angular.scenario.SpecRunner.prototype.addFutureAction = function(name, behavior, line) {
var self = this;
var NG = /\[ng\\\:/;
return this.addFuture(name, function(done) {
this.application.executeAction(function($window, $document) {
//TODO(esprehn): Refactor this so it doesn't need to be in here.
$document.elements = function(selector) {
var args = Array.prototype.slice.call(arguments, 1);
selector = (self.selector || '') + ' ' + (selector || '');
selector = _jQuery.trim(selector) || '*';
angular.forEach(args, function(value, index) {
selector = selector.replace('$' + (index + 1), value);
});
var result = $document.find(selector);
if (selector.match(NG)) {
angular.forEach(['[ng-','[data-ng-','[x-ng-'], function(value, index){
result = result.add(selector.replace(NG, value), $document);
});
}
if (!result.length) {
throw {
type: 'selector',
message: 'Selector ' + selector + ' did not match any elements.'
};
}
return result;
};
try {
behavior.call(self, $window, $document, done);
} catch(e) {
if (e.type && e.type === 'selector') {
done(e.message);
} else {
throw e;
}
}
});
}, line);
};
/**
* Shared DSL statements that are useful to all scenarios.
*/
/**
* Usage:
* pause() pauses until you call resume() in the console
*/
angular.scenario.dsl('pause', function() {
return function() {
return this.addFuture('pausing for you to resume', function(done) {
this.emit('InteractivePause', this.spec, this.step);
this.$window.resume = function() { done(); };
});
};
});
/**
* Usage:
* sleep(seconds) pauses the test for specified number of seconds
*/
angular.scenario.dsl('sleep', function() {
return function(time) {
return this.addFuture('sleep for ' + time + ' seconds', function(done) {
this.$window.setTimeout(function() { done(null, time * 1000); }, time * 1000);
});
};
});
/**
* Usage:
* browser().navigateTo(url) Loads the url into the frame
* browser().navigateTo(url, fn) where fn(url) is called and returns the URL to navigate to
* browser().reload() refresh the page (reload the same URL)
* browser().window.href() window.location.href
* browser().window.path() window.location.pathname
* browser().window.search() window.location.search
* browser().window.hash() window.location.hash without # prefix
* browser().location().url() see ng.$location#url
* browser().location().path() see ng.$location#path
* browser().location().search() see ng.$location#search
* browser().location().hash() see ng.$location#hash
*/
angular.scenario.dsl('browser', function() {
var chain = {};
chain.navigateTo = function(url, delegate) {
var application = this.application;
return this.addFuture("browser navigate to '" + url + "'", function(done) {
if (delegate) {
url = delegate.call(this, url);
}
application.navigateTo(url, function() {
done(null, url);
}, done);
});
};
chain.reload = function() {
var application = this.application;
return this.addFutureAction('browser reload', function($window, $document, done) {
var href = $window.location.href;
application.navigateTo(href, function() {
done(null, href);
}, done);
});
};
chain.window = function() {
var api = {};
api.href = function() {
return this.addFutureAction('window.location.href', function($window, $document, done) {
done(null, $window.location.href);
});
};
api.path = function() {
return this.addFutureAction('window.location.path', function($window, $document, done) {
done(null, $window.location.pathname);
});
};
api.search = function() {
return this.addFutureAction('window.location.search', function($window, $document, done) {
done(null, $window.location.search);
});
};
api.hash = function() {
return this.addFutureAction('window.location.hash', function($window, $document, done) {
done(null, $window.location.hash.replace('#', ''));
});
};
return api;
};
chain.location = function() {
var api = {};
api.url = function() {
return this.addFutureAction('$location.url()', function($window, $document, done) {
done(null, $document.injector().get('$location').url());
});
};
api.path = function() {
return this.addFutureAction('$location.path()', function($window, $document, done) {
done(null, $document.injector().get('$location').path());
});
};
api.search = function() {
return this.addFutureAction('$location.search()', function($window, $document, done) {
done(null, $document.injector().get('$location').search());
});
};
api.hash = function() {
return this.addFutureAction('$location.hash()', function($window, $document, done) {
done(null, $document.injector().get('$location').hash());
});
};
return api;
};
return function() {
return chain;
};
});
/**
* Usage:
* expect(future).{matcher} where matcher is one of the matchers defined
* with angular.scenario.matcher
*
* ex. expect(binding("name")).toEqual("Elliott")
*/
angular.scenario.dsl('expect', function() {
var chain = angular.extend({}, angular.scenario.matcher);
chain.not = function() {
this.inverse = true;
return chain;
};
return function(future) {
this.future = future;
return chain;
};
});
/**
* Usage:
* using(selector, label) scopes the next DSL element selection
*
* ex.
* using('#foo', "'Foo' text field").input('bar')
*/
angular.scenario.dsl('using', function() {
return function(selector, label) {
this.selector = _jQuery.trim((this.selector||'') + ' ' + selector);
if (angular.isString(label) && label.length) {
this.label = label + ' ( ' + this.selector + ' )';
} else {
this.label = this.selector;
}
return this.dsl;
};
});
/**
* Usage:
* binding(name) returns the value of the first matching binding
*/
angular.scenario.dsl('binding', function() {
return function(name) {
return this.addFutureAction("select binding '" + name + "'",
function($window, $document, done) {
var values = $document.elements().bindings($window.angular.element, name);
if (!values.length) {
return done("Binding selector '" + name + "' did not match.");
}
done(null, values[0]);
});
};
});
/**
* Usage:
* input(name).enter(value) enters value in input with specified name
* input(name).check() checks checkbox
* input(name).select(value) selects the radio button with specified name/value
* input(name).val() returns the value of the input.
*/
angular.scenario.dsl('input', function() {
var chain = {};
var supportInputEvent = 'oninput' in document.createElement('div') && msie != 9;
chain.enter = function(value, event) {
return this.addFutureAction("input '" + this.name + "' enter '" + value + "'",
function($window, $document, done) {
var input = $document.elements('[ng\\:model="$1"]', this.name).filter(':input');
input.val(value);
input.trigger(event || (supportInputEvent ? 'input' : 'change'));
done();
});
};
chain.check = function() {
return this.addFutureAction("checkbox '" + this.name + "' toggle",
function($window, $document, done) {
var input = $document.elements('[ng\\:model="$1"]', this.name).filter(':checkbox');
input.trigger('click');
done();
});
};
chain.select = function(value) {
return this.addFutureAction("radio button '" + this.name + "' toggle '" + value + "'",
function($window, $document, done) {
var input = $document.
elements('[ng\\:model="$1"][value="$2"]', this.name, value).filter(':radio');
input.trigger('click');
done();
});
};
chain.val = function() {
return this.addFutureAction("return input val", function($window, $document, done) {
var input = $document.elements('[ng\\:model="$1"]', this.name).filter(':input');
done(null,input.val());
});
};
return function(name) {
this.name = name;
return chain;
};
});
/**
* Usage:
* repeater('#products table', 'Product List').count() number of rows
* repeater('#products table', 'Product List').row(1) all bindings in row as an array
* repeater('#products table', 'Product List').column('product.name') all values across all rows
* in an array
*/
angular.scenario.dsl('repeater', function() {
var chain = {};
chain.count = function() {
return this.addFutureAction("repeater '" + this.label + "' count",
function($window, $document, done) {
try {
done(null, $document.elements().length);
} catch (e) {
done(null, 0);
}
});
};
chain.column = function(binding) {
return this.addFutureAction("repeater '" + this.label + "' column '" + binding + "'",
function($window, $document, done) {
done(null, $document.elements().bindings($window.angular.element, binding));
});
};
chain.row = function(index) {
return this.addFutureAction("repeater '" + this.label + "' row '" + index + "'",
function($window, $document, done) {
var matches = $document.elements().slice(index, index + 1);
if (!matches.length)
return done('row ' + index + ' out of bounds');
done(null, matches.bindings($window.angular.element));
});
};
return function(selector, label) {
this.dsl.using(selector, label);
return chain;
};
});
/**
* Usage:
* select(name).option('value') select one option
* select(name).options('value1', 'value2', ...) select options from a multi select
*/
angular.scenario.dsl('select', function() {
var chain = {};
chain.option = function(value) {
return this.addFutureAction("select '" + this.name + "' option '" + value + "'",
function($window, $document, done) {
var select = $document.elements('select[ng\\:model="$1"]', this.name);
var option = select.find('option[value="' + value + '"]');
if (option.length) {
select.val(value);
} else {
option = select.find('option').filter(function(){
return _jQuery(this).text() === value;
});
if (!option.length) {
option = select.find('option:contains("' + value + '")');
}
if (option.length) {
select.val(option.val());
} else {
return done("option '" + value + "' not found");
}
}
select.trigger('change');
done();
});
};
chain.options = function() {
var values = arguments;
return this.addFutureAction("select '" + this.name + "' options '" + values + "'",
function($window, $document, done) {
var select = $document.elements('select[multiple][ng\\:model="$1"]', this.name);
select.val(values);
select.trigger('change');
done();
});
};
return function(name) {
this.name = name;
return chain;
};
});
/**
* Usage:
* element(selector, label).count() get the number of elements that match selector
* element(selector, label).click() clicks an element
* element(selector, label).mouseover() mouseover an element
* element(selector, label).mousedown() mousedown an element
* element(selector, label).mouseup() mouseup an element
* element(selector, label).query(fn) executes fn(selectedElements, done)
* element(selector, label).{method}() gets the value (as defined by jQuery, ex. val)
* element(selector, label).{method}(value) sets the value (as defined by jQuery, ex. val)
* element(selector, label).{method}(key) gets the value (as defined by jQuery, ex. attr)
* element(selector, label).{method}(key, value) sets the value (as defined by jQuery, ex. attr)
*/
angular.scenario.dsl('element', function() {
var KEY_VALUE_METHODS = ['attr', 'css', 'prop'];
var VALUE_METHODS = [
'val', 'text', 'html', 'height', 'innerHeight', 'outerHeight', 'width',
'innerWidth', 'outerWidth', 'position', 'scrollLeft', 'scrollTop', 'offset'
];
var chain = {};
chain.count = function() {
return this.addFutureAction("element '" + this.label + "' count",
function($window, $document, done) {
try {
done(null, $document.elements().length);
} catch (e) {
done(null, 0);
}
});
};
chain.click = function() {
return this.addFutureAction("element '" + this.label + "' click",
function($window, $document, done) {
var elements = $document.elements();
var href = elements.attr('href');
var eventProcessDefault = elements.trigger('click')[0];
if (href && elements[0].nodeName.toUpperCase() === 'A' && eventProcessDefault) {
this.application.navigateTo(href, function() {
done();
}, done);
} else {
done();
}
});
};
chain.dblclick = function() {
return this.addFutureAction("element '" + this.label + "' dblclick",
function($window, $document, done) {
var elements = $document.elements();
var href = elements.attr('href');
var eventProcessDefault = elements.trigger('dblclick')[0];
if (href && elements[0].nodeName.toUpperCase() === 'A' && eventProcessDefault) {
this.application.navigateTo(href, function() {
done();
}, done);
} else {
done();
}
});
};
chain.mouseover = function() {
return this.addFutureAction("element '" + this.label + "' mouseover",
function($window, $document, done) {
var elements = $document.elements();
elements.trigger('mouseover');
done();
});
};
chain.mousedown = function() {
return this.addFutureAction("element '" + this.label + "' mousedown",
function($window, $document, done) {
var elements = $document.elements();
elements.trigger('mousedown');
done();
});
};
chain.mouseup = function() {
return this.addFutureAction("element '" + this.label + "' mouseup",
function($window, $document, done) {
var elements = $document.elements();
elements.trigger('mouseup');
done();
});
};
chain.query = function(fn) {
return this.addFutureAction('element ' + this.label + ' custom query',
function($window, $document, done) {
fn.call(this, $document.elements(), done);
});
};
angular.forEach(KEY_VALUE_METHODS, function(methodName) {
chain[methodName] = function(name, value) {
var args = arguments,
futureName = (args.length == 1)
? "element '" + this.label + "' get " + methodName + " '" + name + "'"
: "element '" + this.label + "' set " + methodName + " '" + name + "' to " + "'" +
value + "'";
return this.addFutureAction(futureName, function($window, $document, done) {
var element = $document.elements();
done(null, element[methodName].apply(element, args));
});
};
});
angular.forEach(VALUE_METHODS, function(methodName) {
chain[methodName] = function(value) {
var args = arguments,
futureName = (args.length === 0)
? "element '" + this.label + "' " + methodName
: "element '" + this.label + "' set " + methodName + " to '" + value + "'";
return this.addFutureAction(futureName, function($window, $document, done) {
var element = $document.elements();
done(null, element[methodName].apply(element, args));
});
};
});
return function(selector, label) {
this.dsl.using(selector, label);
return chain;
};
});
/**
* Matchers for implementing specs. Follows the Jasmine spec conventions.
*/
angular.scenario.matcher('toEqual', function(expected) {
return angular.equals(this.actual, expected);
});
angular.scenario.matcher('toBe', function(expected) {
return this.actual === expected;
});
angular.scenario.matcher('toBeDefined', function() {
return angular.isDefined(this.actual);
});
angular.scenario.matcher('toBeTruthy', function() {
return this.actual;
});
angular.scenario.matcher('toBeFalsy', function() {
return !this.actual;
});
angular.scenario.matcher('toMatch', function(expected) {
return new RegExp(expected).test(this.actual);
});
angular.scenario.matcher('toBeNull', function() {
return this.actual === null;
});
angular.scenario.matcher('toContain', function(expected) {
return includes(this.actual, expected);
});
angular.scenario.matcher('toBeLessThan', function(expected) {
return this.actual < expected;
});
angular.scenario.matcher('toBeGreaterThan', function(expected) {
return this.actual > expected;
});
/**
* User Interface for the Scenario Runner.
*
* TODO(esprehn): This should be refactored now that ObjectModel exists
* to use angular bindings for the UI.
*/
angular.scenario.output('html', function(context, runner, model) {
var specUiMap = {},
lastStepUiMap = {};
context.append(
'<div id="header">' +
' <h1><span class="angular">AngularJS</span>: Scenario Test Runner</h1>' +
' <ul id="status-legend" class="status-display">' +
' <li class="status-error">0 Errors</li>' +
' <li class="status-failure">0 Failures</li>' +
' <li class="status-success">0 Passed</li>' +
' </ul>' +
'</div>' +
'<div id="specs">' +
' <div class="test-children"></div>' +
'</div>'
);
runner.on('InteractivePause', function(spec) {
var ui = lastStepUiMap[spec.id];
ui.find('.test-title').
html('paused... <a href="javascript:resume()">resume</a> when ready.');
});
runner.on('SpecBegin', function(spec) {
var ui = findContext(spec);
ui.find('> .tests').append(
'<li class="status-pending test-it"></li>'
);
ui = ui.find('> .tests li:last');
ui.append(
'<div class="test-info">' +
' <p class="test-title">' +
' <span class="timer-result"></span>' +
' <span class="test-name"></span>' +
' </p>' +
'</div>' +
'<div class="scrollpane">' +
' <ol class="test-actions"></ol>' +
'</div>'
);
ui.find('> .test-info .test-name').text(spec.name);
ui.find('> .test-info').click(function() {
var scrollpane = ui.find('> .scrollpane');
var actions = scrollpane.find('> .test-actions');
var name = context.find('> .test-info .test-name');
if (actions.find(':visible').length) {
actions.hide();
name.removeClass('open').addClass('closed');
} else {
actions.show();
scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight'));
name.removeClass('closed').addClass('open');
}
});
specUiMap[spec.id] = ui;
});
runner.on('SpecError', function(spec, error) {
var ui = specUiMap[spec.id];
ui.append('<pre></pre>');
ui.find('> pre').text(formatException(error));
});
runner.on('SpecEnd', function(spec) {
var ui = specUiMap[spec.id];
spec = model.getSpec(spec.id);
ui.removeClass('status-pending');
ui.addClass('status-' + spec.status);
ui.find("> .test-info .timer-result").text(spec.duration + "ms");
if (spec.status === 'success') {
ui.find('> .test-info .test-name').addClass('closed');
ui.find('> .scrollpane .test-actions').hide();
}
updateTotals(spec.status);
});
runner.on('StepBegin', function(spec, step) {
var ui = specUiMap[spec.id];
spec = model.getSpec(spec.id);
step = spec.getLastStep();
ui.find('> .scrollpane .test-actions').append('<li class="status-pending"></li>');
var stepUi = lastStepUiMap[spec.id] = ui.find('> .scrollpane .test-actions li:last');
stepUi.append(
'<div class="timer-result"></div>' +
'<div class="test-title"></div>'
);
stepUi.find('> .test-title').text(step.name);
var scrollpane = stepUi.parents('.scrollpane');
scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight'));
});
runner.on('StepFailure', function(spec, step, error) {
var ui = lastStepUiMap[spec.id];
addError(ui, step.line, error);
});
runner.on('StepError', function(spec, step, error) {
var ui = lastStepUiMap[spec.id];
addError(ui, step.line, error);
});
runner.on('StepEnd', function(spec, step) {
var stepUi = lastStepUiMap[spec.id];
spec = model.getSpec(spec.id);
step = spec.getLastStep();
stepUi.find('.timer-result').text(step.duration + 'ms');
stepUi.removeClass('status-pending');
stepUi.addClass('status-' + step.status);
var scrollpane = specUiMap[spec.id].find('> .scrollpane');
scrollpane.attr('scrollTop', scrollpane.attr('scrollHeight'));
});
/**
* Finds the context of a spec block defined by the passed definition.
*
* @param {Object} The definition created by the Describe object.
*/
function findContext(spec) {
var currentContext = context.find('#specs');
angular.forEach(model.getDefinitionPath(spec), function(defn) {
var id = 'describe-' + defn.id;
if (!context.find('#' + id).length) {
currentContext.find('> .test-children').append(
'<div class="test-describe" id="' + id + '">' +
' <h2></h2>' +
' <div class="test-children"></div>' +
' <ul class="tests"></ul>' +
'</div>'
);
context.find('#' + id).find('> h2').text('describe: ' + defn.name);
}
currentContext = context.find('#' + id);
});
return context.find('#describe-' + spec.definition.id);
}
/**
* Updates the test counter for the status.
*
* @param {string} the status.
*/
function updateTotals(status) {
var legend = context.find('#status-legend .status-' + status);
var parts = legend.text().split(' ');
var value = (parts[0] * 1) + 1;
legend.text(value + ' ' + parts[1]);
}
/**
* Add an error to a step.
*
* @param {Object} The JQuery wrapped context
* @param {function()} fn() that should return the file/line number of the error
* @param {Object} the error.
*/
function addError(context, line, error) {
context.find('.test-title').append('<pre></pre>');
var message = _jQuery.trim(line() + '\n\n' + formatException(error));
context.find('.test-title pre:last').text(message);
}
});
/**
* Generates JSON output into a context.
*/
angular.scenario.output('json', function(context, runner, model) {
model.on('RunnerEnd', function() {
context.text(angular.toJson(model.value));
});
});
/**
* Generates XML output into a context.
*/
angular.scenario.output('xml', function(context, runner, model) {
var $ = function(args) {return new context.init(args);};
model.on('RunnerEnd', function() {
var scenario = $('<scenario></scenario>');
context.append(scenario);
serializeXml(scenario, model.value);
});
/**
* Convert the tree into XML.
*
* @param {Object} context jQuery context to add the XML to.
* @param {Object} tree node to serialize
*/
function serializeXml(context, tree) {
angular.forEach(tree.children, function(child) {
var describeContext = $('<describe></describe>');
describeContext.attr('id', child.id);
describeContext.attr('name', child.name);
context.append(describeContext);
serializeXml(describeContext, child);
});
var its = $('<its></its>');
context.append(its);
angular.forEach(tree.specs, function(spec) {
var it = $('<it></it>');
it.attr('id', spec.id);
it.attr('name', spec.name);
it.attr('duration', spec.duration);
it.attr('status', spec.status);
its.append(it);
angular.forEach(spec.steps, function(step) {
var stepContext = $('<step></step>');
stepContext.attr('name', step.name);
stepContext.attr('duration', step.duration);
stepContext.attr('status', step.status);
it.append(stepContext);
if (step.error) {
var error = $('<error></error>');
stepContext.append(error);
error.text(formatException(step.error));
}
});
});
}
});
/**
* Creates a global value $result with the result of the runner.
*/
angular.scenario.output('object', function(context, runner, model) {
runner.$window.$result = model.value;
});
bindJQuery();
publishExternalAPI(angular);
var $runner = new angular.scenario.Runner(window),
scripts = document.getElementsByTagName('script'),
script = scripts[scripts.length - 1],
config = {};
angular.forEach(script.attributes, function(attr) {
var match = attr.name.match(/ng[:\-](.*)/);
if (match) {
config[match[1]] = attr.value || true;
}
});
if (config.autotest) {
JQLite(document).ready(function() {
angular.scenario.setUpAndRun(config);
});
}
})(window, document);
!angular.$$csp() && angular.element(document).find('head').prepend('<style type="text/css">@charset "UTF-8";\n\n[ng\\:cloak], [ng-cloak], [data-ng-cloak], [x-ng-cloak],\n.ng-cloak, .x-ng-cloak,\n.ng-hide {\n display: none !important;\n}\n\nng\\:form {\n display: block;\n}\n\n/* The styles below ensure that the CSS transition will ALWAYS\n * animate and close. A nasty bug occurs with CSS transitions where\n * when the active class isn\'t set, or if the active class doesn\'t\n * contain any styles to transition to, then, if ngAnimate is used,\n * it will appear as if the webpage is broken due to the forever hanging\n * animations. The clip (!ie) and zoom (ie) CSS properties are used\n * since they trigger a transition without making the browser\n * animate anything and they\'re both highly underused CSS properties */\n.ng-animate-start { clip:rect(0, auto, auto, 0); -ms-zoom:1.0001; }\n.ng-animate-active { clip:rect(-1px, auto, auto, 0); -ms-zoom:1; }\n</style>');
!angular.$$csp() && angular.element(document).find('head').prepend('<style type="text/css">@charset "UTF-8";\n/* CSS Document */\n\n/** Structure */\nbody {\n font-family: Arial, sans-serif;\n margin: 0;\n font-size: 14px;\n}\n\n#system-error {\n font-size: 1.5em;\n text-align: center;\n}\n\n#json, #xml {\n display: none;\n}\n\n#header {\n position: fixed;\n width: 100%;\n}\n\n#specs {\n padding-top: 50px;\n}\n\n#header .angular {\n font-family: Courier New, monospace;\n font-weight: bold;\n}\n\n#header h1 {\n font-weight: normal;\n float: left;\n font-size: 30px;\n line-height: 30px;\n margin: 0;\n padding: 10px 10px;\n height: 30px;\n}\n\n#application h2,\n#specs h2 {\n margin: 0;\n padding: 0.5em;\n font-size: 1.1em;\n}\n\n#status-legend {\n margin-top: 10px;\n margin-right: 10px;\n}\n\n#header,\n#application,\n.test-info,\n.test-actions li {\n overflow: hidden;\n}\n\n#application {\n margin: 10px;\n}\n\n#application iframe {\n width: 100%;\n height: 758px;\n}\n\n#application .popout {\n float: right;\n}\n\n#application iframe {\n border: none;\n}\n\n.tests li,\n.test-actions li,\n.test-it li,\n.test-it ol,\n.status-display {\n list-style-type: none;\n}\n\n.tests,\n.test-it ol,\n.status-display {\n margin: 0;\n padding: 0;\n}\n\n.test-info {\n margin-left: 1em;\n margin-top: 0.5em;\n border-radius: 8px 0 0 8px;\n -webkit-border-radius: 8px 0 0 8px;\n -moz-border-radius: 8px 0 0 8px;\n cursor: pointer;\n}\n\n.test-info:hover .test-name {\n text-decoration: underline;\n}\n\n.test-info .closed:before {\n content: \'\\25b8\\00A0\';\n}\n\n.test-info .open:before {\n content: \'\\25be\\00A0\';\n font-weight: bold;\n}\n\n.test-it ol {\n margin-left: 2.5em;\n}\n\n.status-display,\n.status-display li {\n float: right;\n}\n\n.status-display li {\n padding: 5px 10px;\n}\n\n.timer-result,\n.test-title {\n display: inline-block;\n margin: 0;\n padding: 4px;\n}\n\n.test-actions .test-title,\n.test-actions .test-result {\n display: table-cell;\n padding-left: 0.5em;\n padding-right: 0.5em;\n}\n\n.test-actions {\n display: table;\n}\n\n.test-actions li {\n display: table-row;\n}\n\n.timer-result {\n width: 4em;\n padding: 0 10px;\n text-align: right;\n font-family: monospace;\n}\n\n.test-it pre,\n.test-actions pre {\n clear: left;\n color: black;\n margin-left: 6em;\n}\n\n.test-describe {\n padding-bottom: 0.5em;\n}\n\n.test-describe .test-describe {\n margin: 5px 5px 10px 2em;\n}\n\n.test-actions .status-pending .test-title:before {\n content: \'\\00bb\\00A0\';\n}\n\n.scrollpane {\n max-height: 20em;\n overflow: auto;\n}\n\n/** Colors */\n\n#header {\n background-color: #F2C200;\n}\n\n#specs h2 {\n border-top: 2px solid #BABAD1;\n}\n\n#specs h2,\n#application h2 {\n background-color: #efefef;\n}\n\n#application {\n border: 1px solid #BABAD1;\n}\n\n.test-describe .test-describe {\n border-left: 1px solid #BABAD1;\n border-right: 1px solid #BABAD1;\n border-bottom: 1px solid #BABAD1;\n}\n\n.status-display {\n border: 1px solid #777;\n}\n\n.status-display .status-pending,\n.status-pending .test-info {\n background-color: #F9EEBC;\n}\n\n.status-display .status-success,\n.status-success .test-info {\n background-color: #B1D7A1;\n}\n\n.status-display .status-failure,\n.status-failure .test-info {\n background-color: #FF8286;\n}\n\n.status-display .status-error,\n.status-error .test-info {\n background-color: black;\n color: white;\n}\n\n.test-actions .status-success .test-title {\n color: #30B30A;\n}\n\n.test-actions .status-failure .test-title {\n color: #DF0000;\n}\n\n.test-actions .status-error .test-title {\n color: black;\n}\n\n.test-actions .timer-result {\n color: #888;\n}\n</style>'); |
packages/material-ui-icons/src/NfcRounded.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M20 2H4c-1.1 0-2 .9-2 2v16c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V4c0-1.1-.9-2-2-2zm-1 18H5c-.55 0-1-.45-1-1V5c0-.55.45-1 1-1h14c.55 0 1 .45 1 1v14c0 .55-.45 1-1 1zM16 6h-3c-1.1 0-2 .9-2 2v2.28c-.6.35-1 .98-1 1.72 0 1.1.9 2 2 2s2-.9 2-2c0-.74-.4-1.38-1-1.72V8h3v7c0 .55-.45 1-1 1H9c-.55 0-1-.45-1-1V8h1c.55 0 1-.45 1-1s-.45-1-1-1H8c-1.1 0-2 .9-2 2v8c0 1.1.9 2 2 2h8c1.1 0 2-.9 2-2V8c0-1.1-.9-2-2-2z" /></g></React.Fragment>
, 'NfcRounded');
|
ajax/libs/react/0.12.0-rc1/react-with-addons.js | ekeneijeoma/cdnjs | /**
* React (with addons) v0.12.0-rc1
*/
!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.React=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(_dereq_,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 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_("./LinkedStateMixin");
var React = _dereq_("./React");
var ReactComponentWithPureRenderMixin =
_dereq_("./ReactComponentWithPureRenderMixin");
var ReactCSSTransitionGroup = _dereq_("./ReactCSSTransitionGroup");
var ReactTransitionGroup = _dereq_("./ReactTransitionGroup");
var ReactUpdates = _dereq_("./ReactUpdates");
var cx = _dereq_("./cx");
var cloneWithProps = _dereq_("./cloneWithProps");
var update = _dereq_("./update");
React.addons = {
CSSTransitionGroup: ReactCSSTransitionGroup,
LinkedStateMixin: LinkedStateMixin,
PureRenderMixin: ReactComponentWithPureRenderMixin,
TransitionGroup: ReactTransitionGroup,
batchedUpdates: ReactUpdates.batchedUpdates,
classSet: cx,
cloneWithProps: cloneWithProps,
update: update
};
if ("production" !== "development") {
React.addons.Perf = _dereq_("./ReactDefaultPerf");
React.addons.TestUtils = _dereq_("./ReactTestUtils");
}
module.exports = React;
},{"./LinkedStateMixin":25,"./React":31,"./ReactCSSTransitionGroup":34,"./ReactComponentWithPureRenderMixin":39,"./ReactDefaultPerf":56,"./ReactTestUtils":86,"./ReactTransitionGroup":90,"./ReactUpdates":91,"./cloneWithProps":113,"./cx":118,"./update":159}],2:[function(_dereq_,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 AutoFocusMixin
* @typechecks static-only
*/
"use strict";
var focusNode = _dereq_("./focusNode");
var AutoFocusMixin = {
componentDidMount: function() {
if (this.props.autoFocus) {
focusNode(this.getDOMNode());
}
}
};
module.exports = AutoFocusMixin;
},{"./focusNode":125}],3:[function(_dereq_,module,exports){
/**
* Copyright 2013 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
* @typechecks static-only
*/
"use strict";
var EventConstants = _dereq_("./EventConstants");
var EventPropagators = _dereq_("./EventPropagators");
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
var SyntheticInputEvent = _dereq_("./SyntheticInputEvent");
var keyOf = _dereq_("./keyOf");
var canUseTextInputEvent = (
ExecutionEnvironment.canUseDOM &&
'TextEvent' in window &&
!('documentMode' in document || isPresto())
);
/**
* 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
]
}
};
// Track characters inserted via keypress and composition events.
var fallbackChars = null;
// 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)
);
}
/**
* 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.
*/
var BeforeInputEventPlugin = {
eventTypes: eventTypes,
/**
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @see {EventPluginHub.extractEvents}
*/
extractEvents: function(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent) {
var chars;
if (canUseTextInputEvent) {
switch (topLevelType) {
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;
}
hasSpaceKeypress = true;
chars = SPACEBAR_CHAR;
break;
case topLevelTypes.topTextInput:
// Record the characters to be added to the DOM.
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;
}
// Otherwise, carry on.
break;
default:
// For other native event types, do nothing.
return;
}
} else {
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.
fallbackChars = null;
break;
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)) {
fallbackChars = String.fromCharCode(nativeEvent.which);
}
break;
case topLevelTypes.topCompositionEnd:
fallbackChars = nativeEvent.data;
break;
}
// If no changes have occurred to the fallback string, no relevant
// event has fired and we're done.
if (fallbackChars === null) {
return;
}
chars = fallbackChars;
}
// If no characters are being inserted, no BeforeInput event should
// be fired.
if (!chars) {
return;
}
var event = SyntheticInputEvent.getPooled(
eventTypes.beforeInput,
topLevelTargetID,
nativeEvent
);
event.data = chars;
fallbackChars = null;
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
}
};
module.exports = BeforeInputEventPlugin;
},{"./EventConstants":17,"./EventPropagators":22,"./ExecutionEnvironment":23,"./SyntheticInputEvent":101,"./keyOf":147}],4:[function(_dereq_,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 CSSCore
* @typechecks
*/
var invariant = _dereq_("./invariant");
/**
* 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) {
("production" !== "development" ? invariant(
!/\s/.test(className),
'CSSCore.addClass takes only a single class name. "%s" contains ' +
'multiple classes.', className
) : invariant(!/\s/.test(className)));
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) {
("production" !== "development" ? invariant(
!/\s/.test(className),
'CSSCore.removeClass takes only a single class name. "%s" contains ' +
'multiple classes.', className
) : invariant(!/\s/.test(className)));
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) {
("production" !== "development" ? invariant(
!/\s/.test(className),
'CSS.hasClass takes only a single class name.'
) : invariant(!/\s/.test(className)));
if (element.classList) {
return !!className && element.classList.contains(className);
}
return (' ' + element.className + ' ').indexOf(' ' + className + ' ') > -1;
}
};
module.exports = CSSCore;
},{"./invariant":140}],5:[function(_dereq_,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 CSSProperty
*/
"use strict";
/**
* CSS properties which accept numbers but are not in units of "px".
*/
var isUnitlessNumber = {
columnCount: true,
fillOpacity: true,
flex: true,
flexGrow: true,
flexShrink: true,
fontWeight: true,
lineClamp: true,
lineHeight: true,
opacity: true,
order: true,
orphans: true,
widows: true,
zIndex: true,
zoom: true
};
/**
* @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: {
backgroundImage: true,
backgroundPosition: true,
backgroundRepeat: true,
backgroundColor: true
},
border: {
borderWidth: true,
borderStyle: true,
borderColor: true
},
borderBottom: {
borderBottomWidth: true,
borderBottomStyle: true,
borderBottomColor: true
},
borderLeft: {
borderLeftWidth: true,
borderLeftStyle: true,
borderLeftColor: true
},
borderRight: {
borderRightWidth: true,
borderRightStyle: true,
borderRightColor: true
},
borderTop: {
borderTopWidth: true,
borderTopStyle: true,
borderTopColor: true
},
font: {
fontStyle: true,
fontVariant: true,
fontWeight: true,
fontSize: true,
lineHeight: true,
fontFamily: true
}
};
var CSSProperty = {
isUnitlessNumber: isUnitlessNumber,
shorthandPropertyExpansions: shorthandPropertyExpansions
};
module.exports = CSSProperty;
},{}],6:[function(_dereq_,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 CSSPropertyOperations
* @typechecks static-only
*/
"use strict";
var CSSProperty = _dereq_("./CSSProperty");
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
var camelizeStyleName = _dereq_("./camelizeStyleName");
var dangerousStyleValue = _dereq_("./dangerousStyleValue");
var hyphenateStyleName = _dereq_("./hyphenateStyleName");
var memoizeStringOnly = _dereq_("./memoizeStringOnly");
var warning = _dereq_("./warning");
var processStyleName = memoizeStringOnly(function(styleName) {
return hyphenateStyleName(styleName);
});
var styleFloatAccessor = 'cssFloat';
if (ExecutionEnvironment.canUseDOM) {
// IE8 only supports accessing cssFloat (standard) as styleFloat
if (document.documentElement.style.cssFloat === undefined) {
styleFloatAccessor = 'styleFloat';
}
}
if ("production" !== "development") {
var warnedStyleNames = {};
var warnHyphenatedStyleName = function(name) {
if (warnedStyleNames.hasOwnProperty(name) && warnedStyleNames[name]) {
return;
}
warnedStyleNames[name] = true;
("production" !== "development" ? warning(
false,
'Unsupported style property ' + name + '. Did you mean ' +
camelizeStyleName(name) + '?'
) : null);
};
}
/**
* 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
* @return {?string}
*/
createMarkupForStyles: function(styles) {
var serialized = '';
for (var styleName in styles) {
if (!styles.hasOwnProperty(styleName)) {
continue;
}
if ("production" !== "development") {
if (styleName.indexOf('-') > -1) {
warnHyphenatedStyleName(styleName);
}
}
var styleValue = styles[styleName];
if (styleValue != null) {
serialized += processStyleName(styleName) + ':';
serialized += dangerousStyleValue(styleName, styleValue) + ';';
}
}
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) {
var style = node.style;
for (var styleName in styles) {
if (!styles.hasOwnProperty(styleName)) {
continue;
}
if ("production" !== "development") {
if (styleName.indexOf('-') > -1) {
warnHyphenatedStyleName(styleName);
}
}
var styleValue = dangerousStyleValue(styleName, styles[styleName]);
if (styleName === 'float') {
styleName = styleFloatAccessor;
}
if (styleValue) {
style[styleName] = styleValue;
} else {
var expansion = 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] = '';
}
}
}
}
};
module.exports = CSSPropertyOperations;
},{"./CSSProperty":5,"./ExecutionEnvironment":23,"./camelizeStyleName":112,"./dangerousStyleValue":119,"./hyphenateStyleName":138,"./memoizeStringOnly":149,"./warning":160}],7:[function(_dereq_,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 CallbackQueue
*/
"use strict";
var PooledClass = _dereq_("./PooledClass");
var assign = _dereq_("./Object.assign");
var invariant = _dereq_("./invariant");
/**
* 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) {
("production" !== "development" ? invariant(
callbacks.length === contexts.length,
"Mismatched list of contexts in callback queue"
) : invariant(callbacks.length === contexts.length));
this._callbacks = null;
this._contexts = null;
for (var i = 0, l = callbacks.length; i < l; i++) {
callbacks[i].call(contexts[i]);
}
callbacks.length = 0;
contexts.length = 0;
}
},
/**
* 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;
},{"./Object.assign":29,"./PooledClass":30,"./invariant":140}],8:[function(_dereq_,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 ChangeEventPlugin
*/
"use strict";
var EventConstants = _dereq_("./EventConstants");
var EventPluginHub = _dereq_("./EventPluginHub");
var EventPropagators = _dereq_("./EventPropagators");
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
var ReactUpdates = _dereq_("./ReactUpdates");
var SyntheticEvent = _dereq_("./SyntheticEvent");
var isEventSupported = _dereq_("./isEventSupported");
var isTextInputElement = _dereq_("./isTextInputElement");
var keyOf = _dereq_("./keyOf");
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 activeElementID = null;
var activeElementValue = null;
var activeElementValueProp = null;
/**
* SECTION: handle `change` event
*/
function shouldUseChangeEvent(elem) {
return (
elem.nodeName === 'SELECT' ||
(elem.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,
activeElementID,
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();
}
function startWatchingForChangeEventIE8(target, targetID) {
activeElement = target;
activeElementID = targetID;
activeElement.attachEvent('onchange', manualDispatchChangeEvent);
}
function stopWatchingForChangeEventIE8() {
if (!activeElement) {
return;
}
activeElement.detachEvent('onchange', manualDispatchChangeEvent);
activeElement = null;
activeElementID = null;
}
function getTargetIDForChangeEvent(
topLevelType,
topLevelTarget,
topLevelTargetID) {
if (topLevelType === topLevelTypes.topChange) {
return topLevelTargetID;
}
}
function handleEventsForChangeEventIE8(
topLevelType,
topLevelTarget,
topLevelTargetID) {
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(topLevelTarget, topLevelTargetID);
} 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
isInputEventSupported = isEventSupported('input') && (
!('documentMode' in document) || document.documentMode > 9
);
}
/**
* (For old IE.) 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 old IE.) 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, targetID) {
activeElement = target;
activeElementID = targetID;
activeElementValue = target.value;
activeElementValueProp = Object.getOwnPropertyDescriptor(
target.constructor.prototype,
'value'
);
Object.defineProperty(activeElement, 'value', newValueProp);
activeElement.attachEvent('onpropertychange', handlePropertyChange);
}
/**
* (For old IE.) 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;
activeElement.detachEvent('onpropertychange', handlePropertyChange);
activeElement = null;
activeElementID = null;
activeElementValue = null;
activeElementValueProp = null;
}
/**
* (For old IE.) 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 getTargetIDForInputEvent(
topLevelType,
topLevelTarget,
topLevelTargetID) {
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 topLevelTargetID;
}
}
// For IE8 and IE9.
function handleEventsForInputEventIE(
topLevelType,
topLevelTarget,
topLevelTargetID) {
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, 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(topLevelTarget, topLevelTargetID);
} else if (topLevelType === topLevelTypes.topBlur) {
stopWatchingForValueChange();
}
}
// For IE8 and IE9.
function getTargetIDForInputEventIE(
topLevelType,
topLevelTarget,
topLevelTargetID) {
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 activeElementID;
}
}
}
/**
* 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 === 'INPUT' &&
(elem.type === 'checkbox' || elem.type === 'radio')
);
}
function getTargetIDForClickEvent(
topLevelType,
topLevelTarget,
topLevelTargetID) {
if (topLevelType === topLevelTypes.topClick) {
return topLevelTargetID;
}
}
/**
* 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,
/**
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @see {EventPluginHub.extractEvents}
*/
extractEvents: function(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent) {
var getTargetIDFunc, handleEventFunc;
if (shouldUseChangeEvent(topLevelTarget)) {
if (doesChangeEventBubble) {
getTargetIDFunc = getTargetIDForChangeEvent;
} else {
handleEventFunc = handleEventsForChangeEventIE8;
}
} else if (isTextInputElement(topLevelTarget)) {
if (isInputEventSupported) {
getTargetIDFunc = getTargetIDForInputEvent;
} else {
getTargetIDFunc = getTargetIDForInputEventIE;
handleEventFunc = handleEventsForInputEventIE;
}
} else if (shouldUseClickEvent(topLevelTarget)) {
getTargetIDFunc = getTargetIDForClickEvent;
}
if (getTargetIDFunc) {
var targetID = getTargetIDFunc(
topLevelType,
topLevelTarget,
topLevelTargetID
);
if (targetID) {
var event = SyntheticEvent.getPooled(
eventTypes.change,
targetID,
nativeEvent
);
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
}
}
if (handleEventFunc) {
handleEventFunc(
topLevelType,
topLevelTarget,
topLevelTargetID
);
}
}
};
module.exports = ChangeEventPlugin;
},{"./EventConstants":17,"./EventPluginHub":19,"./EventPropagators":22,"./ExecutionEnvironment":23,"./ReactUpdates":91,"./SyntheticEvent":99,"./isEventSupported":141,"./isTextInputElement":143,"./keyOf":147}],9:[function(_dereq_,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 ClientReactRootIndex
* @typechecks
*/
"use strict";
var nextReactRootIndex = 0;
var ClientReactRootIndex = {
createReactRootIndex: function() {
return nextReactRootIndex++;
}
};
module.exports = ClientReactRootIndex;
},{}],10:[function(_dereq_,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 CompositionEventPlugin
* @typechecks static-only
*/
"use strict";
var EventConstants = _dereq_("./EventConstants");
var EventPropagators = _dereq_("./EventPropagators");
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
var ReactInputSelection = _dereq_("./ReactInputSelection");
var SyntheticCompositionEvent = _dereq_("./SyntheticCompositionEvent");
var getTextContentAccessor = _dereq_("./getTextContentAccessor");
var keyOf = _dereq_("./keyOf");
var END_KEYCODES = [9, 13, 27, 32]; // Tab, Return, Esc, Space
var START_KEYCODE = 229;
var useCompositionEvent = (
ExecutionEnvironment.canUseDOM &&
'CompositionEvent' in window
);
// In IE9+, we have access to composition events, but the data supplied
// by the native compositionend event may be incorrect. In Korean, for example,
// the compositionend event contains only one character regardless of
// how many characters have been composed since compositionstart.
// We therefore use the fallback data while still using the native
// events as triggers.
var useFallbackData = (
!useCompositionEvent ||
(
'documentMode' in document &&
document.documentMode > 8 &&
document.documentMode <= 11
)
);
var topLevelTypes = EventConstants.topLevelTypes;
var currentComposition = null;
// Events and their corresponding property names.
var eventTypes = {
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
]
}
};
/**
* 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 isFallbackStart(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 isFallbackEnd(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;
}
}
/**
* Helper class stores information about selection and document state
* so we can figure out what changed at a later date.
*
* @param {DOMEventTarget} root
*/
function FallbackCompositionState(root) {
this.root = root;
this.startSelection = ReactInputSelection.getSelection(root);
this.startValue = this.getText();
}
/**
* Get current text of input.
*
* @return {string}
*/
FallbackCompositionState.prototype.getText = function() {
return this.root.value || this.root[getTextContentAccessor()];
};
/**
* Text that has changed since the start of composition.
*
* @return {string}
*/
FallbackCompositionState.prototype.getData = function() {
var endValue = this.getText();
var prefixLength = this.startSelection.start;
var suffixLength = this.startValue.length - this.startSelection.end;
return endValue.substr(
prefixLength,
endValue.length - suffixLength - prefixLength
);
};
/**
* This plugin creates `onCompositionStart`, `onCompositionUpdate` and
* `onCompositionEnd` events on inputs, textareas and contentEditable
* nodes.
*/
var CompositionEventPlugin = {
eventTypes: eventTypes,
/**
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @see {EventPluginHub.extractEvents}
*/
extractEvents: function(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent) {
var eventType;
var data;
if (useCompositionEvent) {
eventType = getCompositionEventType(topLevelType);
} else if (!currentComposition) {
if (isFallbackStart(topLevelType, nativeEvent)) {
eventType = eventTypes.compositionStart;
}
} else if (isFallbackEnd(topLevelType, nativeEvent)) {
eventType = eventTypes.compositionEnd;
}
if (useFallbackData) {
// The current composition is stored statically and must not be
// overwritten while composition continues.
if (!currentComposition && eventType === eventTypes.compositionStart) {
currentComposition = new FallbackCompositionState(topLevelTarget);
} else if (eventType === eventTypes.compositionEnd) {
if (currentComposition) {
data = currentComposition.getData();
currentComposition = null;
}
}
}
if (eventType) {
var event = SyntheticCompositionEvent.getPooled(
eventType,
topLevelTargetID,
nativeEvent
);
if (data) {
// Inject data generated from fallback path into the synthetic event.
// This matches the property of native CompositionEventInterface.
event.data = data;
}
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
}
}
};
module.exports = CompositionEventPlugin;
},{"./EventConstants":17,"./EventPropagators":22,"./ExecutionEnvironment":23,"./ReactInputSelection":65,"./SyntheticCompositionEvent":97,"./getTextContentAccessor":135,"./keyOf":147}],11:[function(_dereq_,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 DOMChildrenOperations
* @typechecks static-only
*/
"use strict";
var Danger = _dereq_("./Danger");
var ReactMultiChildUpdateTypes = _dereq_("./ReactMultiChildUpdateTypes");
var getTextContentAccessor = _dereq_("./getTextContentAccessor");
var invariant = _dereq_("./invariant");
/**
* The DOM property to use when setting text content.
*
* @type {string}
* @private
*/
var textContentAccessor = getTextContentAccessor();
/**
* 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
*/
function insertChildAt(parentNode, childNode, index) {
// By exploiting arrays returning `undefined` for an undefined index, we can
// rely exclusively on `insertBefore(node, null)` instead of also using
// `appendChild(node)`. However, using `undefined` is not allowed by all
// browsers so we must replace it with `null`.
parentNode.insertBefore(
childNode,
parentNode.childNodes[index] || null
);
}
var updateTextContent;
if (textContentAccessor === 'textContent') {
/**
* Sets the text content of `node` to `text`.
*
* @param {DOMElement} node Node to change
* @param {string} text New text content
*/
updateTextContent = function(node, text) {
node.textContent = text;
};
} else {
/**
* Sets the text content of `node` to `text`.
*
* @param {DOMElement} node Node to change
* @param {string} text New text content
*/
updateTextContent = function(node, text) {
// In order to preserve newlines correctly, we can't use .innerText to set
// the contents (see #1080), so we empty the element then append a text node
while (node.firstChild) {
node.removeChild(node.firstChild);
}
if (text) {
var doc = node.ownerDocument || document;
node.appendChild(doc.createTextNode(text));
}
};
}
/**
* Operations for updating with DOM children.
*/
var DOMChildrenOperations = {
dangerouslyReplaceNodeWithMarkup: Danger.dangerouslyReplaceNodeWithMarkup,
updateTextContent: updateTextContent,
/**
* 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.
* @param {array<string>} markupList List of markup strings.
* @internal
*/
processUpdates: function(updates, markupList) {
var update;
// Mapping from parent IDs to initial child orderings.
var initialChildren = null;
// List of children that will be moved or removed.
var updatedChildren = null;
for (var i = 0; update = updates[i]; i++) {
if (update.type === ReactMultiChildUpdateTypes.MOVE_EXISTING ||
update.type === ReactMultiChildUpdateTypes.REMOVE_NODE) {
var updatedIndex = update.fromIndex;
var updatedChild = update.parentNode.childNodes[updatedIndex];
var parentID = update.parentID;
("production" !== "development" ? invariant(
updatedChild,
'processUpdates(): Unable to find child %s of element. This ' +
'probably means the DOM was unexpectedly mutated (e.g., by the ' +
'browser), usually due to forgetting a <tbody> when using tables, ' +
'nesting tags like <form>, <p>, or <a>, or using non-SVG elements '+
'in an <svg> parent. Try inspecting the child nodes of the element ' +
'with React ID `%s`.',
updatedIndex,
parentID
) : invariant(updatedChild));
initialChildren = initialChildren || {};
initialChildren[parentID] = initialChildren[parentID] || [];
initialChildren[parentID][updatedIndex] = updatedChild;
updatedChildren = updatedChildren || [];
updatedChildren.push(updatedChild);
}
}
var renderedMarkup = Danger.dangerouslyRenderMarkup(markupList);
// Remove updated children first so that `toIndex` is consistent.
if (updatedChildren) {
for (var j = 0; j < updatedChildren.length; j++) {
updatedChildren[j].parentNode.removeChild(updatedChildren[j]);
}
}
for (var k = 0; update = updates[k]; k++) {
switch (update.type) {
case ReactMultiChildUpdateTypes.INSERT_MARKUP:
insertChildAt(
update.parentNode,
renderedMarkup[update.markupIndex],
update.toIndex
);
break;
case ReactMultiChildUpdateTypes.MOVE_EXISTING:
insertChildAt(
update.parentNode,
initialChildren[update.parentID][update.fromIndex],
update.toIndex
);
break;
case ReactMultiChildUpdateTypes.TEXT_CONTENT:
updateTextContent(
update.parentNode,
update.textContent
);
break;
case ReactMultiChildUpdateTypes.REMOVE_NODE:
// Already removed by the for-loop above.
break;
}
}
}
};
module.exports = DOMChildrenOperations;
},{"./Danger":14,"./ReactMultiChildUpdateTypes":72,"./getTextContentAccessor":135,"./invariant":140}],12:[function(_dereq_,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 DOMProperty
* @typechecks static-only
*/
/*jslint bitwise: true */
"use strict";
var invariant = _dereq_("./invariant");
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_ATTRIBUTE: 0x1,
MUST_USE_PROPERTY: 0x2,
HAS_SIDE_EFFECTS: 0x4,
HAS_BOOLEAN_VALUE: 0x8,
HAS_NUMERIC_VALUE: 0x10,
HAS_POSITIVE_NUMERIC_VALUE: 0x20 | 0x10,
HAS_OVERLOADED_BOOLEAN_VALUE: 0x40,
/**
* 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.
*
* 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 Properties = domPropertyConfig.Properties || {};
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) {
("production" !== "development" ? invariant(
!DOMProperty.isStandardName.hasOwnProperty(propName),
'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(!DOMProperty.isStandardName.hasOwnProperty(propName)));
DOMProperty.isStandardName[propName] = true;
var lowerCased = propName.toLowerCase();
DOMProperty.getPossibleStandardName[lowerCased] = propName;
if (DOMAttributeNames.hasOwnProperty(propName)) {
var attributeName = DOMAttributeNames[propName];
DOMProperty.getPossibleStandardName[attributeName] = propName;
DOMProperty.getAttributeName[propName] = attributeName;
} else {
DOMProperty.getAttributeName[propName] = lowerCased;
}
DOMProperty.getPropertyName[propName] =
DOMPropertyNames.hasOwnProperty(propName) ?
DOMPropertyNames[propName] :
propName;
if (DOMMutationMethods.hasOwnProperty(propName)) {
DOMProperty.getMutationMethod[propName] = DOMMutationMethods[propName];
} else {
DOMProperty.getMutationMethod[propName] = null;
}
var propConfig = Properties[propName];
DOMProperty.mustUseAttribute[propName] =
checkMask(propConfig, DOMPropertyInjection.MUST_USE_ATTRIBUTE);
DOMProperty.mustUseProperty[propName] =
checkMask(propConfig, DOMPropertyInjection.MUST_USE_PROPERTY);
DOMProperty.hasSideEffects[propName] =
checkMask(propConfig, DOMPropertyInjection.HAS_SIDE_EFFECTS);
DOMProperty.hasBooleanValue[propName] =
checkMask(propConfig, DOMPropertyInjection.HAS_BOOLEAN_VALUE);
DOMProperty.hasNumericValue[propName] =
checkMask(propConfig, DOMPropertyInjection.HAS_NUMERIC_VALUE);
DOMProperty.hasPositiveNumericValue[propName] =
checkMask(propConfig, DOMPropertyInjection.HAS_POSITIVE_NUMERIC_VALUE);
DOMProperty.hasOverloadedBooleanValue[propName] =
checkMask(propConfig, DOMPropertyInjection.HAS_OVERLOADED_BOOLEAN_VALUE);
("production" !== "development" ? invariant(
!DOMProperty.mustUseAttribute[propName] ||
!DOMProperty.mustUseProperty[propName],
'DOMProperty: Cannot require using both attribute and property: %s',
propName
) : invariant(!DOMProperty.mustUseAttribute[propName] ||
!DOMProperty.mustUseProperty[propName]));
("production" !== "development" ? invariant(
DOMProperty.mustUseProperty[propName] ||
!DOMProperty.hasSideEffects[propName],
'DOMProperty: Properties that have side effects must use property: %s',
propName
) : invariant(DOMProperty.mustUseProperty[propName] ||
!DOMProperty.hasSideEffects[propName]));
("production" !== "development" ? invariant(
!!DOMProperty.hasBooleanValue[propName] +
!!DOMProperty.hasNumericValue[propName] +
!!DOMProperty.hasOverloadedBooleanValue[propName] <= 1,
'DOMProperty: Value can be one of boolean, overloaded boolean, or ' +
'numeric value, but not a combination: %s',
propName
) : invariant(!!DOMProperty.hasBooleanValue[propName] +
!!DOMProperty.hasNumericValue[propName] +
!!DOMProperty.hasOverloadedBooleanValue[propName] <= 1));
}
}
};
var defaultValueCache = {};
/**
* 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',
/**
* Checks whether a property name is a standard property.
* @type {Object}
*/
isStandardName: {},
/**
* Mapping from lowercase property names to the properly cased version, used
* to warn in the case of missing properties.
* @type {Object}
*/
getPossibleStandardName: {},
/**
* 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 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: {},
/**
* Whether the property should be removed when set to a falsey value.
* @type {Object}
*/
hasBooleanValue: {},
/**
* Whether the property must be numeric or parse as a
* numeric and should be removed when set to a falsey value.
* @type {Object}
*/
hasNumericValue: {},
/**
* Whether the property must be positive numeric or parse as a positive
* numeric and should be removed when set to a falsey value.
* @type {Object}
*/
hasPositiveNumericValue: {},
/**
* 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.
* @type {Object}
*/
hasOverloadedBooleanValue: {},
/**
* 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;
},
/**
* Returns the default property value for a DOM property (i.e., not an
* attribute). Most default values are '' or false, but not all. Worse yet,
* some (in particular, `type`) vary depending on the type of element.
*
* TODO: Is it better to grab all the possible properties when creating an
* element to avoid having to create the same element twice?
*/
getDefaultValueForProperty: function(nodeName, prop) {
var nodeDefaults = defaultValueCache[nodeName];
var testElement;
if (!nodeDefaults) {
defaultValueCache[nodeName] = nodeDefaults = {};
}
if (!(prop in nodeDefaults)) {
testElement = document.createElement(nodeName);
nodeDefaults[prop] = testElement[prop];
}
return nodeDefaults[prop];
},
injection: DOMPropertyInjection
};
module.exports = DOMProperty;
},{"./invariant":140}],13:[function(_dereq_,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 DOMPropertyOperations
* @typechecks static-only
*/
"use strict";
var DOMProperty = _dereq_("./DOMProperty");
var escapeTextForBrowser = _dereq_("./escapeTextForBrowser");
var memoizeStringOnly = _dereq_("./memoizeStringOnly");
var warning = _dereq_("./warning");
function shouldIgnoreValue(name, value) {
return value == null ||
(DOMProperty.hasBooleanValue[name] && !value) ||
(DOMProperty.hasNumericValue[name] && isNaN(value)) ||
(DOMProperty.hasPositiveNumericValue[name] && (value < 1)) ||
(DOMProperty.hasOverloadedBooleanValue[name] && value === false);
}
var processAttributeNameAndPrefix = memoizeStringOnly(function(name) {
return escapeTextForBrowser(name) + '="';
});
if ("production" !== "development") {
var reactProps = {
children: true,
dangerouslySetInnerHTML: true,
key: true,
ref: true
};
var warnedProperties = {};
var warnUnknownProperty = function(name) {
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.
("production" !== "development" ? warning(
standardName == null,
'Unknown DOM property ' + name + '. Did you mean ' + standardName + '?'
) : null);
};
}
/**
* 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 processAttributeNameAndPrefix(DOMProperty.ID_ATTRIBUTE_NAME) +
escapeTextForBrowser(id) + '"';
},
/**
* 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.hasOwnProperty(name) &&
DOMProperty.isStandardName[name]) {
if (shouldIgnoreValue(name, value)) {
return '';
}
var attributeName = DOMProperty.getAttributeName[name];
if (DOMProperty.hasBooleanValue[name] ||
(DOMProperty.hasOverloadedBooleanValue[name] && value === true)) {
return escapeTextForBrowser(attributeName);
}
return processAttributeNameAndPrefix(attributeName) +
escapeTextForBrowser(value) + '"';
} else if (DOMProperty.isCustomAttribute(name)) {
if (value == null) {
return '';
}
return processAttributeNameAndPrefix(name) +
escapeTextForBrowser(value) + '"';
} else if ("production" !== "development") {
warnUnknownProperty(name);
}
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.hasOwnProperty(name) &&
DOMProperty.isStandardName[name]) {
var mutationMethod = DOMProperty.getMutationMethod[name];
if (mutationMethod) {
mutationMethod(node, value);
} else if (shouldIgnoreValue(name, value)) {
this.deleteValueForProperty(node, name);
} else if (DOMProperty.mustUseAttribute[name]) {
// `setAttribute` with objects becomes only `[object]` in IE8/9,
// ('' + value) makes it output the correct toString()-value.
node.setAttribute(DOMProperty.getAttributeName[name], '' + value);
} else {
var propName = DOMProperty.getPropertyName[name];
// Must explicitly cast values for HAS_SIDE_EFFECTS-properties to the
// property type before comparing; only `value` does and is string.
if (!DOMProperty.hasSideEffects[name] ||
('' + node[propName]) !== ('' + value)) {
// Contrary to `setAttribute`, object properties are properly
// `toString`ed by IE8/9.
node[propName] = value;
}
}
} else if (DOMProperty.isCustomAttribute(name)) {
if (value == null) {
node.removeAttribute(name);
} else {
node.setAttribute(name, '' + value);
}
} else if ("production" !== "development") {
warnUnknownProperty(name);
}
},
/**
* Deletes the value for a property on a node.
*
* @param {DOMElement} node
* @param {string} name
*/
deleteValueForProperty: function(node, name) {
if (DOMProperty.isStandardName.hasOwnProperty(name) &&
DOMProperty.isStandardName[name]) {
var mutationMethod = DOMProperty.getMutationMethod[name];
if (mutationMethod) {
mutationMethod(node, undefined);
} else if (DOMProperty.mustUseAttribute[name]) {
node.removeAttribute(DOMProperty.getAttributeName[name]);
} else {
var propName = DOMProperty.getPropertyName[name];
var defaultValue = DOMProperty.getDefaultValueForProperty(
node.nodeName,
propName
);
if (!DOMProperty.hasSideEffects[name] ||
('' + node[propName]) !== defaultValue) {
node[propName] = defaultValue;
}
}
} else if (DOMProperty.isCustomAttribute(name)) {
node.removeAttribute(name);
} else if ("production" !== "development") {
warnUnknownProperty(name);
}
}
};
module.exports = DOMPropertyOperations;
},{"./DOMProperty":12,"./escapeTextForBrowser":123,"./memoizeStringOnly":149,"./warning":160}],14:[function(_dereq_,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 Danger
* @typechecks static-only
*/
/*jslint evil: true, sub: true */
"use strict";
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
var createNodesFromMarkup = _dereq_("./createNodesFromMarkup");
var emptyFunction = _dereq_("./emptyFunction");
var getMarkupWrap = _dereq_("./getMarkupWrap");
var invariant = _dereq_("./invariant");
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) {
("production" !== "development" ? invariant(
ExecutionEnvironment.canUseDOM,
'dangerouslyRenderMarkup(...): Cannot render markup in a worker ' +
'thread. Make sure `window` and `document` are available globally ' +
'before requiring React when unit testing or use ' +
'React.renderToString for server rendering.'
) : invariant(ExecutionEnvironment.canUseDOM));
var nodeName;
var markupByNodeName = {};
// Group markup by `nodeName` if a wrap is necessary, else by '*'.
for (var i = 0; i < markupList.length; i++) {
("production" !== "development" ? invariant(
markupList[i],
'dangerouslyRenderMarkup(...): Missing markup.'
) : invariant(markupList[i]));
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.
for (var 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 (i = 0; i < renderNodes.length; ++i) {
var renderNode = renderNodes[i];
if (renderNode.hasAttribute &&
renderNode.hasAttribute(RESULT_INDEX_ATTR)) {
resultIndex = +renderNode.getAttribute(RESULT_INDEX_ATTR);
renderNode.removeAttribute(RESULT_INDEX_ATTR);
("production" !== "development" ? invariant(
!resultList.hasOwnProperty(resultIndex),
'Danger: Assigning to an already-occupied result index.'
) : invariant(!resultList.hasOwnProperty(resultIndex)));
resultList[resultIndex] = renderNode;
// This should match resultList.length and markupList.length when
// we're done.
resultListAssignmentCount += 1;
} else if ("production" !== "development") {
console.error(
"Danger: Discarding unexpected node:",
renderNode
);
}
}
}
// Although resultList was populated out of order, it should now be a dense
// array.
("production" !== "development" ? invariant(
resultListAssignmentCount === resultList.length,
'Danger: Did not assign to every index of resultList.'
) : invariant(resultListAssignmentCount === resultList.length));
("production" !== "development" ? invariant(
resultList.length === markupList.length,
'Danger: Expected markup to render %s nodes, but rendered %s.',
markupList.length,
resultList.length
) : invariant(resultList.length === markupList.length));
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) {
("production" !== "development" ? invariant(
ExecutionEnvironment.canUseDOM,
'dangerouslyReplaceNodeWithMarkup(...): Cannot render markup in a ' +
'worker thread. Make sure `window` and `document` are available ' +
'globally before requiring React when unit testing or use ' +
'React.renderToString for server rendering.'
) : invariant(ExecutionEnvironment.canUseDOM));
("production" !== "development" ? invariant(markup, 'dangerouslyReplaceNodeWithMarkup(...): Missing markup.') : invariant(markup));
("production" !== "development" ? invariant(
oldChild.tagName.toLowerCase() !== 'html',
'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 renderComponentToString().'
) : invariant(oldChild.tagName.toLowerCase() !== 'html'));
var newChild = createNodesFromMarkup(markup, emptyFunction)[0];
oldChild.parentNode.replaceChild(newChild, oldChild);
}
};
module.exports = Danger;
},{"./ExecutionEnvironment":23,"./createNodesFromMarkup":117,"./emptyFunction":121,"./getMarkupWrap":132,"./invariant":140}],15:[function(_dereq_,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 DefaultEventPluginOrder
*/
"use strict";
var keyOf = _dereq_("./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({ChangeEventPlugin: null}),
keyOf({SelectEventPlugin: null}),
keyOf({CompositionEventPlugin: null}),
keyOf({BeforeInputEventPlugin: null}),
keyOf({AnalyticsEventPlugin: null}),
keyOf({MobileSafariClickEventPlugin: null})
];
module.exports = DefaultEventPluginOrder;
},{"./keyOf":147}],16:[function(_dereq_,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 EnterLeaveEventPlugin
* @typechecks static-only
*/
"use strict";
var EventConstants = _dereq_("./EventConstants");
var EventPropagators = _dereq_("./EventPropagators");
var SyntheticMouseEvent = _dereq_("./SyntheticMouseEvent");
var ReactMount = _dereq_("./ReactMount");
var keyOf = _dereq_("./keyOf");
var topLevelTypes = EventConstants.topLevelTypes;
var getFirstReactDOM = ReactMount.getFirstReactDOM;
var eventTypes = {
mouseEnter: {
registrationName: keyOf({onMouseEnter: null}),
dependencies: [
topLevelTypes.topMouseOut,
topLevelTypes.topMouseOver
]
},
mouseLeave: {
registrationName: keyOf({onMouseLeave: null}),
dependencies: [
topLevelTypes.topMouseOut,
topLevelTypes.topMouseOver
]
}
};
var extractedEvents = [null, null];
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.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @see {EventPluginHub.extractEvents}
*/
extractEvents: function(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent) {
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 (topLevelTarget.window === topLevelTarget) {
// `topLevelTarget` is probably a window object.
win = topLevelTarget;
} else {
// TODO: Figure out why `ownerDocument` is sometimes undefined in IE8.
var doc = topLevelTarget.ownerDocument;
if (doc) {
win = doc.defaultView || doc.parentWindow;
} else {
win = window;
}
}
var from, to;
if (topLevelType === topLevelTypes.topMouseOut) {
from = topLevelTarget;
to =
getFirstReactDOM(nativeEvent.relatedTarget || nativeEvent.toElement) ||
win;
} else {
from = win;
to = topLevelTarget;
}
if (from === to) {
// Nothing pertains to our managed components.
return null;
}
var fromID = from ? ReactMount.getID(from) : '';
var toID = to ? ReactMount.getID(to) : '';
var leave = SyntheticMouseEvent.getPooled(
eventTypes.mouseLeave,
fromID,
nativeEvent
);
leave.type = 'mouseleave';
leave.target = from;
leave.relatedTarget = to;
var enter = SyntheticMouseEvent.getPooled(
eventTypes.mouseEnter,
toID,
nativeEvent
);
enter.type = 'mouseenter';
enter.target = to;
enter.relatedTarget = from;
EventPropagators.accumulateEnterLeaveDispatches(leave, enter, fromID, toID);
extractedEvents[0] = leave;
extractedEvents[1] = enter;
return extractedEvents;
}
};
module.exports = EnterLeaveEventPlugin;
},{"./EventConstants":17,"./EventPropagators":22,"./ReactMount":70,"./SyntheticMouseEvent":103,"./keyOf":147}],17:[function(_dereq_,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 EventConstants
*/
"use strict";
var keyMirror = _dereq_("./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,
topCompositionEnd: null,
topCompositionStart: null,
topCompositionUpdate: null,
topContextMenu: null,
topCopy: null,
topCut: null,
topDoubleClick: null,
topDrag: null,
topDragEnd: null,
topDragEnter: null,
topDragExit: null,
topDragLeave: null,
topDragOver: null,
topDragStart: null,
topDrop: null,
topError: null,
topFocus: null,
topInput: null,
topKeyDown: null,
topKeyPress: null,
topKeyUp: null,
topLoad: null,
topMouseDown: null,
topMouseMove: null,
topMouseOut: null,
topMouseOver: null,
topMouseUp: null,
topPaste: null,
topReset: null,
topScroll: null,
topSelectionChange: null,
topSubmit: null,
topTextInput: null,
topTouchCancel: null,
topTouchEnd: null,
topTouchMove: null,
topTouchStart: null,
topWheel: null
});
var EventConstants = {
topLevelTypes: topLevelTypes,
PropagationPhases: PropagationPhases
};
module.exports = EventConstants;
},{"./keyMirror":146}],18:[function(_dereq_,module,exports){
/**
* Copyright 2013-2014 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
* @typechecks
*/
var emptyFunction = _dereq_("./emptyFunction");
/**
* 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) {
if ("production" !== "development") {
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
};
} else {
target.addEventListener(eventType, callback, true);
return {
remove: function() {
target.removeEventListener(eventType, callback, true);
}
};
}
},
registerDefault: function() {}
};
module.exports = EventListener;
},{"./emptyFunction":121}],19:[function(_dereq_,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 EventPluginHub
*/
"use strict";
var EventPluginRegistry = _dereq_("./EventPluginRegistry");
var EventPluginUtils = _dereq_("./EventPluginUtils");
var accumulateInto = _dereq_("./accumulateInto");
var forEachAccumulated = _dereq_("./forEachAccumulated");
var invariant = _dereq_("./invariant");
/**
* 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.
* @private
*/
var executeDispatchesAndRelease = function(event) {
if (event) {
var executeDispatch = EventPluginUtils.executeDispatch;
// Plugins can provide custom behavior when dispatching events.
var PluginModule = EventPluginRegistry.getPluginModuleForEvent(event);
if (PluginModule && PluginModule.executeDispatch) {
executeDispatch = PluginModule.executeDispatch;
}
EventPluginUtils.executeDispatchesInOrder(event, executeDispatch);
if (!event.isPersistent()) {
event.constructor.release(event);
}
}
};
/**
* - `InstanceHandle`: [required] Module that performs logical traversals of DOM
* hierarchy given ids of the logical DOM elements involved.
*/
var InstanceHandle = null;
function validateInstanceHandle() {
var invalid = !InstanceHandle||
!InstanceHandle.traverseTwoPhase ||
!InstanceHandle.traverseEnterLeave;
if (invalid) {
throw new Error('InstanceHandle not injected before use!');
}
}
/**
* 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 {object} InjectedMount
* @public
*/
injectMount: EventPluginUtils.injection.injectMount,
/**
* @param {object} InjectedInstanceHandle
* @public
*/
injectInstanceHandle: function(InjectedInstanceHandle) {
InstanceHandle = InjectedInstanceHandle;
if ("production" !== "development") {
validateInstanceHandle();
}
},
getInstanceHandle: function() {
if ("production" !== "development") {
validateInstanceHandle();
}
return InstanceHandle;
},
/**
* @param {array} InjectedEventPluginOrder
* @public
*/
injectEventPluginOrder: EventPluginRegistry.injectEventPluginOrder,
/**
* @param {object} injectedNamesToPlugins Map from names to plugin modules.
*/
injectEventPluginsByName: EventPluginRegistry.injectEventPluginsByName
},
eventNameDispatchConfigs: EventPluginRegistry.eventNameDispatchConfigs,
registrationNameModules: EventPluginRegistry.registrationNameModules,
/**
* Stores `listener` at `listenerBank[registrationName][id]`. Is idempotent.
*
* @param {string} id ID of the DOM element.
* @param {string} registrationName Name of listener (e.g. `onClick`).
* @param {?function} listener The callback to store.
*/
putListener: function(id, registrationName, listener) {
("production" !== "development" ? invariant(
!listener || typeof listener === 'function',
'Expected %s listener to be a function, instead got type %s',
registrationName, typeof listener
) : invariant(!listener || typeof listener === 'function'));
var bankForRegistrationName =
listenerBank[registrationName] || (listenerBank[registrationName] = {});
bankForRegistrationName[id] = listener;
},
/**
* @param {string} id ID of the DOM element.
* @param {string} registrationName Name of listener (e.g. `onClick`).
* @return {?function} The stored callback.
*/
getListener: function(id, registrationName) {
var bankForRegistrationName = listenerBank[registrationName];
return bankForRegistrationName && bankForRegistrationName[id];
},
/**
* Deletes a listener from the registration bank.
*
* @param {string} id ID of the DOM element.
* @param {string} registrationName Name of listener (e.g. `onClick`).
*/
deleteListener: function(id, registrationName) {
var bankForRegistrationName = listenerBank[registrationName];
if (bankForRegistrationName) {
delete bankForRegistrationName[id];
}
},
/**
* Deletes all listeners for the DOM element with the supplied ID.
*
* @param {string} id ID of the DOM element.
*/
deleteAllListeners: function(id) {
for (var registrationName in listenerBank) {
delete listenerBank[registrationName][id];
}
},
/**
* Allows registered plugins an opportunity to extract events from top-level
* native browser events.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @internal
*/
extractEvents: function(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent) {
var events;
var plugins = EventPluginRegistry.plugins;
for (var i = 0, l = plugins.length; i < l; i++) {
// Not every plugin in the ordering may be loaded at runtime.
var possiblePlugin = plugins[i];
if (possiblePlugin) {
var extractedEvents = possiblePlugin.extractEvents(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent
);
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() {
// Set `eventQueue` to null before processing it so that we can tell if more
// events get enqueued while processing.
var processingEventQueue = eventQueue;
eventQueue = null;
forEachAccumulated(processingEventQueue, executeDispatchesAndRelease);
("production" !== "development" ? invariant(
!eventQueue,
'processEventQueue(): Additional events were enqueued while processing ' +
'an event queue. Support for this has not yet been implemented.'
) : invariant(!eventQueue));
},
/**
* These are needed for tests only. Do not use!
*/
__purge: function() {
listenerBank = {};
},
__getListenerBank: function() {
return listenerBank;
}
};
module.exports = EventPluginHub;
},{"./EventPluginRegistry":20,"./EventPluginUtils":21,"./accumulateInto":109,"./forEachAccumulated":126,"./invariant":140}],20:[function(_dereq_,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 EventPluginRegistry
* @typechecks static-only
*/
"use strict";
var invariant = _dereq_("./invariant");
/**
* 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);
("production" !== "development" ? invariant(
pluginIndex > -1,
'EventPluginRegistry: Cannot inject event plugins that do not exist in ' +
'the plugin ordering, `%s`.',
pluginName
) : invariant(pluginIndex > -1));
if (EventPluginRegistry.plugins[pluginIndex]) {
continue;
}
("production" !== "development" ? invariant(
PluginModule.extractEvents,
'EventPluginRegistry: Event plugins must implement an `extractEvents` ' +
'method, but `%s` does not.',
pluginName
) : invariant(PluginModule.extractEvents));
EventPluginRegistry.plugins[pluginIndex] = PluginModule;
var publishedEvents = PluginModule.eventTypes;
for (var eventName in publishedEvents) {
("production" !== "development" ? invariant(
publishEventForPlugin(
publishedEvents[eventName],
PluginModule,
eventName
),
'EventPluginRegistry: Failed to publish event `%s` for plugin `%s`.',
eventName,
pluginName
) : invariant(publishEventForPlugin(
publishedEvents[eventName],
PluginModule,
eventName
)));
}
}
}
/**
* 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) {
("production" !== "development" ? invariant(
!EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName),
'EventPluginHub: More than one plugin attempted to publish the same ' +
'event name, `%s`.',
eventName
) : invariant(!EventPluginRegistry.eventNameDispatchConfigs.hasOwnProperty(eventName)));
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) {
("production" !== "development" ? invariant(
!EventPluginRegistry.registrationNameModules[registrationName],
'EventPluginHub: More than one plugin attempted to publish the same ' +
'registration name, `%s`.',
registrationName
) : invariant(!EventPluginRegistry.registrationNameModules[registrationName]));
EventPluginRegistry.registrationNameModules[registrationName] = PluginModule;
EventPluginRegistry.registrationNameDependencies[registrationName] =
PluginModule.eventTypes[eventName].dependencies;
}
/**
* 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: {},
/**
* 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) {
("production" !== "development" ? invariant(
!EventPluginOrder,
'EventPluginRegistry: Cannot inject event plugin ordering more than ' +
'once. You are likely trying to load more than one copy of React.'
) : invariant(!EventPluginOrder));
// 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) {
("production" !== "development" ? invariant(
!namesToPlugins[pluginName],
'EventPluginRegistry: Cannot inject two different event plugins ' +
'using the same name, `%s`.',
pluginName
) : invariant(!namesToPlugins[pluginName]));
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];
}
}
}
};
module.exports = EventPluginRegistry;
},{"./invariant":140}],21:[function(_dereq_,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 EventPluginUtils
*/
"use strict";
var EventConstants = _dereq_("./EventConstants");
var invariant = _dereq_("./invariant");
/**
* Injected dependencies:
*/
/**
* - `Mount`: [required] Module that can convert between React dom IDs and
* actual node references.
*/
var injection = {
Mount: null,
injectMount: function(InjectedMount) {
injection.Mount = InjectedMount;
if ("production" !== "development") {
("production" !== "development" ? invariant(
InjectedMount && InjectedMount.getNode,
'EventPluginUtils.injection.injectMount(...): Injected Mount module ' +
'is missing getNode.'
) : invariant(InjectedMount && InjectedMount.getNode));
}
}
};
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 ("production" !== "development") {
validateEventDispatches = function(event) {
var dispatchListeners = event._dispatchListeners;
var dispatchIDs = event._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;
("production" !== "development" ? invariant(
idsIsArr === listenersIsArr && IDsLen === listenersLen,
'EventPluginUtils: Invalid `event`.'
) : invariant(idsIsArr === listenersIsArr && IDsLen === listenersLen));
};
}
/**
* Invokes `cb(event, 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(event, cb) {
var dispatchListeners = event._dispatchListeners;
var dispatchIDs = event._dispatchIDs;
if ("production" !== "development") {
validateEventDispatches(event);
}
if (Array.isArray(dispatchListeners)) {
for (var i = 0; i < dispatchListeners.length; i++) {
if (event.isPropagationStopped()) {
break;
}
// Listeners and IDs are two parallel arrays that are always in sync.
cb(event, dispatchListeners[i], dispatchIDs[i]);
}
} else if (dispatchListeners) {
cb(event, dispatchListeners, dispatchIDs);
}
}
/**
* Default implementation of PluginModule.executeDispatch().
* @param {SyntheticEvent} SyntheticEvent to handle
* @param {function} Application-level callback
* @param {string} domID DOM id to pass to the callback.
*/
function executeDispatch(event, listener, domID) {
event.currentTarget = injection.Mount.getNode(domID);
var returnValue = listener(event, domID);
event.currentTarget = null;
return returnValue;
}
/**
* Standard/simple iteration through an event's collected dispatches.
*/
function executeDispatchesInOrder(event, executeDispatch) {
forEachEventDispatch(event, executeDispatch);
event._dispatchListeners = null;
event._dispatchIDs = null;
}
/**
* Standard/simple iteration through an event's collected dispatches, but stops
* at the first dispatch execution returning true, and returns that id.
*
* @return 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 dispatchIDs = event._dispatchIDs;
if ("production" !== "development") {
validateEventDispatches(event);
}
if (Array.isArray(dispatchListeners)) {
for (var i = 0; i < dispatchListeners.length; i++) {
if (event.isPropagationStopped()) {
break;
}
// Listeners and IDs are two parallel arrays that are always in sync.
if (dispatchListeners[i](event, dispatchIDs[i])) {
return dispatchIDs[i];
}
}
} else if (dispatchListeners) {
if (dispatchListeners(event, dispatchIDs)) {
return dispatchIDs;
}
}
return null;
}
/**
* @see executeDispatchesInOrderStopAtTrueImpl
*/
function executeDispatchesInOrderStopAtTrue(event) {
var ret = executeDispatchesInOrderStopAtTrueImpl(event);
event._dispatchIDs = 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 ("production" !== "development") {
validateEventDispatches(event);
}
var dispatchListener = event._dispatchListeners;
var dispatchID = event._dispatchIDs;
("production" !== "development" ? invariant(
!Array.isArray(dispatchListener),
'executeDirectDispatch(...): Invalid `event`.'
) : invariant(!Array.isArray(dispatchListener)));
var res = dispatchListener ?
dispatchListener(event, dispatchID) :
null;
event._dispatchListeners = null;
event._dispatchIDs = null;
return res;
}
/**
* @param {SyntheticEvent} event
* @return {bool} 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,
executeDispatch: executeDispatch,
executeDispatchesInOrder: executeDispatchesInOrder,
executeDispatchesInOrderStopAtTrue: executeDispatchesInOrderStopAtTrue,
hasDispatches: hasDispatches,
injection: injection,
useTouchEvents: false
};
module.exports = EventPluginUtils;
},{"./EventConstants":17,"./invariant":140}],22:[function(_dereq_,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 EventPropagators
*/
"use strict";
var EventConstants = _dereq_("./EventConstants");
var EventPluginHub = _dereq_("./EventPluginHub");
var accumulateInto = _dereq_("./accumulateInto");
var forEachAccumulated = _dereq_("./forEachAccumulated");
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(id, event, propagationPhase) {
var registrationName =
event.dispatchConfig.phasedRegistrationNames[propagationPhase];
return getListener(id, 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(domID, upwards, event) {
if ("production" !== "development") {
if (!domID) {
throw new Error('Dispatching id must not be null');
}
}
var phase = upwards ? PropagationPhases.bubbled : PropagationPhases.captured;
var listener = listenerAtPhase(domID, event, phase);
if (listener) {
event._dispatchListeners =
accumulateInto(event._dispatchListeners, listener);
event._dispatchIDs = accumulateInto(event._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(event) {
if (event && event.dispatchConfig.phasedRegistrationNames) {
EventPluginHub.injection.getInstanceHandle().traverseTwoPhase(
event.dispatchMarker,
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(id, ignoredDirection, event) {
if (event && event.dispatchConfig.registrationName) {
var registrationName = event.dispatchConfig.registrationName;
var listener = getListener(id, registrationName);
if (listener) {
event._dispatchListeners =
accumulateInto(event._dispatchListeners, listener);
event._dispatchIDs = accumulateInto(event._dispatchIDs, id);
}
}
}
/**
* Accumulates dispatches on an `SyntheticEvent`, but only for the
* `dispatchMarker`.
* @param {SyntheticEvent} event
*/
function accumulateDirectDispatchesSingle(event) {
if (event && event.dispatchConfig.registrationName) {
accumulateDispatches(event.dispatchMarker, null, event);
}
}
function accumulateTwoPhaseDispatches(events) {
forEachAccumulated(events, accumulateTwoPhaseDispatchesSingle);
}
function accumulateEnterLeaveDispatches(leave, enter, fromID, toID) {
EventPluginHub.injection.getInstanceHandle().traverseEnterLeave(
fromID,
toID,
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,
accumulateDirectDispatches: accumulateDirectDispatches,
accumulateEnterLeaveDispatches: accumulateEnterLeaveDispatches
};
module.exports = EventPropagators;
},{"./EventConstants":17,"./EventPluginHub":19,"./accumulateInto":109,"./forEachAccumulated":126}],23:[function(_dereq_,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 ExecutionEnvironment
*/
/*jslint evil: true */
"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;
},{}],24:[function(_dereq_,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 HTMLDOMPropertyConfig
*/
/*jslint bitwise: true*/
"use strict";
var DOMProperty = _dereq_("./DOMProperty");
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
var MUST_USE_ATTRIBUTE = DOMProperty.injection.MUST_USE_ATTRIBUTE;
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 hasSVG;
if (ExecutionEnvironment.canUseDOM) {
var implementation = document.implementation;
hasSVG = (
implementation &&
implementation.hasFeature &&
implementation.hasFeature(
'http://www.w3.org/TR/SVG11/feature#BasicStructure',
'1.1'
)
);
}
var HTMLDOMPropertyConfig = {
isCustomAttribute: RegExp.prototype.test.bind(
/^(data|aria)-[a-z_][a-z\d_.\-]*$/
),
Properties: {
/**
* Standard Properties
*/
accept: null,
acceptCharset: null,
accessKey: null,
action: null,
allowFullScreen: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
allowTransparency: MUST_USE_ATTRIBUTE,
alt: null,
async: HAS_BOOLEAN_VALUE,
autoComplete: null,
// autoFocus is polyfilled/normalized by AutoFocusMixin
// autoFocus: HAS_BOOLEAN_VALUE,
autoPlay: HAS_BOOLEAN_VALUE,
cellPadding: null,
cellSpacing: null,
charSet: MUST_USE_ATTRIBUTE,
checked: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
classID: MUST_USE_ATTRIBUTE,
// To set className on SVG elements, it's necessary to use .setAttribute;
// this works on HTML elements too in all browsers except IE8. Conveniently,
// IE8 doesn't support SVG and so we can simply use the attribute in
// browsers that support SVG and the property in browsers that don't,
// regardless of whether the element is HTML or SVG.
className: hasSVG ? MUST_USE_ATTRIBUTE : MUST_USE_PROPERTY,
cols: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE,
colSpan: null,
content: null,
contentEditable: null,
contextMenu: MUST_USE_ATTRIBUTE,
controls: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
coords: null,
crossOrigin: null,
data: null, // For `<object />` acts as `src`.
dateTime: MUST_USE_ATTRIBUTE,
defer: HAS_BOOLEAN_VALUE,
dir: null,
disabled: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
download: HAS_OVERLOADED_BOOLEAN_VALUE,
draggable: null,
encType: null,
form: MUST_USE_ATTRIBUTE,
formNoValidate: HAS_BOOLEAN_VALUE,
frameBorder: MUST_USE_ATTRIBUTE,
height: MUST_USE_ATTRIBUTE,
hidden: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
href: null,
hrefLang: null,
htmlFor: null,
httpEquiv: null,
icon: null,
id: MUST_USE_PROPERTY,
label: null,
lang: null,
list: MUST_USE_ATTRIBUTE,
loop: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
manifest: MUST_USE_ATTRIBUTE,
max: null,
maxLength: MUST_USE_ATTRIBUTE,
media: MUST_USE_ATTRIBUTE,
mediaGroup: null,
method: null,
min: null,
multiple: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
muted: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
name: null,
noValidate: HAS_BOOLEAN_VALUE,
open: null,
pattern: null,
placeholder: null,
poster: null,
preload: null,
radioGroup: null,
readOnly: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
rel: null,
required: HAS_BOOLEAN_VALUE,
role: MUST_USE_ATTRIBUTE,
rows: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE,
rowSpan: null,
sandbox: null,
scope: null,
scrolling: null,
seamless: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE,
selected: MUST_USE_PROPERTY | HAS_BOOLEAN_VALUE,
shape: null,
size: MUST_USE_ATTRIBUTE | HAS_POSITIVE_NUMERIC_VALUE,
sizes: MUST_USE_ATTRIBUTE,
span: HAS_POSITIVE_NUMERIC_VALUE,
spellCheck: null,
src: null,
srcDoc: MUST_USE_PROPERTY,
srcSet: MUST_USE_ATTRIBUTE,
start: HAS_NUMERIC_VALUE,
step: null,
style: null,
tabIndex: null,
target: null,
title: null,
type: null,
useMap: null,
value: MUST_USE_PROPERTY | HAS_SIDE_EFFECTS,
width: MUST_USE_ATTRIBUTE,
wmode: MUST_USE_ATTRIBUTE,
/**
* Non-standard Properties
*/
autoCapitalize: null, // Supported in Mobile Safari for keyboard hints
autoCorrect: null, // Supported in Mobile Safari for keyboard hints
itemProp: MUST_USE_ATTRIBUTE, // Microdata: http://schema.org/docs/gs.html
itemScope: MUST_USE_ATTRIBUTE | HAS_BOOLEAN_VALUE, // Microdata: http://schema.org/docs/gs.html
itemType: MUST_USE_ATTRIBUTE, // Microdata: http://schema.org/docs/gs.html
property: null // Supports OG in meta tags
},
DOMAttributeNames: {
acceptCharset: 'accept-charset',
className: 'class',
htmlFor: 'for',
httpEquiv: 'http-equiv'
},
DOMPropertyNames: {
autoCapitalize: 'autocapitalize',
autoComplete: 'autocomplete',
autoCorrect: 'autocorrect',
autoFocus: 'autofocus',
autoPlay: 'autoplay',
encType: 'enctype',
hrefLang: 'hreflang',
radioGroup: 'radiogroup',
spellCheck: 'spellcheck',
srcDoc: 'srcdoc',
srcSet: 'srcset'
}
};
module.exports = HTMLDOMPropertyConfig;
},{"./DOMProperty":12,"./ExecutionEnvironment":23}],25:[function(_dereq_,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 LinkedStateMixin
* @typechecks static-only
*/
"use strict";
var ReactLink = _dereq_("./ReactLink");
var ReactStateSetters = _dereq_("./ReactStateSetters");
/**
* 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;
},{"./ReactLink":68,"./ReactStateSetters":85}],26:[function(_dereq_,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 LinkedValueUtils
* @typechecks static-only
*/
"use strict";
var ReactPropTypes = _dereq_("./ReactPropTypes");
var invariant = _dereq_("./invariant");
var hasReadOnlyValue = {
'button': true,
'checkbox': true,
'image': true,
'hidden': true,
'radio': true,
'reset': true,
'submit': true
};
function _assertSingleLink(input) {
("production" !== "development" ? invariant(
input.props.checkedLink == null || input.props.valueLink == null,
'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(input.props.checkedLink == null || input.props.valueLink == null));
}
function _assertValueLink(input) {
_assertSingleLink(input);
("production" !== "development" ? invariant(
input.props.value == null && input.props.onChange == null,
'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(input.props.value == null && input.props.onChange == null));
}
function _assertCheckedLink(input) {
_assertSingleLink(input);
("production" !== "development" ? invariant(
input.props.checked == null && input.props.onChange == null,
'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(input.props.checked == null && input.props.onChange == null));
}
/**
* @param {SyntheticEvent} e change event to handle
*/
function _handleLinkedValueChange(e) {
/*jshint validthis:true */
this.props.valueLink.requestChange(e.target.value);
}
/**
* @param {SyntheticEvent} e change event to handle
*/
function _handleLinkedCheckChange(e) {
/*jshint validthis:true */
this.props.checkedLink.requestChange(e.target.checked);
}
/**
* Provide a linked `value` attribute for controlled forms. You should not use
* this outside of the ReactDOM controlled form components.
*/
var LinkedValueUtils = {
Mixin: {
propTypes: {
value: function(props, propName, componentName) {
if (!props[propName] ||
hasReadOnlyValue[props.type] ||
props.onChange ||
props.readOnly ||
props.disabled) {
return;
}
return new Error(
'You provided a `value` prop to a form field without an ' +
'`onChange` handler. This will render a read-only field. If ' +
'the field should be mutable use `defaultValue`. Otherwise, ' +
'set either `onChange` or `readOnly`.'
);
},
checked: function(props, propName, componentName) {
if (!props[propName] ||
props.onChange ||
props.readOnly ||
props.disabled) {
return;
}
return new Error(
'You provided a `checked` prop to a form field without an ' +
'`onChange` handler. This will render a read-only field. If ' +
'the field should be mutable use `defaultChecked`. Otherwise, ' +
'set either `onChange` or `readOnly`.'
);
},
onChange: ReactPropTypes.func
}
},
/**
* @param {ReactComponent} input Form component
* @return {*} current value of the input either from value prop or link.
*/
getValue: function(input) {
if (input.props.valueLink) {
_assertValueLink(input);
return input.props.valueLink.value;
}
return input.props.value;
},
/**
* @param {ReactComponent} input Form component
* @return {*} current checked status of the input either from checked prop
* or link.
*/
getChecked: function(input) {
if (input.props.checkedLink) {
_assertCheckedLink(input);
return input.props.checkedLink.value;
}
return input.props.checked;
},
/**
* @param {ReactComponent} input Form component
* @return {function} change callback either from onChange prop or link.
*/
getOnChange: function(input) {
if (input.props.valueLink) {
_assertValueLink(input);
return _handleLinkedValueChange;
} else if (input.props.checkedLink) {
_assertCheckedLink(input);
return _handleLinkedCheckChange;
}
return input.props.onChange;
}
};
module.exports = LinkedValueUtils;
},{"./ReactPropTypes":79,"./invariant":140}],27:[function(_dereq_,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 LocalEventTrapMixin
*/
"use strict";
var ReactBrowserEventEmitter = _dereq_("./ReactBrowserEventEmitter");
var accumulateInto = _dereq_("./accumulateInto");
var forEachAccumulated = _dereq_("./forEachAccumulated");
var invariant = _dereq_("./invariant");
function remove(event) {
event.remove();
}
var LocalEventTrapMixin = {
trapBubbledEvent:function(topLevelType, handlerBaseName) {
("production" !== "development" ? invariant(this.isMounted(), 'Must be mounted to trap events') : invariant(this.isMounted()));
var listener = ReactBrowserEventEmitter.trapBubbledEvent(
topLevelType,
handlerBaseName,
this.getDOMNode()
);
this._localEventListeners =
accumulateInto(this._localEventListeners, listener);
},
// trapCapturedEvent would look nearly identical. We don't implement that
// method because it isn't currently needed.
componentWillUnmount:function() {
if (this._localEventListeners) {
forEachAccumulated(this._localEventListeners, remove);
}
}
};
module.exports = LocalEventTrapMixin;
},{"./ReactBrowserEventEmitter":33,"./accumulateInto":109,"./forEachAccumulated":126,"./invariant":140}],28:[function(_dereq_,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 MobileSafariClickEventPlugin
* @typechecks static-only
*/
"use strict";
var EventConstants = _dereq_("./EventConstants");
var emptyFunction = _dereq_("./emptyFunction");
var topLevelTypes = EventConstants.topLevelTypes;
/**
* 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.
*
* This particular plugin works around the bug by attaching an empty click
* listener on `touchstart` (which does fire on every element).
*/
var MobileSafariClickEventPlugin = {
eventTypes: null,
/**
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @see {EventPluginHub.extractEvents}
*/
extractEvents: function(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent) {
if (topLevelType === topLevelTypes.topTouchStart) {
var target = nativeEvent.target;
if (target && !target.onclick) {
target.onclick = emptyFunction;
}
}
}
};
module.exports = MobileSafariClickEventPlugin;
},{"./EventConstants":17,"./emptyFunction":121}],29:[function(_dereq_,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;
},{}],30:[function(_dereq_,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 PooledClass
*/
"use strict";
var invariant = _dereq_("./invariant");
/**
* 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 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;
("production" !== "development" ? invariant(
instance instanceof Klass,
'Trying to release an instance into a pool of a different type.'
) : invariant(instance instanceof Klass));
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,
threeArgumentPooler: threeArgumentPooler,
fiveArgumentPooler: fiveArgumentPooler
};
module.exports = PooledClass;
},{"./invariant":140}],31:[function(_dereq_,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 React
*/
"use strict";
var DOMPropertyOperations = _dereq_("./DOMPropertyOperations");
var EventPluginUtils = _dereq_("./EventPluginUtils");
var ReactChildren = _dereq_("./ReactChildren");
var ReactComponent = _dereq_("./ReactComponent");
var ReactCompositeComponent = _dereq_("./ReactCompositeComponent");
var ReactContext = _dereq_("./ReactContext");
var ReactCurrentOwner = _dereq_("./ReactCurrentOwner");
var ReactElement = _dereq_("./ReactElement");
var ReactElementValidator = _dereq_("./ReactElementValidator");
var ReactDOM = _dereq_("./ReactDOM");
var ReactDOMComponent = _dereq_("./ReactDOMComponent");
var ReactDefaultInjection = _dereq_("./ReactDefaultInjection");
var ReactInstanceHandles = _dereq_("./ReactInstanceHandles");
var ReactLegacyElement = _dereq_("./ReactLegacyElement");
var ReactMount = _dereq_("./ReactMount");
var ReactMultiChild = _dereq_("./ReactMultiChild");
var ReactPerf = _dereq_("./ReactPerf");
var ReactPropTypes = _dereq_("./ReactPropTypes");
var ReactServerRendering = _dereq_("./ReactServerRendering");
var ReactTextComponent = _dereq_("./ReactTextComponent");
var assign = _dereq_("./Object.assign");
var deprecated = _dereq_("./deprecated");
var onlyChild = _dereq_("./onlyChild");
ReactDefaultInjection.inject();
var createElement = ReactElement.createElement;
var createFactory = ReactElement.createFactory;
if ("production" !== "development") {
createElement = ReactElementValidator.createElement;
createFactory = ReactElementValidator.createFactory;
}
// TODO: Drop legacy elements once classes no longer export these factories
createElement = ReactLegacyElement.wrapCreateElement(
createElement
);
createFactory = ReactLegacyElement.wrapCreateFactory(
createFactory
);
var render = ReactPerf.measure('React', 'render', ReactMount.render);
var React = {
Children: {
map: ReactChildren.map,
forEach: ReactChildren.forEach,
count: ReactChildren.count,
only: onlyChild
},
DOM: ReactDOM,
PropTypes: ReactPropTypes,
initializeTouchEvents: function(shouldUseTouch) {
EventPluginUtils.useTouchEvents = shouldUseTouch;
},
createClass: ReactCompositeComponent.createClass,
createElement: createElement,
createFactory: createFactory,
constructAndRenderComponent: ReactMount.constructAndRenderComponent,
constructAndRenderComponentByID: ReactMount.constructAndRenderComponentByID,
render: render,
renderToString: ReactServerRendering.renderToString,
renderToStaticMarkup: ReactServerRendering.renderToStaticMarkup,
unmountComponentAtNode: ReactMount.unmountComponentAtNode,
isValidClass: ReactLegacyElement.isValidFactory,
isValidElement: ReactElement.isValidElement,
withContext: ReactContext.withContext,
// Hook for JSX spread, don't use this for anything else.
__spread: assign,
// Deprecations (remove for 0.13)
renderComponent: deprecated(
'React',
'renderComponent',
'render',
this,
render
),
renderComponentToString: deprecated(
'React',
'renderComponentToString',
'renderToString',
this,
ReactServerRendering.renderToString
),
renderComponentToStaticMarkup: deprecated(
'React',
'renderComponentToStaticMarkup',
'renderToStaticMarkup',
this,
ReactServerRendering.renderToStaticMarkup
),
isValidComponent: deprecated(
'React',
'isValidComponent',
'isValidElement',
this,
ReactElement.isValidElement
)
};
// Inject the runtime into a devtools global hook regardless of browser.
// Allows for debugging when the hook is injected on the page.
if (
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ !== 'undefined' &&
typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.inject === 'function') {
__REACT_DEVTOOLS_GLOBAL_HOOK__.inject({
Component: ReactComponent,
CurrentOwner: ReactCurrentOwner,
DOMComponent: ReactDOMComponent,
DOMPropertyOperations: DOMPropertyOperations,
InstanceHandles: ReactInstanceHandles,
Mount: ReactMount,
MultiChild: ReactMultiChild,
TextComponent: ReactTextComponent
});
}
if ("production" !== "development") {
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
if (ExecutionEnvironment.canUseDOM && window.top === window.self) {
// If we're in Chrome, look for the devtools marker and provide a download
// link if not installed.
if (navigator.userAgent.indexOf('Chrome') > -1) {
if (typeof __REACT_DEVTOOLS_GLOBAL_HOOK__ === 'undefined') {
console.debug(
'Download the React DevTools for a better development experience: ' +
'http://fb.me/react-devtools'
);
}
}
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,
// shams
Object.create,
Object.freeze
];
for (var i = 0; i < expectedFeatures.length; i++) {
if (!expectedFeatures[i]) {
console.error(
'One or more ES5 shim/shams expected by React are not available: ' +
'http://fb.me/react-warning-polyfills'
);
break;
}
}
}
}
// Version exists only in the open-source version of React, not in Facebook's
// internal version.
React.version = '0.12.0-rc1';
module.exports = React;
},{"./DOMPropertyOperations":13,"./EventPluginUtils":21,"./ExecutionEnvironment":23,"./Object.assign":29,"./ReactChildren":36,"./ReactComponent":37,"./ReactCompositeComponent":40,"./ReactContext":41,"./ReactCurrentOwner":42,"./ReactDOM":43,"./ReactDOMComponent":45,"./ReactDefaultInjection":55,"./ReactElement":58,"./ReactElementValidator":59,"./ReactInstanceHandles":66,"./ReactLegacyElement":67,"./ReactMount":70,"./ReactMultiChild":71,"./ReactPerf":75,"./ReactPropTypes":79,"./ReactServerRendering":83,"./ReactTextComponent":87,"./deprecated":120,"./onlyChild":151}],32:[function(_dereq_,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 ReactBrowserComponentMixin
*/
"use strict";
var ReactEmptyComponent = _dereq_("./ReactEmptyComponent");
var ReactMount = _dereq_("./ReactMount");
var invariant = _dereq_("./invariant");
var ReactBrowserComponentMixin = {
/**
* Returns the DOM node rendered by this component.
*
* @return {DOMElement} The root node of this component.
* @final
* @protected
*/
getDOMNode: function() {
("production" !== "development" ? invariant(
this.isMounted(),
'getDOMNode(): A component must be mounted to have a DOM node.'
) : invariant(this.isMounted()));
if (ReactEmptyComponent.isNullComponentID(this._rootNodeID)) {
return null;
}
return ReactMount.getNode(this._rootNodeID);
}
};
module.exports = ReactBrowserComponentMixin;
},{"./ReactEmptyComponent":60,"./ReactMount":70,"./invariant":140}],33:[function(_dereq_,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 ReactBrowserEventEmitter
* @typechecks static-only
*/
"use strict";
var EventConstants = _dereq_("./EventConstants");
var EventPluginHub = _dereq_("./EventPluginHub");
var EventPluginRegistry = _dereq_("./EventPluginRegistry");
var ReactEventEmitterMixin = _dereq_("./ReactEventEmitterMixin");
var ViewportMetrics = _dereq_("./ViewportMetrics");
var assign = _dereq_("./Object.assign");
var isEventSupported = _dereq_("./isEventSupported");
/**
* 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 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 = {
topBlur: 'blur',
topChange: 'change',
topClick: 'click',
topCompositionEnd: 'compositionend',
topCompositionStart: 'compositionstart',
topCompositionUpdate: 'compositionupdate',
topContextMenu: 'contextmenu',
topCopy: 'copy',
topCut: 'cut',
topDoubleClick: 'dblclick',
topDrag: 'drag',
topDragEnd: 'dragend',
topDragEnter: 'dragenter',
topDragExit: 'dragexit',
topDragLeave: 'dragleave',
topDragOver: 'dragover',
topDragStart: 'dragstart',
topDrop: 'drop',
topFocus: 'focus',
topInput: 'input',
topKeyDown: 'keydown',
topKeyPress: 'keypress',
topKeyUp: 'keyup',
topMouseDown: 'mousedown',
topMouseMove: 'mousemove',
topMouseOut: 'mouseout',
topMouseOver: 'mouseover',
topMouseUp: 'mouseup',
topPaste: 'paste',
topScroll: 'scroll',
topSelectionChange: 'selectionchange',
topTextInput: 'textInput',
topTouchCancel: 'touchcancel',
topTouchEnd: 'touchend',
topTouchMove: 'touchmove',
topTouchStart: 'touchstart',
topWheel: 'wheel'
};
/**
* 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:
*
* ReactBrowserEventEmitter.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, l = dependencies.length; i < l; 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.
*
* NOTE: Scroll events do not bubble.
*
* @see http://www.quirksmode.org/dom/events/scroll.html
*/
ensureScrollValueMonitoring: function(){
if (!isMonitoringScrollValue) {
var refresh = ViewportMetrics.refreshScrollValues;
ReactBrowserEventEmitter.ReactEventListener.monitorScrollValue(refresh);
isMonitoringScrollValue = true;
}
},
eventNameDispatchConfigs: EventPluginHub.eventNameDispatchConfigs,
registrationNameModules: EventPluginHub.registrationNameModules,
putListener: EventPluginHub.putListener,
getListener: EventPluginHub.getListener,
deleteListener: EventPluginHub.deleteListener,
deleteAllListeners: EventPluginHub.deleteAllListeners
});
module.exports = ReactBrowserEventEmitter;
},{"./EventConstants":17,"./EventPluginHub":19,"./EventPluginRegistry":20,"./Object.assign":29,"./ReactEventEmitterMixin":62,"./ViewportMetrics":108,"./isEventSupported":141}],34:[function(_dereq_,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.
*
* @typechecks
* @providesModule ReactCSSTransitionGroup
*/
"use strict";
var React = _dereq_("./React");
var assign = _dereq_("./Object.assign");
var ReactTransitionGroup = React.createFactory(
_dereq_("./ReactTransitionGroup")
);
var ReactCSSTransitionGroupChild = React.createFactory(
_dereq_("./ReactCSSTransitionGroupChild")
);
var ReactCSSTransitionGroup = React.createClass({
displayName: 'ReactCSSTransitionGroup',
propTypes: {
transitionName: React.PropTypes.string.isRequired,
transitionEnter: React.PropTypes.bool,
transitionLeave: React.PropTypes.bool
},
getDefaultProps: function() {
return {
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 ReactCSSTransitionGroupChild(
{
name: this.props.transitionName,
enter: this.props.transitionEnter,
leave: this.props.transitionLeave
},
child
);
},
render: function() {
return (
ReactTransitionGroup(
assign({}, this.props, {childFactory: this._wrapChild})
)
);
}
});
module.exports = ReactCSSTransitionGroup;
},{"./Object.assign":29,"./React":31,"./ReactCSSTransitionGroupChild":35,"./ReactTransitionGroup":90}],35:[function(_dereq_,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.
*
* @typechecks
* @providesModule ReactCSSTransitionGroupChild
*/
"use strict";
var React = _dereq_("./React");
var CSSCore = _dereq_("./CSSCore");
var ReactTransitionEvents = _dereq_("./ReactTransitionEvents");
var onlyChild = _dereq_("./onlyChild");
// We don't remove the element from the DOM until we receive an animationend or
// transitionend event. If the user screws up and forgets to add an animation
// their node will be stuck in the DOM forever, so we detect if an animation
// does not start and if it doesn't, we just call the end listener immediately.
var TICK = 17;
var NO_EVENT_TIMEOUT = 5000;
var noEventListener = null;
if ("production" !== "development") {
noEventListener = function() {
console.warn(
'transition(): tried to perform an animation without ' +
'an animationend or transitionend event after timeout (' +
NO_EVENT_TIMEOUT + 'ms). You should either disable this ' +
'transition in JS or add a CSS animation/transition.'
);
};
}
var ReactCSSTransitionGroupChild = React.createClass({
displayName: 'ReactCSSTransitionGroupChild',
transition: function(animationType, finishCallback) {
var node = this.getDOMNode();
var className = this.props.name + '-' + animationType;
var activeClassName = className + '-active';
var noEventTimeout = null;
var endListener = function(e) {
if (e && e.target !== node) {
return;
}
if ("production" !== "development") {
clearTimeout(noEventTimeout);
}
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.
finishCallback && finishCallback();
};
ReactTransitionEvents.addEndEventListener(node, endListener);
CSSCore.addClass(node, className);
// Need to do this to actually trigger a transition.
this.queueClass(activeClassName);
if ("production" !== "development") {
noEventTimeout = setTimeout(noEventListener, NO_EVENT_TIMEOUT);
}
},
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, this.getDOMNode())
);
}
this.classNameQueue.length = 0;
this.timeout = null;
},
componentWillMount: function() {
this.classNameQueue = [];
},
componentWillUnmount: function() {
if (this.timeout) {
clearTimeout(this.timeout);
}
},
componentWillEnter: function(done) {
if (this.props.enter) {
this.transition('enter', done);
} else {
done();
}
},
componentWillLeave: function(done) {
if (this.props.leave) {
this.transition('leave', done);
} else {
done();
}
},
render: function() {
return onlyChild(this.props.children);
}
});
module.exports = ReactCSSTransitionGroupChild;
},{"./CSSCore":4,"./React":31,"./ReactTransitionEvents":89,"./onlyChild":151}],36:[function(_dereq_,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 ReactChildren
*/
"use strict";
var PooledClass = _dereq_("./PooledClass");
var traverseAllChildren = _dereq_("./traverseAllChildren");
var warning = _dereq_("./warning");
var twoArgumentPooler = PooledClass.twoArgumentPooler;
var threeArgumentPooler = PooledClass.threeArgumentPooler;
/**
* 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.forEachFunction = forEachFunction;
this.forEachContext = forEachContext;
}
PooledClass.addPoolingTo(ForEachBookKeeping, twoArgumentPooler);
function forEachSingleChild(traverseContext, child, name, i) {
var forEachBookKeeping = traverseContext;
forEachBookKeeping.forEachFunction.call(
forEachBookKeeping.forEachContext, child, i);
}
/**
* 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, mapFunction, mapContext) {
this.mapResult = mapResult;
this.mapFunction = mapFunction;
this.mapContext = mapContext;
}
PooledClass.addPoolingTo(MapBookKeeping, threeArgumentPooler);
function mapSingleChildIntoContext(traverseContext, child, name, i) {
var mapBookKeeping = traverseContext;
var mapResult = mapBookKeeping.mapResult;
var keyUnique = !mapResult.hasOwnProperty(name);
("production" !== "development" ? warning(
keyUnique,
'ReactChildren.map(...): Encountered two children with the same key, ' +
'`%s`. Child keys must be unique; when two children share a key, only ' +
'the first child will be used.',
name
) : null);
if (keyUnique) {
var mappedChild =
mapBookKeeping.mapFunction.call(mapBookKeeping.mapContext, child, i);
mapResult[name] = mappedChild;
}
}
/**
* Maps children that are typically specified as `props.children`.
*
* The provided mapFunction(child, key, index) will be called for each
* leaf child.
*
* TODO: This may likely break any calls to `ReactChildren.map` that were
* previously relying on the fact that we guarded against null children.
*
* @param {?*} children Children tree container.
* @param {function(*, int)} mapFunction.
* @param {*} mapContext Context for mapFunction.
* @return {object} Object containing the ordered map of results.
*/
function mapChildren(children, func, context) {
if (children == null) {
return children;
}
var mapResult = {};
var traverseContext = MapBookKeeping.getPooled(mapResult, func, context);
traverseAllChildren(children, mapSingleChildIntoContext, traverseContext);
MapBookKeeping.release(traverseContext);
return mapResult;
}
function forEachSingleChildDummy(traverseContext, child, name, i) {
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);
}
var ReactChildren = {
forEach: forEachChildren,
map: mapChildren,
count: countChildren
};
module.exports = ReactChildren;
},{"./PooledClass":30,"./traverseAllChildren":158,"./warning":160}],37:[function(_dereq_,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 ReactComponent
*/
"use strict";
var ReactElement = _dereq_("./ReactElement");
var ReactOwner = _dereq_("./ReactOwner");
var ReactUpdates = _dereq_("./ReactUpdates");
var assign = _dereq_("./Object.assign");
var invariant = _dereq_("./invariant");
var keyMirror = _dereq_("./keyMirror");
/**
* 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
});
var injected = false;
/**
* 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.
*
* @private
*/
var unmountIDFromEnvironment = null;
/**
* The "image" of a component tree, is the platform specific (typically
* serialized) data that represents a tree of lower level UI building blocks.
* On the web, this "image" is HTML markup which describes a construction of
* low level `div` and `span` nodes. Other platforms may have different
* encoding of this "image". This must be injected.
*
* @private
*/
var mountImageIntoNode = 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.
*
* `receiveComponent`
* Updates the rendered DOM nodes to match the given component.
*
* `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 = {
injection: {
injectEnvironment: function(ReactComponentEnvironment) {
("production" !== "development" ? invariant(
!injected,
'ReactComponent: injectEnvironment() can only be called once.'
) : invariant(!injected));
mountImageIntoNode = ReactComponentEnvironment.mountImageIntoNode;
unmountIDFromEnvironment =
ReactComponentEnvironment.unmountIDFromEnvironment;
ReactComponent.BackendIDOperations =
ReactComponentEnvironment.BackendIDOperations;
injected = true;
}
},
/**
* @internal
*/
LifeCycle: ComponentLifeCycle,
/**
* Injected module that provides ability to mutate individual properties.
* Injected into the base class because many different subclasses need access
* to this.
*
* @internal
*/
BackendIDOperations: null,
/**
* Base functionality for every ReactComponent constructor. Mixed into the
* `ReactComponent` prototype, but exposed statically for easy access.
*
* @lends {ReactComponent.prototype}
*/
Mixin: {
/**
* Checks whether or not this component is mounted.
*
* @return {boolean} True if mounted, false otherwise.
* @final
* @protected
*/
isMounted: function() {
return this._lifeCycleState === ComponentLifeCycle.MOUNTED;
},
/**
* Sets a subset of the props.
*
* @param {object} partialProps Subset of the next props.
* @param {?function} callback Called after props are updated.
* @final
* @public
*/
setProps: function(partialProps, callback) {
// Merge with the pending element if it exists, otherwise with existing
// element props.
var element = this._pendingElement || this._currentElement;
this.replaceProps(
assign({}, element.props, partialProps),
callback
);
},
/**
* Replaces all of the props.
*
* @param {object} props New props.
* @param {?function} callback Called after props are updated.
* @final
* @public
*/
replaceProps: function(props, callback) {
("production" !== "development" ? invariant(
this.isMounted(),
'replaceProps(...): Can only update a mounted component.'
) : invariant(this.isMounted()));
("production" !== "development" ? invariant(
this._mountDepth === 0,
'replaceProps(...): You called `setProps` or `replaceProps` on a ' +
'component with a parent. This is an anti-pattern since props will ' +
'get reactively updated when rendered. Instead, change the owner\'s ' +
'`render` method to pass the correct value as props to the component ' +
'where it is created.'
) : invariant(this._mountDepth === 0));
// This is a deoptimized path. We optimize for always having a element.
// This creates an extra internal element.
this._pendingElement = ReactElement.cloneAndReplaceProps(
this._pendingElement || this._currentElement,
props
);
ReactUpdates.enqueueUpdate(this, callback);
},
/**
* Schedule a partial update to the props. Only used for internal testing.
*
* @param {object} partialProps Subset of the next props.
* @param {?function} callback Called after props are updated.
* @final
* @internal
*/
_setPropsInternal: function(partialProps, callback) {
// This is a deoptimized path. We optimize for always having a element.
// This creates an extra internal element.
var element = this._pendingElement || this._currentElement;
this._pendingElement = ReactElement.cloneAndReplaceProps(
element,
assign({}, element.props, partialProps)
);
ReactUpdates.enqueueUpdate(this, callback);
},
/**
* Base constructor for all React components.
*
* Subclasses that override this method should make sure to invoke
* `ReactComponent.Mixin.construct.call(this, ...)`.
*
* @param {ReactElement} element
* @internal
*/
construct: function(element) {
// This is the public exposed props object after it has been processed
// with default props. The element's props represents the true internal
// state of the props.
this.props = element.props;
// Record the component responsible for creating this component.
// This is accessible through the element but we maintain an extra
// field for compatibility with devtools and as a way to make an
// incremental update. TODO: Consider deprecating this field.
this._owner = element._owner;
// All components start unmounted.
this._lifeCycleState = ComponentLifeCycle.UNMOUNTED;
// See ReactUpdates.
this._pendingCallbacks = null;
// We keep the old element and a reference to the pending element
// to track updates.
this._currentElement = element;
this._pendingElement = null;
},
/**
* 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|ReactServerRenderingTransaction} transaction
* @param {number} mountDepth number of components in the owner hierarchy.
* @return {?string} Rendered markup to be inserted into the DOM.
* @internal
*/
mountComponent: function(rootID, transaction, mountDepth) {
("production" !== "development" ? invariant(
!this.isMounted(),
'mountComponent(%s, ...): Can only mount an unmounted component. ' +
'Make sure to avoid storing components between renders or reusing a ' +
'single component instance in multiple places.',
rootID
) : invariant(!this.isMounted()));
var ref = this._currentElement.ref;
if (ref != null) {
var owner = this._currentElement._owner;
ReactOwner.addComponentAsRefTo(this, ref, owner);
}
this._rootNodeID = rootID;
this._lifeCycleState = ComponentLifeCycle.MOUNTED;
this._mountDepth = mountDepth;
// 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() {
("production" !== "development" ? invariant(
this.isMounted(),
'unmountComponent(): Can only unmount a mounted component.'
) : invariant(this.isMounted()));
var ref = this._currentElement.ref;
if (ref != null) {
ReactOwner.removeComponentAsRefFrom(this, ref, this._owner);
}
unmountIDFromEnvironment(this._rootNodeID);
this._rootNodeID = null;
this._lifeCycleState = ComponentLifeCycle.UNMOUNTED;
},
/**
* Given a new instance of this component, updates the rendered DOM nodes
* as if that instance was rendered instead.
*
* Subclasses that override this method should make sure to invoke
* `ReactComponent.Mixin.receiveComponent.call(this, ...)`.
*
* @param {object} nextComponent Next set of properties.
* @param {ReactReconcileTransaction} transaction
* @internal
*/
receiveComponent: function(nextElement, transaction) {
("production" !== "development" ? invariant(
this.isMounted(),
'receiveComponent(...): Can only update a mounted component.'
) : invariant(this.isMounted()));
this._pendingElement = nextElement;
this.performUpdateIfNecessary(transaction);
},
/**
* If `_pendingElement` is set, update the component.
*
* @param {ReactReconcileTransaction} transaction
* @internal
*/
performUpdateIfNecessary: function(transaction) {
if (this._pendingElement == null) {
return;
}
var prevElement = this._currentElement;
var nextElement = this._pendingElement;
this._currentElement = nextElement;
this.props = nextElement.props;
this._owner = nextElement._owner;
this._pendingElement = null;
this.updateComponent(transaction, prevElement);
},
/**
* Updates the component's currently mounted representation.
*
* @param {ReactReconcileTransaction} transaction
* @param {object} prevElement
* @internal
*/
updateComponent: function(transaction, prevElement) {
var nextElement = this._currentElement;
// 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.
if (nextElement._owner !== prevElement._owner ||
nextElement.ref !== prevElement.ref) {
if (prevElement.ref != null) {
ReactOwner.removeComponentAsRefFrom(
this, prevElement.ref, prevElement._owner
);
}
// Correct, even if the owner is the same, and only the ref has changed.
if (nextElement.ref != null) {
ReactOwner.addComponentAsRefTo(
this,
nextElement.ref,
nextElement._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.
* @param {boolean} shouldReuseMarkup If true, do not insert markup
* @final
* @internal
* @see {ReactMount.render}
*/
mountComponentIntoNode: function(rootID, container, shouldReuseMarkup) {
var transaction = ReactUpdates.ReactReconcileTransaction.getPooled();
transaction.perform(
this._mountComponentIntoNode,
this,
rootID,
container,
transaction,
shouldReuseMarkup
);
ReactUpdates.ReactReconcileTransaction.release(transaction);
},
/**
* @param {string} rootID DOM ID of the root node.
* @param {DOMElement} container DOM element to mount into.
* @param {ReactReconcileTransaction} transaction
* @param {boolean} shouldReuseMarkup If true, do not insert markup
* @final
* @private
*/
_mountComponentIntoNode: function(
rootID,
container,
transaction,
shouldReuseMarkup) {
var markup = this.mountComponent(rootID, transaction, 0);
mountImageIntoNode(markup, container, shouldReuseMarkup);
},
/**
* 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._owner === owner;
},
/**
* Gets another component, that shares the same owner as this one, by ref.
*
* @param {string} ref of a sibling Component.
* @return {?ReactComponent} the actual sibling Component.
* @final
* @internal
*/
getSiblingByRef: function(ref) {
var owner = this._owner;
if (!owner || !owner.refs) {
return null;
}
return owner.refs[ref];
}
}
};
module.exports = ReactComponent;
},{"./Object.assign":29,"./ReactElement":58,"./ReactOwner":74,"./ReactUpdates":91,"./invariant":140,"./keyMirror":146}],38:[function(_dereq_,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 ReactComponentBrowserEnvironment
*/
/*jslint evil: true */
"use strict";
var ReactDOMIDOperations = _dereq_("./ReactDOMIDOperations");
var ReactMarkupChecksum = _dereq_("./ReactMarkupChecksum");
var ReactMount = _dereq_("./ReactMount");
var ReactPerf = _dereq_("./ReactPerf");
var ReactReconcileTransaction = _dereq_("./ReactReconcileTransaction");
var getReactRootElementInContainer = _dereq_("./getReactRootElementInContainer");
var invariant = _dereq_("./invariant");
var setInnerHTML = _dereq_("./setInnerHTML");
var ELEMENT_NODE_TYPE = 1;
var DOC_NODE_TYPE = 9;
/**
* Abstracts away all functionality of `ReactComponent` requires knowledge of
* the browser context.
*/
var ReactComponentBrowserEnvironment = {
ReactReconcileTransaction: ReactReconcileTransaction,
BackendIDOperations: ReactDOMIDOperations,
/**
* 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) {
ReactMount.purgeID(rootNodeID);
},
/**
* @param {string} markup Markup string to place into the DOM Element.
* @param {DOMElement} container DOM Element to insert markup into.
* @param {boolean} shouldReuseMarkup Should reuse the existing markup in the
* container if possible.
*/
mountImageIntoNode: ReactPerf.measure(
'ReactComponentBrowserEnvironment',
'mountImageIntoNode',
function(markup, container, shouldReuseMarkup) {
("production" !== "development" ? invariant(
container && (
container.nodeType === ELEMENT_NODE_TYPE ||
container.nodeType === DOC_NODE_TYPE
),
'mountComponentIntoNode(...): Target container is not valid.'
) : invariant(container && (
container.nodeType === ELEMENT_NODE_TYPE ||
container.nodeType === DOC_NODE_TYPE
)));
if (shouldReuseMarkup) {
if (ReactMarkupChecksum.canReuseMarkup(
markup,
getReactRootElementInContainer(container))) {
return;
} else {
("production" !== "development" ? invariant(
container.nodeType !== DOC_NODE_TYPE,
'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.'
) : invariant(container.nodeType !== DOC_NODE_TYPE));
if ("production" !== "development") {
console.warn(
'React attempted to use 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.'
);
}
}
}
("production" !== "development" ? invariant(
container.nodeType !== DOC_NODE_TYPE,
'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 renderComponentToString() for server rendering.'
) : invariant(container.nodeType !== DOC_NODE_TYPE));
setInnerHTML(container, markup);
}
)
};
module.exports = ReactComponentBrowserEnvironment;
},{"./ReactDOMIDOperations":47,"./ReactMarkupChecksum":69,"./ReactMount":70,"./ReactPerf":75,"./ReactReconcileTransaction":81,"./getReactRootElementInContainer":134,"./invariant":140,"./setInnerHTML":154}],39:[function(_dereq_,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 ReactComponentWithPureRenderMixin
*/
"use strict";
var shallowEqual = _dereq_("./shallowEqual");
/**
* 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 !shallowEqual(this.props, nextProps) ||
!shallowEqual(this.state, nextState);
}
};
module.exports = ReactComponentWithPureRenderMixin;
},{"./shallowEqual":155}],40:[function(_dereq_,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 ReactCompositeComponent
*/
"use strict";
var ReactComponent = _dereq_("./ReactComponent");
var ReactContext = _dereq_("./ReactContext");
var ReactCurrentOwner = _dereq_("./ReactCurrentOwner");
var ReactElement = _dereq_("./ReactElement");
var ReactElementValidator = _dereq_("./ReactElementValidator");
var ReactEmptyComponent = _dereq_("./ReactEmptyComponent");
var ReactErrorUtils = _dereq_("./ReactErrorUtils");
var ReactLegacyElement = _dereq_("./ReactLegacyElement");
var ReactOwner = _dereq_("./ReactOwner");
var ReactPerf = _dereq_("./ReactPerf");
var ReactPropTransferer = _dereq_("./ReactPropTransferer");
var ReactPropTypeLocations = _dereq_("./ReactPropTypeLocations");
var ReactPropTypeLocationNames = _dereq_("./ReactPropTypeLocationNames");
var ReactUpdates = _dereq_("./ReactUpdates");
var assign = _dereq_("./Object.assign");
var instantiateReactComponent = _dereq_("./instantiateReactComponent");
var invariant = _dereq_("./invariant");
var keyMirror = _dereq_("./keyMirror");
var keyOf = _dereq_("./keyOf");
var monitorCodeUse = _dereq_("./monitorCodeUse");
var mapObject = _dereq_("./mapObject");
var shouldUpdateReactComponent = _dereq_("./shouldUpdateReactComponent");
var warning = _dereq_("./warning");
var MIXINS_KEY = keyOf({mixins: null});
/**
* 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,
/**
* 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 `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,
/**
* 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) {
validateTypeDef(
Constructor,
childContextTypes,
ReactPropTypeLocations.childContext
);
Constructor.childContextTypes = assign(
{},
Constructor.childContextTypes,
childContextTypes
);
},
contextTypes: function(Constructor, contextTypes) {
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) {
validateTypeDef(
Constructor,
propTypes,
ReactPropTypeLocations.prop
);
Constructor.propTypes = assign(
{},
Constructor.propTypes,
propTypes
);
},
statics: function(Constructor, statics) {
mixStaticSpecIntoComponent(Constructor, statics);
}
};
function getDeclarationErrorAddendum(component) {
var owner = component._owner || null;
if (owner && owner.constructor && owner.constructor.displayName) {
return ' Check the render method of `' + owner.constructor.displayName +
'`.';
}
return '';
}
function validateTypeDef(Constructor, typeDef, location) {
for (var propName in typeDef) {
if (typeDef.hasOwnProperty(propName)) {
("production" !== "development" ? invariant(
typeof typeDef[propName] == 'function',
'%s: %s type `%s` is invalid; it must be a function, usually from ' +
'React.PropTypes.',
Constructor.displayName || 'ReactCompositeComponent',
ReactPropTypeLocationNames[location],
propName
) : invariant(typeof typeDef[propName] == 'function'));
}
}
}
function validateMethodOverride(proto, name) {
var specPolicy = ReactCompositeComponentInterface.hasOwnProperty(name) ?
ReactCompositeComponentInterface[name] :
null;
// Disallow overriding of base class methods unless explicitly allowed.
if (ReactCompositeComponentMixin.hasOwnProperty(name)) {
("production" !== "development" ? 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
) : invariant(specPolicy === SpecPolicy.OVERRIDE_BASE));
}
// Disallow defining methods more than once unless explicitly allowed.
if (proto.hasOwnProperty(name)) {
("production" !== "development" ? invariant(
specPolicy === SpecPolicy.DEFINE_MANY ||
specPolicy === SpecPolicy.DEFINE_MANY_MERGED,
'ReactCompositeComponentInterface: You are attempting to define ' +
'`%s` on your component more than once. This conflict may be due ' +
'to a mixin.',
name
) : invariant(specPolicy === SpecPolicy.DEFINE_MANY ||
specPolicy === SpecPolicy.DEFINE_MANY_MERGED));
}
}
function validateLifeCycleOnReplaceState(instance) {
var compositeLifeCycleState = instance._compositeLifeCycleState;
("production" !== "development" ? invariant(
instance.isMounted() ||
compositeLifeCycleState === CompositeLifeCycle.MOUNTING,
'replaceState(...): Can only update a mounted or mounting component.'
) : invariant(instance.isMounted() ||
compositeLifeCycleState === CompositeLifeCycle.MOUNTING));
("production" !== "development" ? invariant(
ReactCurrentOwner.current == null,
'replaceState(...): Cannot update during an existing state transition ' +
'(such as within `render`). Render methods should be a pure function ' +
'of props and state.'
) : invariant(ReactCurrentOwner.current == null));
("production" !== "development" ? invariant(compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING,
'replaceState(...): Cannot update while unmounting component. This ' +
'usually means you called setState() on an unmounted component.'
) : invariant(compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING));
}
/**
* Mixin helper which handles policy validation and reserved
* specification keys when building `ReactCompositeComponent` classses.
*/
function mixSpecIntoComponent(Constructor, spec) {
if (!spec) {
return;
}
("production" !== "development" ? invariant(
!ReactLegacyElement.isValidFactory(spec),
'ReactCompositeComponent: You\'re attempting to ' +
'use a component class as a mixin. Instead, just use a regular object.'
) : invariant(!ReactLegacyElement.isValidFactory(spec)));
("production" !== "development" ? invariant(
!ReactElement.isValidElement(spec),
'ReactCompositeComponent: You\'re attempting to ' +
'use a component as a mixin. Instead, just use a regular object.'
) : invariant(!ReactElement.isValidElement(spec)));
var proto = Constructor.prototype;
// 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];
validateMethodOverride(proto, 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 ReactCompositeComponent methods (in the "interface").
// 2. Overridden methods (that were mixed in).
var isCompositeComponentMethod =
ReactCompositeComponentInterface.hasOwnProperty(name);
var isAlreadyDefined = proto.hasOwnProperty(name);
var markedDontBind = property && property.__reactDontBind;
var isFunction = typeof property === 'function';
var shouldAutoBind =
isFunction &&
!isCompositeComponentMethod &&
!isAlreadyDefined &&
!markedDontBind;
if (shouldAutoBind) {
if (!proto.__reactAutoBindMap) {
proto.__reactAutoBindMap = {};
}
proto.__reactAutoBindMap[name] = property;
proto[name] = property;
} else {
if (isAlreadyDefined) {
var specPolicy = ReactCompositeComponentInterface[name];
// These cases should already be caught by validateMethodOverride
("production" !== "development" ? invariant(
isCompositeComponentMethod && (
specPolicy === SpecPolicy.DEFINE_MANY_MERGED ||
specPolicy === SpecPolicy.DEFINE_MANY
),
'ReactCompositeComponent: Unexpected spec policy %s for key %s ' +
'when mixing in component specs.',
specPolicy,
name
) : invariant(isCompositeComponentMethod && (
specPolicy === SpecPolicy.DEFINE_MANY_MERGED ||
specPolicy === SpecPolicy.DEFINE_MANY
)));
// 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 ("production" !== "development") {
// 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;
("production" !== "development" ? invariant(
!isReserved,
'ReactCompositeComponent: 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(!isReserved));
var isInherited = name in Constructor;
("production" !== "development" ? invariant(
!isInherited,
'ReactCompositeComponent: You are attempting to define ' +
'`%s` on your component more than once. This conflict may be ' +
'due to a mixin.',
name
) : invariant(!isInherited));
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 mergeObjectsWithNoDuplicateKeys(one, two) {
("production" !== "development" ? invariant(
one && two && typeof one === 'object' && typeof two === 'object',
'mergeObjectsWithNoDuplicateKeys(): Cannot merge non-objects'
) : invariant(one && two && typeof one === 'object' && typeof two === 'object'));
mapObject(two, function(value, key) {
("production" !== "development" ? invariant(
one[key] === undefined,
'mergeObjectsWithNoDuplicateKeys(): ' +
'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(one[key] === undefined));
one[key] = value;
});
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;
}
return mergeObjectsWithNoDuplicateKeys(a, b);
};
}
/**
* 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);
};
}
/**
* `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`. The following diagram shows how the states overlap in
* time. There are times when the CompositeLifeCycle is null - at those times it
* is only meaningful to look at ComponentLifeCycle alone.
*
* Top Row: ReactComponent.ComponentLifeCycle
* Low Row: ReactComponent.CompositeLifeCycle
*
* +-------+---------------------------------+--------+
* | UN | MOUNTED | UN |
* |MOUNTED| | MOUNTED|
* +-------+---------------------------------+--------+
* | ^--------+ +-------+ +--------^ |
* | | | | | | | |
* | 0--|MOUNTING|-0-|RECEIVE|-0-| UN |--->0 |
* | | | |PROPS | |MOUNTING| |
* | | | | | | | |
* | | | | | | | |
* | +--------+ +-------+ +--------+ |
* | | | |
* +-------+---------------------------------+--------+
*/
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
});
/**
* @lends {ReactCompositeComponent.prototype}
*/
var ReactCompositeComponentMixin = {
/**
* Base constructor for all composite component.
*
* @param {ReactElement} element
* @final
* @internal
*/
construct: function(element) {
// Children can be either an array or more than one argument
ReactComponent.Mixin.construct.apply(this, arguments);
ReactOwner.Mixin.construct.apply(this, arguments);
this.state = null;
this._pendingState = null;
// This is the public post-processed context. The real context and pending
// context lives on the element.
this.context = null;
this._compositeLifeCycleState = null;
},
/**
* Checks whether or not this composite component is mounted.
* @return {boolean} True if mounted, false otherwise.
* @protected
* @final
*/
isMounted: function() {
return ReactComponent.Mixin.isMounted.call(this) &&
this._compositeLifeCycleState !== CompositeLifeCycle.MOUNTING;
},
/**
* Initializes the component, renders markup, and registers event listeners.
*
* @param {string} rootID DOM ID of the root node.
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {number} mountDepth number of components in the owner hierarchy
* @return {?string} Rendered markup to be inserted into the DOM.
* @final
* @internal
*/
mountComponent: ReactPerf.measure(
'ReactCompositeComponent',
'mountComponent',
function(rootID, transaction, mountDepth) {
ReactComponent.Mixin.mountComponent.call(
this,
rootID,
transaction,
mountDepth
);
this._compositeLifeCycleState = CompositeLifeCycle.MOUNTING;
if (this.__reactAutoBindMap) {
this._bindAutoBindMethods();
}
this.context = this._processContext(this._currentElement._context);
this.props = this._processProps(this.props);
this.state = this.getInitialState ? this.getInitialState() : null;
("production" !== "development" ? invariant(
typeof this.state === 'object' && !Array.isArray(this.state),
'%s.getInitialState(): must return an object or null',
this.constructor.displayName || 'ReactCompositeComponent'
) : invariant(typeof this.state === 'object' && !Array.isArray(this.state)));
this._pendingState = null;
this._pendingForceUpdate = false;
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;
}
}
this._renderedComponent = instantiateReactComponent(
this._renderValidatedComponent(),
this._currentElement.type // The wrapping type
);
// Done with mounting, `setState` will now trigger UI changes.
this._compositeLifeCycleState = null;
var markup = this._renderedComponent.mountComponent(
rootID,
transaction,
mountDepth + 1
);
if (this.componentDidMount) {
transaction.getReactMountReady().enqueue(this.componentDidMount, this);
}
return markup;
}
),
/**
* Releases any resources allocated by `mountComponent`.
*
* @final
* @internal
*/
unmountComponent: function() {
this._compositeLifeCycleState = CompositeLifeCycle.UNMOUNTING;
if (this.componentWillUnmount) {
this.componentWillUnmount();
}
this._compositeLifeCycleState = null;
this._renderedComponent.unmountComponent();
this._renderedComponent = null;
ReactComponent.Mixin.unmountComponent.call(this);
// Some existing components rely on this.props even after they've been
// destroyed (in event handlers).
// TODO: this.props = null;
// TODO: this.state = 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.
*
* 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.
*
* @param {object} partialState Next partial state to be merged with state.
* @param {?function} callback Called after state is updated.
* @final
* @protected
*/
setState: function(partialState, callback) {
("production" !== "development" ? invariant(
typeof partialState === 'object' || partialState == null,
'setState(...): takes an object of state variables to update.'
) : invariant(typeof partialState === 'object' || partialState == null));
if ("production" !== "development"){
("production" !== "development" ? warning(
partialState != null,
'setState(...): You passed an undefined or null state object; ' +
'instead, use forceUpdate().'
) : null);
}
// Merge with `_pendingState` if it exists, otherwise with existing state.
this.replaceState(
assign({}, this._pendingState || this.state, partialState),
callback
);
},
/**
* 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.
* @param {?function} callback Called after state is updated.
* @final
* @protected
*/
replaceState: function(completeState, callback) {
validateLifeCycleOnReplaceState(this);
this._pendingState = completeState;
if (this._compositeLifeCycleState !== CompositeLifeCycle.MOUNTING) {
// If we're in a componentWillMount handler, don't enqueue a rerender
// because ReactUpdates assumes we're in a browser context (which is wrong
// for server rendering) and we're about to do a render anyway.
// TODO: The callback here is ignored when setState is called from
// componentWillMount. Either fix it or disallow doing so completely in
// favor of getInitialState.
ReactUpdates.enqueueUpdate(this, callback);
}
},
/**
* 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 = null;
var contextTypes = this.constructor.contextTypes;
if (contextTypes) {
maskedContext = {};
for (var contextName in contextTypes) {
maskedContext[contextName] = context[contextName];
}
if ("production" !== "development") {
this._checkPropTypes(
contextTypes,
maskedContext,
ReactPropTypeLocations.context
);
}
}
return maskedContext;
},
/**
* @param {object} currentContext
* @return {object}
* @private
*/
_processChildContext: function(currentContext) {
var childContext = this.getChildContext && this.getChildContext();
var displayName = this.constructor.displayName || 'ReactCompositeComponent';
if (childContext) {
("production" !== "development" ? invariant(
typeof this.constructor.childContextTypes === 'object',
'%s.getChildContext(): childContextTypes must be defined in order to ' +
'use getChildContext().',
displayName
) : invariant(typeof this.constructor.childContextTypes === 'object'));
if ("production" !== "development") {
this._checkPropTypes(
this.constructor.childContextTypes,
childContext,
ReactPropTypeLocations.childContext
);
}
for (var name in childContext) {
("production" !== "development" ? invariant(
name in this.constructor.childContextTypes,
'%s.getChildContext(): key "%s" is not defined in childContextTypes.',
displayName,
name
) : invariant(name in this.constructor.childContextTypes));
}
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 ("production" !== "development") {
var propTypes = this.constructor.propTypes;
if (propTypes) {
this._checkPropTypes(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.constructor.displayName;
for (var propName in propTypes) {
if (propTypes.hasOwnProperty(propName)) {
var error =
propTypes[propName](props, propName, componentName, location);
if (error instanceof Error) {
// We may want to extend this logic for similar errors in
// renderComponent calls, so I'm abstracting it away into
// a function to minimize refactoring in the future
var addendum = getDeclarationErrorAddendum(this);
("production" !== "development" ? warning(false, error.message + addendum) : null);
}
}
}
},
/**
* If any of `_pendingElement`, `_pendingState`, or `_pendingForceUpdate`
* is set, update the component.
*
* @param {ReactReconcileTransaction} transaction
* @internal
*/
performUpdateIfNecessary: function(transaction) {
var compositeLifeCycleState = this._compositeLifeCycleState;
// 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) {
return;
}
if (this._pendingElement == null &&
this._pendingState == null &&
!this._pendingForceUpdate) {
return;
}
var nextContext = this.context;
var nextProps = this.props;
var nextElement = this._currentElement;
if (this._pendingElement != null) {
nextElement = this._pendingElement;
nextContext = this._processContext(nextElement._context);
nextProps = this._processProps(nextElement.props);
this._pendingElement = null;
this._compositeLifeCycleState = CompositeLifeCycle.RECEIVING_PROPS;
if (this.componentWillReceiveProps) {
this.componentWillReceiveProps(nextProps, nextContext);
}
}
this._compositeLifeCycleState = null;
var nextState = this._pendingState || this.state;
this._pendingState = null;
var shouldUpdate =
this._pendingForceUpdate ||
!this.shouldComponentUpdate ||
this.shouldComponentUpdate(nextProps, nextState, nextContext);
if ("production" !== "development") {
if (typeof shouldUpdate === "undefined") {
console.warn(
(this.constructor.displayName || 'ReactCompositeComponent') +
'.shouldComponentUpdate(): Returned undefined instead of a ' +
'boolean value. Make sure to return true or false.'
);
}
}
if (shouldUpdate) {
this._pendingForceUpdate = false;
// Will set `this.props`, `this.state` and `this.context`.
this._performComponentUpdate(
nextElement,
nextProps,
nextState,
nextContext,
transaction
);
} else {
// If it's determined that a component should not update, we still want
// to set props and state.
this._currentElement = nextElement;
this.props = nextProps;
this.state = nextState;
this.context = nextContext;
// Owner cannot change because shouldUpdateReactComponent doesn't allow
// it. TODO: Remove this._owner completely.
this._owner = nextElement._owner;
}
},
/**
* 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
* @private
*/
_performComponentUpdate: function(
nextElement,
nextProps,
nextState,
nextContext,
transaction
) {
var prevElement = this._currentElement;
var prevProps = this.props;
var prevState = this.state;
var prevContext = this.context;
if (this.componentWillUpdate) {
this.componentWillUpdate(nextProps, nextState, nextContext);
}
this._currentElement = nextElement;
this.props = nextProps;
this.state = nextState;
this.context = nextContext;
// Owner cannot change because shouldUpdateReactComponent doesn't allow
// it. TODO: Remove this._owner completely.
this._owner = nextElement._owner;
this.updateComponent(
transaction,
prevElement
);
if (this.componentDidUpdate) {
transaction.getReactMountReady().enqueue(
this.componentDidUpdate.bind(this, prevProps, prevState, prevContext),
this
);
}
},
receiveComponent: function(nextElement, transaction) {
if (nextElement === this._currentElement &&
nextElement._owner != null) {
// 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 a element created outside a composite to be
// deeply mutated and reused.
return;
}
ReactComponent.Mixin.receiveComponent.call(
this,
nextElement,
transaction
);
},
/**
* 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
* @param {ReactElement} prevElement
* @internal
* @overridable
*/
updateComponent: ReactPerf.measure(
'ReactCompositeComponent',
'updateComponent',
function(transaction, prevParentElement) {
ReactComponent.Mixin.updateComponent.call(
this,
transaction,
prevParentElement
);
var prevComponentInstance = this._renderedComponent;
var prevElement = prevComponentInstance._currentElement;
var nextElement = this._renderValidatedComponent();
if (shouldUpdateReactComponent(prevElement, nextElement)) {
prevComponentInstance.receiveComponent(nextElement, transaction);
} else {
// These two IDs are actually the same! But nothing should rely on that.
var thisID = this._rootNodeID;
var prevComponentID = prevComponentInstance._rootNodeID;
prevComponentInstance.unmountComponent();
this._renderedComponent = instantiateReactComponent(
nextElement,
this._currentElement.type
);
var nextMarkup = this._renderedComponent.mountComponent(
thisID,
transaction,
this._mountDepth + 1
);
ReactComponent.BackendIDOperations.dangerouslyReplaceNodeWithMarkupByID(
prevComponentID,
nextMarkup
);
}
}
),
/**
* 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`.
*
* @param {?function} callback Called after update is complete.
* @final
* @protected
*/
forceUpdate: function(callback) {
var compositeLifeCycleState = this._compositeLifeCycleState;
("production" !== "development" ? invariant(
this.isMounted() ||
compositeLifeCycleState === CompositeLifeCycle.MOUNTING,
'forceUpdate(...): Can only force an update on mounted or mounting ' +
'components.'
) : invariant(this.isMounted() ||
compositeLifeCycleState === CompositeLifeCycle.MOUNTING));
("production" !== "development" ? invariant(
compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING &&
ReactCurrentOwner.current == null,
'forceUpdate(...): Cannot force an update while unmounting component ' +
'or within a `render` function.'
) : invariant(compositeLifeCycleState !== CompositeLifeCycle.UNMOUNTING &&
ReactCurrentOwner.current == null));
this._pendingForceUpdate = true;
ReactUpdates.enqueueUpdate(this, callback);
},
/**
* @private
*/
_renderValidatedComponent: ReactPerf.measure(
'ReactCompositeComponent',
'_renderValidatedComponent',
function() {
var renderedComponent;
var previousContext = ReactContext.current;
ReactContext.current = this._processChildContext(
this._currentElement._context
);
ReactCurrentOwner.current = this;
try {
renderedComponent = this.render();
if (renderedComponent === null || renderedComponent === false) {
renderedComponent = ReactEmptyComponent.getEmptyComponent();
ReactEmptyComponent.registerNullComponentID(this._rootNodeID);
} else {
ReactEmptyComponent.deregisterNullComponentID(this._rootNodeID);
}
} finally {
ReactContext.current = previousContext;
ReactCurrentOwner.current = null;
}
("production" !== "development" ? invariant(
ReactElement.isValidElement(renderedComponent),
'%s.render(): A valid ReactComponent must be returned. You may have ' +
'returned undefined, an array or some other invalid object.',
this.constructor.displayName || 'ReactCompositeComponent'
) : invariant(ReactElement.isValidElement(renderedComponent)));
return renderedComponent;
}
),
/**
* @private
*/
_bindAutoBindMethods: function() {
for (var autoBindKey in this.__reactAutoBindMap) {
if (!this.__reactAutoBindMap.hasOwnProperty(autoBindKey)) {
continue;
}
var method = this.__reactAutoBindMap[autoBindKey];
this[autoBindKey] = this._bindAutoBindMethod(ReactErrorUtils.guard(
method,
this.constructor.displayName + '.' + autoBindKey
));
}
},
/**
* Binds a method to the component.
*
* @param {function} method Method to be bound.
* @private
*/
_bindAutoBindMethod: function(method) {
var component = this;
var boundMethod = method.bind(component);
if ("production" !== "development") {
boundMethod.__reactBoundContext = component;
boundMethod.__reactBoundMethod = method;
boundMethod.__reactBoundArguments = null;
var componentName = component.constructor.displayName;
var _bind = boundMethod.bind;
boundMethod.bind = function(newThis ) {var args=Array.prototype.slice.call(arguments,1);
// 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) {
monitorCodeUse('react_bind_warning', { component: componentName });
console.warn(
'bind(): React component methods may only be bound to the ' +
'component instance. See ' + componentName
);
} else if (!args.length) {
monitorCodeUse('react_bind_warning', { component: componentName });
console.warn(
'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 ' + componentName
);
return boundMethod;
}
var reboundMethod = _bind.apply(boundMethod, arguments);
reboundMethod.__reactBoundContext = component;
reboundMethod.__reactBoundMethod = method;
reboundMethod.__reactBoundArguments = args;
return reboundMethod;
};
}
return boundMethod;
}
};
var ReactCompositeComponentBase = function() {};
assign(
ReactCompositeComponentBase.prototype,
ReactComponent.Mixin,
ReactOwner.Mixin,
ReactPropTransferer.Mixin,
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(props) {
// This constructor is overridden by mocks. The argument is used
// by mocks to assert on what gets mounted. This will later be used
// by the stand-alone class implementation.
};
Constructor.prototype = new ReactCompositeComponentBase();
Constructor.prototype.constructor = Constructor;
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();
}
("production" !== "development" ? invariant(
Constructor.prototype.render,
'createClass(...): Class specification must implement a `render` method.'
) : invariant(Constructor.prototype.render));
if ("production" !== "development") {
if (Constructor.prototype.componentShouldUpdate) {
monitorCodeUse(
'react_component_should_update_warning',
{ component: spec.displayName }
);
console.warn(
(spec.displayName || 'A component') + ' 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.'
);
}
}
// Reduce time spent doing lookups by setting these on the prototype.
for (var methodName in ReactCompositeComponentInterface) {
if (!Constructor.prototype[methodName]) {
Constructor.prototype[methodName] = null;
}
}
if ("production" !== "development") {
return ReactLegacyElement.wrapFactory(
ReactElementValidator.createFactory(Constructor)
);
}
return ReactLegacyElement.wrapFactory(
ReactElement.createFactory(Constructor)
);
},
injection: {
injectMixin: function(mixin) {
injectedMixins.push(mixin);
}
}
};
module.exports = ReactCompositeComponent;
},{"./Object.assign":29,"./ReactComponent":37,"./ReactContext":41,"./ReactCurrentOwner":42,"./ReactElement":58,"./ReactElementValidator":59,"./ReactEmptyComponent":60,"./ReactErrorUtils":61,"./ReactLegacyElement":67,"./ReactOwner":74,"./ReactPerf":75,"./ReactPropTransferer":76,"./ReactPropTypeLocationNames":77,"./ReactPropTypeLocations":78,"./ReactUpdates":91,"./instantiateReactComponent":139,"./invariant":140,"./keyMirror":146,"./keyOf":147,"./mapObject":148,"./monitorCodeUse":150,"./shouldUpdateReactComponent":156,"./warning":160}],41:[function(_dereq_,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 ReactContext
*/
"use strict";
var assign = _dereq_("./Object.assign");
/**
* Keeps track of the current context.
*
* The context is automatically passed down the component ownership hierarchy
* and is accessible via `this.context` on ReactCompositeComponents.
*/
var ReactContext = {
/**
* @internal
* @type {object}
*/
current: {},
/**
* Temporarily extends the current context while executing scopedCallback.
*
* A typical use case might look like
*
* render: function() {
* var children = ReactContext.withContext({foo: 'foo'}, () => (
*
* ));
* return <div>{children}</div>;
* }
*
* @param {object} newContext New context to merge into the existing context
* @param {function} scopedCallback Callback to run with the new context
* @return {ReactComponent|array<ReactComponent>}
*/
withContext: function(newContext, scopedCallback) {
var result;
var previousContext = ReactContext.current;
ReactContext.current = assign({}, previousContext, newContext);
try {
result = scopedCallback();
} finally {
ReactContext.current = previousContext;
}
return result;
}
};
module.exports = ReactContext;
},{"./Object.assign":29}],42:[function(_dereq_,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 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.
*
* The depth indicate how many composite components are above this render level.
*/
var ReactCurrentOwner = {
/**
* @internal
* @type {ReactComponent}
*/
current: null
};
module.exports = ReactCurrentOwner;
},{}],43:[function(_dereq_,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 ReactDOM
* @typechecks static-only
*/
"use strict";
var ReactElement = _dereq_("./ReactElement");
var ReactElementValidator = _dereq_("./ReactElementValidator");
var ReactLegacyElement = _dereq_("./ReactLegacyElement");
var mapObject = _dereq_("./mapObject");
/**
* Create a factory that creates HTML tag elements.
*
* @param {string} tag Tag name (e.g. `div`).
* @private
*/
function createDOMFactory(tag) {
if ("production" !== "development") {
return ReactLegacyElement.markNonLegacyFactory(
ReactElementValidator.createFactory(tag)
);
}
return ReactLegacyElement.markNonLegacyFactory(
ReactElement.createFactory(tag)
);
}
/**
* Creates a mapping from supported HTML tags to `ReactDOMComponent` classes.
* This is also accessible via `React.DOM`.
*
* @public
*/
var ReactDOM = 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',
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',
defs: 'defs',
ellipse: 'ellipse',
g: 'g',
line: 'line',
linearGradient: 'linearGradient',
mask: 'mask',
path: 'path',
pattern: 'pattern',
polygon: 'polygon',
polyline: 'polyline',
radialGradient: 'radialGradient',
rect: 'rect',
stop: 'stop',
svg: 'svg',
text: 'text',
tspan: 'tspan'
}, createDOMFactory);
module.exports = ReactDOM;
},{"./ReactElement":58,"./ReactElementValidator":59,"./ReactLegacyElement":67,"./mapObject":148}],44:[function(_dereq_,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 ReactDOMButton
*/
"use strict";
var AutoFocusMixin = _dereq_("./AutoFocusMixin");
var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin");
var ReactCompositeComponent = _dereq_("./ReactCompositeComponent");
var ReactElement = _dereq_("./ReactElement");
var ReactDOM = _dereq_("./ReactDOM");
var keyMirror = _dereq_("./keyMirror");
// Store a reference to the <button> `ReactDOMComponent`. TODO: use string
var button = ReactElement.createFactory(ReactDOM.button.type);
var mouseListenerNames = keyMirror({
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 = ReactCompositeComponent.createClass({
displayName: 'ReactDOMButton',
mixins: [AutoFocusMixin, ReactBrowserComponentMixin],
render: function() {
var props = {};
// Copy the props; except the mouse listeners if we're disabled
for (var key in this.props) {
if (this.props.hasOwnProperty(key) &&
(!this.props.disabled || !mouseListenerNames[key])) {
props[key] = this.props[key];
}
}
return button(props, this.props.children);
}
});
module.exports = ReactDOMButton;
},{"./AutoFocusMixin":2,"./ReactBrowserComponentMixin":32,"./ReactCompositeComponent":40,"./ReactDOM":43,"./ReactElement":58,"./keyMirror":146}],45:[function(_dereq_,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 ReactDOMComponent
* @typechecks static-only
*/
"use strict";
var CSSPropertyOperations = _dereq_("./CSSPropertyOperations");
var DOMProperty = _dereq_("./DOMProperty");
var DOMPropertyOperations = _dereq_("./DOMPropertyOperations");
var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin");
var ReactComponent = _dereq_("./ReactComponent");
var ReactBrowserEventEmitter = _dereq_("./ReactBrowserEventEmitter");
var ReactMount = _dereq_("./ReactMount");
var ReactMultiChild = _dereq_("./ReactMultiChild");
var ReactPerf = _dereq_("./ReactPerf");
var assign = _dereq_("./Object.assign");
var escapeTextForBrowser = _dereq_("./escapeTextForBrowser");
var invariant = _dereq_("./invariant");
var isEventSupported = _dereq_("./isEventSupported");
var keyOf = _dereq_("./keyOf");
var monitorCodeUse = _dereq_("./monitorCodeUse");
var deleteListener = ReactBrowserEventEmitter.deleteListener;
var listenTo = ReactBrowserEventEmitter.listenTo;
var registrationNameModules = ReactBrowserEventEmitter.registrationNameModules;
// For quickly matching children type, to test if can be treated as content.
var CONTENT_TYPES = {'string': true, 'number': true};
var STYLE = keyOf({style: null});
var ELEMENT_NODE_TYPE = 1;
/**
* @param {?object} props
*/
function assertValidProps(props) {
if (!props) {
return;
}
// Note the use of `==` which checks for null or undefined.
("production" !== "development" ? invariant(
props.children == null || props.dangerouslySetInnerHTML == null,
'Can only set one of `children` or `props.dangerouslySetInnerHTML`.'
) : invariant(props.children == null || props.dangerouslySetInnerHTML == null));
if ("production" !== "development") {
if (props.contentEditable && props.children != null) {
console.warn(
'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.'
);
}
}
("production" !== "development" ? invariant(
props.style == null || typeof props.style === 'object',
'The `style` prop expects a mapping from style properties to values, ' +
'not a string.'
) : invariant(props.style == null || typeof props.style === 'object'));
}
function putListener(id, registrationName, listener, transaction) {
if ("production" !== "development") {
// IE8 has no API for event capturing and the `onScroll` event doesn't
// bubble.
if (registrationName === 'onScroll' &&
!isEventSupported('scroll', true)) {
monitorCodeUse('react_no_scroll_event');
console.warn('This browser doesn\'t support the `onScroll` event');
}
}
var container = ReactMount.findReactContainerForID(id);
if (container) {
var doc = container.nodeType === ELEMENT_NODE_TYPE ?
container.ownerDocument :
container;
listenTo(registrationName, doc);
}
transaction.getPutListenerQueue().enqueuePutListener(
id,
registrationName,
listener
);
}
// For HTML, certain tags should omit their close tag. We keep a whitelist for
// those special cased 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.
};
// We accept any tag to be rendered but since this gets injected into abitrary
// 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)) {
("production" !== "development" ? invariant(VALID_TAG_REGEX.test(tag), 'Invalid tag: %s', tag) : invariant(VALID_TAG_REGEX.test(tag)));
validatedTagCache[tag] = true;
}
}
/**
* 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 ReactComponent
* @extends ReactMultiChild
*/
function ReactDOMComponent(tag) {
validateDangerousTag(tag);
this._tag = tag;
this.tagName = tag.toUpperCase();
}
ReactDOMComponent.displayName = 'ReactDOMComponent';
ReactDOMComponent.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|ReactServerRenderingTransaction} transaction
* @param {number} mountDepth number of components in the owner hierarchy
* @return {string} The computed markup.
*/
mountComponent: ReactPerf.measure(
'ReactDOMComponent',
'mountComponent',
function(rootID, transaction, mountDepth) {
ReactComponent.Mixin.mountComponent.call(
this,
rootID,
transaction,
mountDepth
);
assertValidProps(this.props);
var closeTag = omittedCloseTags[this._tag] ? '' : '</' + this._tag + '>';
return (
this._createOpenTagMarkupAndPutListeners(transaction) +
this._createContentMarkup(transaction) +
closeTag
);
}
),
/**
* 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
* @return {string} Markup of opening tag.
*/
_createOpenTagMarkupAndPutListeners: function(transaction) {
var props = this.props;
var ret = '<' + this._tag;
for (var propKey in props) {
if (!props.hasOwnProperty(propKey)) {
continue;
}
var propValue = props[propKey];
if (propValue == null) {
continue;
}
if (registrationNameModules.hasOwnProperty(propKey)) {
putListener(this._rootNodeID, propKey, propValue, transaction);
} else {
if (propKey === STYLE) {
if (propValue) {
propValue = props.style = assign({}, props.style);
}
propValue = CSSPropertyOperations.createMarkupForStyles(propValue);
}
var 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 + '>';
}
var markupForID = DOMPropertyOperations.createMarkupForID(this._rootNodeID);
return ret + ' ' + markupForID + '>';
},
/**
* Creates markup for the content between the tags.
*
* @private
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} 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 =
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) {
var mountImages = this.mountChildren(
childrenToUse,
transaction
);
return mountImages.join('');
}
}
return '';
},
receiveComponent: function(nextElement, transaction) {
if (nextElement === this._currentElement &&
nextElement._owner != null) {
// 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 a element created outside a composite to be
// deeply mutated and reused.
return;
}
ReactComponent.Mixin.receiveComponent.call(
this,
nextElement,
transaction
);
},
/**
* 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
* @internal
* @overridable
*/
updateComponent: ReactPerf.measure(
'ReactDOMComponent',
'updateComponent',
function(transaction, prevElement) {
assertValidProps(this._currentElement.props);
ReactComponent.Mixin.updateComponent.call(
this,
transaction,
prevElement
);
this._updateDOMProperties(prevElement.props, transaction);
this._updateDOMChildren(prevElement.props, transaction);
}
),
/**
* 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 {ReactReconcileTransaction} transaction
*/
_updateDOMProperties: function(lastProps, transaction) {
var nextProps = this.props;
var propKey;
var styleName;
var styleUpdates;
for (propKey in lastProps) {
if (nextProps.hasOwnProperty(propKey) ||
!lastProps.hasOwnProperty(propKey)) {
continue;
}
if (propKey === STYLE) {
var lastStyle = lastProps[propKey];
for (styleName in lastStyle) {
if (lastStyle.hasOwnProperty(styleName)) {
styleUpdates = styleUpdates || {};
styleUpdates[styleName] = '';
}
}
} else if (registrationNameModules.hasOwnProperty(propKey)) {
deleteListener(this._rootNodeID, propKey);
} else if (
DOMProperty.isStandardName[propKey] ||
DOMProperty.isCustomAttribute(propKey)) {
ReactComponent.BackendIDOperations.deletePropertyByID(
this._rootNodeID,
propKey
);
}
}
for (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 = assign({}, nextProp);
}
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)) {
putListener(this._rootNodeID, propKey, nextProp, transaction);
} else if (
DOMProperty.isStandardName[propKey] ||
DOMProperty.isCustomAttribute(propKey)) {
ReactComponent.BackendIDOperations.updatePropertyByID(
this._rootNodeID,
propKey,
nextProp
);
}
}
if (styleUpdates) {
ReactComponent.BackendIDOperations.updateStylesByID(
this._rootNodeID,
styleUpdates
);
}
},
/**
* Reconciles the children with the various properties that affect the
* children content.
*
* @param {object} lastProps
* @param {ReactReconcileTransaction} transaction
*/
_updateDOMChildren: function(lastProps, transaction) {
var nextProps = this.props;
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);
} else if (lastHasContentOrHtml && !nextHasContentOrHtml) {
this.updateTextContent('');
}
if (nextContent != null) {
if (lastContent !== nextContent) {
this.updateTextContent('' + nextContent);
}
} else if (nextHtml != null) {
if (lastHtml !== nextHtml) {
ReactComponent.BackendIDOperations.updateInnerHTMLByID(
this._rootNodeID,
nextHtml
);
}
} else if (nextChildren != null) {
this.updateChildren(nextChildren, transaction);
}
},
/**
* Destroys all event registrations for this instance. Does not remove from
* the DOM. That must be done by the parent.
*
* @internal
*/
unmountComponent: function() {
this.unmountChildren();
ReactBrowserEventEmitter.deleteAllListeners(this._rootNodeID);
ReactComponent.Mixin.unmountComponent.call(this);
}
};
assign(
ReactDOMComponent.prototype,
ReactComponent.Mixin,
ReactDOMComponent.Mixin,
ReactMultiChild.Mixin,
ReactBrowserComponentMixin
);
module.exports = ReactDOMComponent;
},{"./CSSPropertyOperations":6,"./DOMProperty":12,"./DOMPropertyOperations":13,"./Object.assign":29,"./ReactBrowserComponentMixin":32,"./ReactBrowserEventEmitter":33,"./ReactComponent":37,"./ReactMount":70,"./ReactMultiChild":71,"./ReactPerf":75,"./escapeTextForBrowser":123,"./invariant":140,"./isEventSupported":141,"./keyOf":147,"./monitorCodeUse":150}],46:[function(_dereq_,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 ReactDOMForm
*/
"use strict";
var EventConstants = _dereq_("./EventConstants");
var LocalEventTrapMixin = _dereq_("./LocalEventTrapMixin");
var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin");
var ReactCompositeComponent = _dereq_("./ReactCompositeComponent");
var ReactElement = _dereq_("./ReactElement");
var ReactDOM = _dereq_("./ReactDOM");
// Store a reference to the <form> `ReactDOMComponent`. TODO: use string
var form = ReactElement.createFactory(ReactDOM.form.type);
/**
* 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({
displayName: 'ReactDOMForm',
mixins: [ReactBrowserComponentMixin, LocalEventTrapMixin],
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 form(this.props);
},
componentDidMount: function() {
this.trapBubbledEvent(EventConstants.topLevelTypes.topReset, 'reset');
this.trapBubbledEvent(EventConstants.topLevelTypes.topSubmit, 'submit');
}
});
module.exports = ReactDOMForm;
},{"./EventConstants":17,"./LocalEventTrapMixin":27,"./ReactBrowserComponentMixin":32,"./ReactCompositeComponent":40,"./ReactDOM":43,"./ReactElement":58}],47:[function(_dereq_,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 ReactDOMIDOperations
* @typechecks static-only
*/
/*jslint evil: true */
"use strict";
var CSSPropertyOperations = _dereq_("./CSSPropertyOperations");
var DOMChildrenOperations = _dereq_("./DOMChildrenOperations");
var DOMPropertyOperations = _dereq_("./DOMPropertyOperations");
var ReactMount = _dereq_("./ReactMount");
var ReactPerf = _dereq_("./ReactPerf");
var invariant = _dereq_("./invariant");
var setInnerHTML = _dereq_("./setInnerHTML");
/**
* Errors for properties that should not be updated with `updatePropertyById()`.
*
* @type {object}
* @private
*/
var INVALID_PROPERTY_ERRORS = {
dangerouslySetInnerHTML:
'`dangerouslySetInnerHTML` must be set using `updateInnerHTMLByID()`.',
style: '`style` must be set using `updateStylesByID()`.'
};
/**
* Operations used to process updates to DOM nodes. This is made injectable via
* `ReactComponent.BackendIDOperations`.
*/
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: ReactPerf.measure(
'ReactDOMIDOperations',
'updatePropertyByID',
function(id, name, value) {
var node = ReactMount.getNode(id);
("production" !== "development" ? invariant(
!INVALID_PROPERTY_ERRORS.hasOwnProperty(name),
'updatePropertyByID(...): %s',
INVALID_PROPERTY_ERRORS[name]
) : invariant(!INVALID_PROPERTY_ERRORS.hasOwnProperty(name)));
// If we're updating to null or undefined, we should remove the property
// from the DOM node instead of inadvertantly setting to a string. This
// brings us in line with the same behavior we have on initial render.
if (value != null) {
DOMPropertyOperations.setValueForProperty(node, name, value);
} else {
DOMPropertyOperations.deleteValueForProperty(node, name);
}
}
),
/**
* Updates a DOM node to remove a property. This should only be used to remove
* DOM properties in `DOMProperty`.
*
* @param {string} id ID of the node to update.
* @param {string} name A property name to remove, see `DOMProperty`.
* @internal
*/
deletePropertyByID: ReactPerf.measure(
'ReactDOMIDOperations',
'deletePropertyByID',
function(id, name, value) {
var node = ReactMount.getNode(id);
("production" !== "development" ? invariant(
!INVALID_PROPERTY_ERRORS.hasOwnProperty(name),
'updatePropertyByID(...): %s',
INVALID_PROPERTY_ERRORS[name]
) : invariant(!INVALID_PROPERTY_ERRORS.hasOwnProperty(name)));
DOMPropertyOperations.deleteValueForProperty(node, name, value);
}
),
/**
* Updates a DOM node with new style values. If a value is specified as '',
* the corresponding style property will be unset.
*
* @param {string} id ID of the node to update.
* @param {object} styles Mapping from styles to values.
* @internal
*/
updateStylesByID: ReactPerf.measure(
'ReactDOMIDOperations',
'updateStylesByID',
function(id, styles) {
var node = ReactMount.getNode(id);
CSSPropertyOperations.setValueForStyles(node, styles);
}
),
/**
* Updates a DOM node's innerHTML.
*
* @param {string} id ID of the node to update.
* @param {string} html An HTML string.
* @internal
*/
updateInnerHTMLByID: ReactPerf.measure(
'ReactDOMIDOperations',
'updateInnerHTMLByID',
function(id, html) {
var node = ReactMount.getNode(id);
setInnerHTML(node, html);
}
),
/**
* 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: ReactPerf.measure(
'ReactDOMIDOperations',
'updateTextContentByID',
function(id, content) {
var node = ReactMount.getNode(id);
DOMChildrenOperations.updateTextContent(node, 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: ReactPerf.measure(
'ReactDOMIDOperations',
'dangerouslyReplaceNodeWithMarkupByID',
function(id, markup) {
var node = ReactMount.getNode(id);
DOMChildrenOperations.dangerouslyReplaceNodeWithMarkup(node, markup);
}
),
/**
* Updates a component's children by processing a series of updates.
*
* @param {array<object>} updates List of update configurations.
* @param {array<string>} markup List of markup strings.
* @internal
*/
dangerouslyProcessChildrenUpdates: ReactPerf.measure(
'ReactDOMIDOperations',
'dangerouslyProcessChildrenUpdates',
function(updates, markup) {
for (var i = 0; i < updates.length; i++) {
updates[i].parentNode = ReactMount.getNode(updates[i].parentID);
}
DOMChildrenOperations.processUpdates(updates, markup);
}
)
};
module.exports = ReactDOMIDOperations;
},{"./CSSPropertyOperations":6,"./DOMChildrenOperations":11,"./DOMPropertyOperations":13,"./ReactMount":70,"./ReactPerf":75,"./invariant":140,"./setInnerHTML":154}],48:[function(_dereq_,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 ReactDOMImg
*/
"use strict";
var EventConstants = _dereq_("./EventConstants");
var LocalEventTrapMixin = _dereq_("./LocalEventTrapMixin");
var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin");
var ReactCompositeComponent = _dereq_("./ReactCompositeComponent");
var ReactElement = _dereq_("./ReactElement");
var ReactDOM = _dereq_("./ReactDOM");
// Store a reference to the <img> `ReactDOMComponent`. TODO: use string
var img = ReactElement.createFactory(ReactDOM.img.type);
/**
* Since onLoad doesn't bubble OR capture on the top level in IE8, we need to
* capture it on the <img> element itself. There are lots of hacks we could do
* to accomplish this, but the most reliable is to make <img> a composite
* component and use `componentDidMount` to attach the event handlers.
*/
var ReactDOMImg = ReactCompositeComponent.createClass({
displayName: 'ReactDOMImg',
tagName: 'IMG',
mixins: [ReactBrowserComponentMixin, LocalEventTrapMixin],
render: function() {
return img(this.props);
},
componentDidMount: function() {
this.trapBubbledEvent(EventConstants.topLevelTypes.topLoad, 'load');
this.trapBubbledEvent(EventConstants.topLevelTypes.topError, 'error');
}
});
module.exports = ReactDOMImg;
},{"./EventConstants":17,"./LocalEventTrapMixin":27,"./ReactBrowserComponentMixin":32,"./ReactCompositeComponent":40,"./ReactDOM":43,"./ReactElement":58}],49:[function(_dereq_,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 ReactDOMInput
*/
"use strict";
var AutoFocusMixin = _dereq_("./AutoFocusMixin");
var DOMPropertyOperations = _dereq_("./DOMPropertyOperations");
var LinkedValueUtils = _dereq_("./LinkedValueUtils");
var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin");
var ReactCompositeComponent = _dereq_("./ReactCompositeComponent");
var ReactElement = _dereq_("./ReactElement");
var ReactDOM = _dereq_("./ReactDOM");
var ReactMount = _dereq_("./ReactMount");
var ReactUpdates = _dereq_("./ReactUpdates");
var assign = _dereq_("./Object.assign");
var invariant = _dereq_("./invariant");
// Store a reference to the <input> `ReactDOMComponent`. TODO: use string
var input = ReactElement.createFactory(ReactDOM.input.type);
var instancesByReactID = {};
function forceUpdateIfMounted() {
/*jshint validthis:true */
if (this.isMounted()) {
this.forceUpdate();
}
}
/**
* 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 = ReactCompositeComponent.createClass({
displayName: 'ReactDOMInput',
mixins: [AutoFocusMixin, LinkedValueUtils.Mixin, ReactBrowserComponentMixin],
getInitialState: function() {
var defaultValue = this.props.defaultValue;
return {
initialChecked: this.props.defaultChecked || false,
initialValue: defaultValue != null ? defaultValue : null
};
},
render: function() {
// Clone `this.props` so we don't mutate the input.
var props = assign({}, this.props);
props.defaultChecked = null;
props.defaultValue = null;
var value = LinkedValueUtils.getValue(this);
props.value = value != null ? value : this.state.initialValue;
var checked = LinkedValueUtils.getChecked(this);
props.checked = checked != null ? checked : this.state.initialChecked;
props.onChange = this._handleChange;
return input(props, this.props.children);
},
componentDidMount: function() {
var id = ReactMount.getID(this.getDOMNode());
instancesByReactID[id] = this;
},
componentWillUnmount: function() {
var rootNode = this.getDOMNode();
var id = ReactMount.getID(rootNode);
delete instancesByReactID[id];
},
componentDidUpdate: function(prevProps, prevState, prevContext) {
var rootNode = this.getDOMNode();
if (this.props.checked != null) {
DOMPropertyOperations.setValueForProperty(
rootNode,
'checked',
this.props.checked || false
);
}
var value = LinkedValueUtils.getValue(this);
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(rootNode, 'value', '' + value);
}
},
_handleChange: function(event) {
var returnValue;
var onChange = LinkedValueUtils.getOnChange(this);
if (onChange) {
returnValue = onChange.call(this, 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 = this.props.name;
if (this.props.type === 'radio' && name != null) {
var rootNode = this.getDOMNode();
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, groupLen = group.length; i < groupLen; i++) {
var otherNode = group[i];
if (otherNode === rootNode ||
otherNode.form !== rootNode.form) {
continue;
}
var otherID = ReactMount.getID(otherNode);
("production" !== "development" ? invariant(
otherID,
'ReactDOMInput: Mixing React and non-React radio inputs with the ' +
'same `name` is not supported.'
) : invariant(otherID));
var otherInstance = instancesByReactID[otherID];
("production" !== "development" ? invariant(
otherInstance,
'ReactDOMInput: Unknown radio button ID %s.',
otherID
) : invariant(otherInstance));
// 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;
},{"./AutoFocusMixin":2,"./DOMPropertyOperations":13,"./LinkedValueUtils":26,"./Object.assign":29,"./ReactBrowserComponentMixin":32,"./ReactCompositeComponent":40,"./ReactDOM":43,"./ReactElement":58,"./ReactMount":70,"./ReactUpdates":91,"./invariant":140}],50:[function(_dereq_,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 ReactDOMOption
*/
"use strict";
var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin");
var ReactCompositeComponent = _dereq_("./ReactCompositeComponent");
var ReactElement = _dereq_("./ReactElement");
var ReactDOM = _dereq_("./ReactDOM");
var warning = _dereq_("./warning");
// Store a reference to the <option> `ReactDOMComponent`. TODO: use string
var option = ReactElement.createFactory(ReactDOM.option.type);
/**
* Implements an <option> native component that warns when `selected` is set.
*/
var ReactDOMOption = ReactCompositeComponent.createClass({
displayName: 'ReactDOMOption',
mixins: [ReactBrowserComponentMixin],
componentWillMount: function() {
// TODO (yungsters): Remove support for `selected` in <option>.
if ("production" !== "development") {
("production" !== "development" ? warning(
this.props.selected == null,
'Use the `defaultValue` or `value` props on <select> instead of ' +
'setting `selected` on <option>.'
) : null);
}
},
render: function() {
return option(this.props, this.props.children);
}
});
module.exports = ReactDOMOption;
},{"./ReactBrowserComponentMixin":32,"./ReactCompositeComponent":40,"./ReactDOM":43,"./ReactElement":58,"./warning":160}],51:[function(_dereq_,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 ReactDOMSelect
*/
"use strict";
var AutoFocusMixin = _dereq_("./AutoFocusMixin");
var LinkedValueUtils = _dereq_("./LinkedValueUtils");
var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin");
var ReactCompositeComponent = _dereq_("./ReactCompositeComponent");
var ReactElement = _dereq_("./ReactElement");
var ReactDOM = _dereq_("./ReactDOM");
var ReactUpdates = _dereq_("./ReactUpdates");
var assign = _dereq_("./Object.assign");
// Store a reference to the <select> `ReactDOMComponent`. TODO: use string
var select = ReactElement.createFactory(ReactDOM.select.type);
function updateWithPendingValueIfMounted() {
/*jshint validthis:true */
if (this.isMounted()) {
this.setState({value: this._pendingValue});
this._pendingValue = 0;
}
}
/**
* Validation function for `value` and `defaultValue`.
* @private
*/
function selectValueType(props, propName, componentName) {
if (props[propName] == null) {
return;
}
if (props.multiple) {
if (!Array.isArray(props[propName])) {
return new Error(
("The `" + propName + "` prop supplied to <select> must be an array if ") +
("`multiple` is true.")
);
}
} else {
if (Array.isArray(props[propName])) {
return new Error(
("The `" + propName + "` prop supplied to <select> must be a scalar ") +
("value if `multiple` is false.")
);
}
}
}
/**
* If `value` is supplied, updates <option> elements on mount and update.
* @param {ReactComponent} component Instance of ReactDOMSelect
* @param {?*} propValue For uncontrolled components, null/undefined. For
* controlled components, a string (or with `multiple`, a list of strings).
* @private
*/
function updateOptions(component, propValue) {
var multiple = component.props.multiple;
var value = propValue != null ? propValue : component.state.value;
var options = component.getDOMNode().options;
var selectedValue, i, l;
if (multiple) {
selectedValue = {};
for (i = 0, l = value.length; i < l; ++i) {
selectedValue['' + value[i]] = true;
}
} else {
selectedValue = '' + value;
}
for (i = 0, l = options.length; i < l; i++) {
var selected = multiple ?
selectedValue.hasOwnProperty(options[i].value) :
options[i].value === selectedValue;
if (selected !== options[i].selected) {
options[i].selected = selected;
}
}
}
/**
* Implements a <select> native component that allows optionally setting the
* props `value` and `defaultValue`. If `multiple` is false, the prop must be a
* string. If `multiple` is true, the prop must be an array of strings.
*
* 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 = ReactCompositeComponent.createClass({
displayName: 'ReactDOMSelect',
mixins: [AutoFocusMixin, LinkedValueUtils.Mixin, ReactBrowserComponentMixin],
propTypes: {
defaultValue: selectValueType,
value: selectValueType
},
getInitialState: function() {
return {value: this.props.defaultValue || (this.props.multiple ? [] : '')};
},
componentWillMount: function() {
this._pendingValue = null;
},
componentWillReceiveProps: function(nextProps) {
if (!this.props.multiple && nextProps.multiple) {
this.setState({value: [this.state.value]});
} else if (this.props.multiple && !nextProps.multiple) {
this.setState({value: this.state.value[0]});
}
},
render: function() {
// Clone `this.props` so we don't mutate the input.
var props = assign({}, this.props);
props.onChange = this._handleChange;
props.value = null;
return select(props, this.props.children);
},
componentDidMount: function() {
updateOptions(this, LinkedValueUtils.getValue(this));
},
componentDidUpdate: function(prevProps) {
var value = LinkedValueUtils.getValue(this);
var prevMultiple = !!prevProps.multiple;
var multiple = !!this.props.multiple;
if (value != null || prevMultiple !== multiple) {
updateOptions(this, value);
}
},
_handleChange: function(event) {
var returnValue;
var onChange = LinkedValueUtils.getOnChange(this);
if (onChange) {
returnValue = onChange.call(this, event);
}
var selectedValue;
if (this.props.multiple) {
selectedValue = [];
var options = event.target.options;
for (var i = 0, l = options.length; i < l; i++) {
if (options[i].selected) {
selectedValue.push(options[i].value);
}
}
} else {
selectedValue = event.target.value;
}
this._pendingValue = selectedValue;
ReactUpdates.asap(updateWithPendingValueIfMounted, this);
return returnValue;
}
});
module.exports = ReactDOMSelect;
},{"./AutoFocusMixin":2,"./LinkedValueUtils":26,"./Object.assign":29,"./ReactBrowserComponentMixin":32,"./ReactCompositeComponent":40,"./ReactDOM":43,"./ReactElement":58,"./ReactUpdates":91}],52:[function(_dereq_,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 ReactDOMSelection
*/
"use strict";
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
var getNodeForCharacterOffset = _dereq_("./getNodeForCharacterOffset");
var getTextContentAccessor = _dereq_("./getTextContentAccessor");
/**
* 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);
// 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 (typeof 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 programatically 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 = typeof 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 && document.selection;
var ReactDOMSelection = {
/**
* @param {DOMElement} node
*/
getOffsets: useIEOffsets ? getIEOffsets : getModernOffsets,
/**
* @param {DOMElement|DOMTextNode} node
* @param {object} offsets
*/
setOffsets: useIEOffsets ? setIEOffsets : setModernOffsets
};
module.exports = ReactDOMSelection;
},{"./ExecutionEnvironment":23,"./getNodeForCharacterOffset":133,"./getTextContentAccessor":135}],53:[function(_dereq_,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 ReactDOMTextarea
*/
"use strict";
var AutoFocusMixin = _dereq_("./AutoFocusMixin");
var DOMPropertyOperations = _dereq_("./DOMPropertyOperations");
var LinkedValueUtils = _dereq_("./LinkedValueUtils");
var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin");
var ReactCompositeComponent = _dereq_("./ReactCompositeComponent");
var ReactElement = _dereq_("./ReactElement");
var ReactDOM = _dereq_("./ReactDOM");
var ReactUpdates = _dereq_("./ReactUpdates");
var assign = _dereq_("./Object.assign");
var invariant = _dereq_("./invariant");
var warning = _dereq_("./warning");
// Store a reference to the <textarea> `ReactDOMComponent`. TODO: use string
var textarea = ReactElement.createFactory(ReactDOM.textarea.type);
function forceUpdateIfMounted() {
/*jshint validthis:true */
if (this.isMounted()) {
this.forceUpdate();
}
}
/**
* 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 = ReactCompositeComponent.createClass({
displayName: 'ReactDOMTextarea',
mixins: [AutoFocusMixin, LinkedValueUtils.Mixin, ReactBrowserComponentMixin],
getInitialState: function() {
var defaultValue = this.props.defaultValue;
// TODO (yungsters): Remove support for children content in <textarea>.
var children = this.props.children;
if (children != null) {
if ("production" !== "development") {
("production" !== "development" ? warning(
false,
'Use the `defaultValue` or `value` props instead of setting ' +
'children on <textarea>.'
) : null);
}
("production" !== "development" ? invariant(
defaultValue == null,
'If you supply `defaultValue` on a <textarea>, do not pass children.'
) : invariant(defaultValue == null));
if (Array.isArray(children)) {
("production" !== "development" ? invariant(
children.length <= 1,
'<textarea> can only have at most one child.'
) : invariant(children.length <= 1));
children = children[0];
}
defaultValue = '' + children;
}
if (defaultValue == null) {
defaultValue = '';
}
var value = LinkedValueUtils.getValue(this);
return {
// 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)
};
},
render: function() {
// Clone `this.props` so we don't mutate the input.
var props = assign({}, this.props);
("production" !== "development" ? invariant(
props.dangerouslySetInnerHTML == null,
'`dangerouslySetInnerHTML` does not make sense on <textarea>.'
) : invariant(props.dangerouslySetInnerHTML == null));
props.defaultValue = null;
props.value = null;
props.onChange = this._handleChange;
// Always set children to the same thing. In IE9, the selection range will
// get reset if `textContent` is mutated.
return textarea(props, this.state.initialValue);
},
componentDidUpdate: function(prevProps, prevState, prevContext) {
var value = LinkedValueUtils.getValue(this);
if (value != null) {
var rootNode = this.getDOMNode();
// Cast `value` to a string to ensure the value is set correctly. While
// browsers typically do this as necessary, jsdom doesn't.
DOMPropertyOperations.setValueForProperty(rootNode, 'value', '' + value);
}
},
_handleChange: function(event) {
var returnValue;
var onChange = LinkedValueUtils.getOnChange(this);
if (onChange) {
returnValue = onChange.call(this, event);
}
ReactUpdates.asap(forceUpdateIfMounted, this);
return returnValue;
}
});
module.exports = ReactDOMTextarea;
},{"./AutoFocusMixin":2,"./DOMPropertyOperations":13,"./LinkedValueUtils":26,"./Object.assign":29,"./ReactBrowserComponentMixin":32,"./ReactCompositeComponent":40,"./ReactDOM":43,"./ReactElement":58,"./ReactUpdates":91,"./invariant":140,"./warning":160}],54:[function(_dereq_,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 ReactDefaultBatchingStrategy
*/
"use strict";
var ReactUpdates = _dereq_("./ReactUpdates");
var Transaction = _dereq_("./Transaction");
var assign = _dereq_("./Object.assign");
var emptyFunction = _dereq_("./emptyFunction");
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) {
var alreadyBatchingUpdates = ReactDefaultBatchingStrategy.isBatchingUpdates;
ReactDefaultBatchingStrategy.isBatchingUpdates = true;
// The code is written this way to avoid extra allocations
if (alreadyBatchingUpdates) {
callback(a, b);
} else {
transaction.perform(callback, null, a, b);
}
}
};
module.exports = ReactDefaultBatchingStrategy;
},{"./Object.assign":29,"./ReactUpdates":91,"./Transaction":107,"./emptyFunction":121}],55:[function(_dereq_,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 ReactDefaultInjection
*/
"use strict";
var BeforeInputEventPlugin = _dereq_("./BeforeInputEventPlugin");
var ChangeEventPlugin = _dereq_("./ChangeEventPlugin");
var ClientReactRootIndex = _dereq_("./ClientReactRootIndex");
var CompositionEventPlugin = _dereq_("./CompositionEventPlugin");
var DefaultEventPluginOrder = _dereq_("./DefaultEventPluginOrder");
var EnterLeaveEventPlugin = _dereq_("./EnterLeaveEventPlugin");
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
var HTMLDOMPropertyConfig = _dereq_("./HTMLDOMPropertyConfig");
var MobileSafariClickEventPlugin = _dereq_("./MobileSafariClickEventPlugin");
var ReactBrowserComponentMixin = _dereq_("./ReactBrowserComponentMixin");
var ReactComponentBrowserEnvironment =
_dereq_("./ReactComponentBrowserEnvironment");
var ReactDefaultBatchingStrategy = _dereq_("./ReactDefaultBatchingStrategy");
var ReactDOMComponent = _dereq_("./ReactDOMComponent");
var ReactDOMButton = _dereq_("./ReactDOMButton");
var ReactDOMForm = _dereq_("./ReactDOMForm");
var ReactDOMImg = _dereq_("./ReactDOMImg");
var ReactDOMInput = _dereq_("./ReactDOMInput");
var ReactDOMOption = _dereq_("./ReactDOMOption");
var ReactDOMSelect = _dereq_("./ReactDOMSelect");
var ReactDOMTextarea = _dereq_("./ReactDOMTextarea");
var ReactEventListener = _dereq_("./ReactEventListener");
var ReactInjection = _dereq_("./ReactInjection");
var ReactInstanceHandles = _dereq_("./ReactInstanceHandles");
var ReactMount = _dereq_("./ReactMount");
var SelectEventPlugin = _dereq_("./SelectEventPlugin");
var ServerReactRootIndex = _dereq_("./ServerReactRootIndex");
var SimpleEventPlugin = _dereq_("./SimpleEventPlugin");
var SVGDOMPropertyConfig = _dereq_("./SVGDOMPropertyConfig");
var createFullPageComponent = _dereq_("./createFullPageComponent");
function inject() {
ReactInjection.EventEmitter.injectReactEventListener(
ReactEventListener
);
/**
* Inject modules for resolving DOM hierarchy and plugin ordering.
*/
ReactInjection.EventPluginHub.injectEventPluginOrder(DefaultEventPluginOrder);
ReactInjection.EventPluginHub.injectInstanceHandle(ReactInstanceHandles);
ReactInjection.EventPluginHub.injectMount(ReactMount);
/**
* Some important event plugins included by default (without having to require
* them).
*/
ReactInjection.EventPluginHub.injectEventPluginsByName({
SimpleEventPlugin: SimpleEventPlugin,
EnterLeaveEventPlugin: EnterLeaveEventPlugin,
ChangeEventPlugin: ChangeEventPlugin,
CompositionEventPlugin: CompositionEventPlugin,
MobileSafariClickEventPlugin: MobileSafariClickEventPlugin,
SelectEventPlugin: SelectEventPlugin,
BeforeInputEventPlugin: BeforeInputEventPlugin
});
ReactInjection.NativeComponent.injectGenericComponentClass(
ReactDOMComponent
);
ReactInjection.NativeComponent.injectComponentClasses({
'button': ReactDOMButton,
'form': ReactDOMForm,
'img': ReactDOMImg,
'input': ReactDOMInput,
'option': ReactDOMOption,
'select': ReactDOMSelect,
'textarea': ReactDOMTextarea,
'html': createFullPageComponent('html'),
'head': createFullPageComponent('head'),
'body': createFullPageComponent('body')
});
// This needs to happen after createFullPageComponent() otherwise the mixin
// gets double injected.
ReactInjection.CompositeComponent.injectMixin(ReactBrowserComponentMixin);
ReactInjection.DOMProperty.injectDOMPropertyConfig(HTMLDOMPropertyConfig);
ReactInjection.DOMProperty.injectDOMPropertyConfig(SVGDOMPropertyConfig);
ReactInjection.EmptyComponent.injectEmptyComponent('noscript');
ReactInjection.Updates.injectReconcileTransaction(
ReactComponentBrowserEnvironment.ReactReconcileTransaction
);
ReactInjection.Updates.injectBatchingStrategy(
ReactDefaultBatchingStrategy
);
ReactInjection.RootIndex.injectCreateReactRootIndex(
ExecutionEnvironment.canUseDOM ?
ClientReactRootIndex.createReactRootIndex :
ServerReactRootIndex.createReactRootIndex
);
ReactInjection.Component.injectEnvironment(ReactComponentBrowserEnvironment);
if ("production" !== "development") {
var url = (ExecutionEnvironment.canUseDOM && window.location.href) || '';
if ((/[?&]react_perf\b/).test(url)) {
var ReactDefaultPerf = _dereq_("./ReactDefaultPerf");
ReactDefaultPerf.start();
}
}
}
module.exports = {
inject: inject
};
},{"./BeforeInputEventPlugin":3,"./ChangeEventPlugin":8,"./ClientReactRootIndex":9,"./CompositionEventPlugin":10,"./DefaultEventPluginOrder":15,"./EnterLeaveEventPlugin":16,"./ExecutionEnvironment":23,"./HTMLDOMPropertyConfig":24,"./MobileSafariClickEventPlugin":28,"./ReactBrowserComponentMixin":32,"./ReactComponentBrowserEnvironment":38,"./ReactDOMButton":44,"./ReactDOMComponent":45,"./ReactDOMForm":46,"./ReactDOMImg":48,"./ReactDOMInput":49,"./ReactDOMOption":50,"./ReactDOMSelect":51,"./ReactDOMTextarea":53,"./ReactDefaultBatchingStrategy":54,"./ReactDefaultPerf":56,"./ReactEventListener":63,"./ReactInjection":64,"./ReactInstanceHandles":66,"./ReactMount":70,"./SVGDOMPropertyConfig":92,"./SelectEventPlugin":93,"./ServerReactRootIndex":94,"./SimpleEventPlugin":95,"./createFullPageComponent":116}],56:[function(_dereq_,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 ReactDefaultPerf
* @typechecks static-only
*/
"use strict";
var DOMProperty = _dereq_("./DOMProperty");
var ReactDefaultPerfAnalysis = _dereq_("./ReactDefaultPerfAnalysis");
var ReactMount = _dereq_("./ReactMount");
var ReactPerf = _dereq_("./ReactPerf");
var performanceNow = _dereq_("./performanceNow");
function roundFloat(val) {
return Math.floor(val * 100) / 100;
}
function addValue(obj, key, val) {
obj[key] = (obj[key] || 0) + val;
}
var ReactDefaultPerf = {
_allMeasurements: [], // last item in the list is the current one
_mountStack: [0],
_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 writes =
ReactDefaultPerf
._allMeasurements[ReactDefaultPerf._allMeasurements.length - 1]
.writes;
writes[id] = writes[id] || [];
writes[id].push({
type: fnName,
time: totalTime,
args: args
});
},
measure: function(moduleName, fnName, func) {
return function() {var args=Array.prototype.slice.call(arguments,0);
var totalTime;
var rv;
var start;
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({
exclusive: {},
inclusive: {},
render: {},
counts: {},
writes: {},
displayNames: {},
totalTime: 0
});
start = performanceNow();
rv = func.apply(this, args);
ReactDefaultPerf._allMeasurements[
ReactDefaultPerf._allMeasurements.length - 1
].totalTime = performanceNow() - start;
return rv;
} else if (moduleName === 'ReactDOMIDOperations' ||
moduleName === 'ReactComponentBrowserEnvironment') {
start = performanceNow();
rv = func.apply(this, args);
totalTime = performanceNow() - start;
if (fnName === 'mountImageIntoNode') {
var mountID = ReactMount.getID(args[1]);
ReactDefaultPerf._recordWrite(mountID, fnName, totalTime, args[0]);
} else if (fnName === 'dangerouslyProcessChildrenUpdates') {
// special format
args[0].forEach(function(update) {
var writeArgs = {};
if (update.fromIndex !== null) {
writeArgs.fromIndex = update.fromIndex;
}
if (update.toIndex !== null) {
writeArgs.toIndex = update.toIndex;
}
if (update.textContent !== null) {
writeArgs.textContent = update.textContent;
}
if (update.markupIndex !== null) {
writeArgs.markup = args[1][update.markupIndex];
}
ReactDefaultPerf._recordWrite(
update.parentID,
update.type,
totalTime,
writeArgs
);
});
} else {
// basic format
ReactDefaultPerf._recordWrite(
args[0],
fnName,
totalTime,
Array.prototype.slice.call(args, 1)
);
}
return rv;
} else if (moduleName === 'ReactCompositeComponent' && (
fnName === 'mountComponent' ||
fnName === 'updateComponent' || // TODO: receiveComponent()?
fnName === '_renderValidatedComponent')) {
var rootNodeID = fnName === 'mountComponent' ?
args[0] :
this._rootNodeID;
var isRender = fnName === '_renderValidatedComponent';
var isMount = fnName === 'mountComponent';
var mountStack = ReactDefaultPerf._mountStack;
var entry = ReactDefaultPerf._allMeasurements[
ReactDefaultPerf._allMeasurements.length - 1
];
if (isRender) {
addValue(entry.counts, rootNodeID, 1);
} else if (isMount) {
mountStack.push(0);
}
start = performanceNow();
rv = func.apply(this, args);
totalTime = performanceNow() - start;
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.constructor.displayName,
owner: this._owner ? this._owner.constructor.displayName : '<root>'
};
return rv;
} else {
return func.apply(this, args);
}
};
}
};
module.exports = ReactDefaultPerf;
},{"./DOMProperty":12,"./ReactDefaultPerfAnalysis":57,"./ReactMount":70,"./ReactPerf":75,"./performanceNow":153}],57:[function(_dereq_,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 ReactDefaultPerfAnalysis
*/
var assign = _dereq_("./Object.assign");
// 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',
TEXT_CONTENT: 'set textContent',
'updatePropertyByID': 'update attribute',
'deletePropertyByID': 'delete attribute',
'updateStylesByID': 'update styles',
'updateInnerHTMLByID': 'set innerHTML',
'dangerouslyReplaceNodeWithMarkupByID': 'replace'
};
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 = [];
for (var i = 0; i < measurements.length; i++) {
var measurement = measurements[i];
var id;
for (id in measurement.writes) {
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 dirtyLeafIDs = Object.keys(measurement.writes);
var allIDs = assign({}, measurement.exclusive, measurement.inclusive);
for (var id in allIDs) {
var isDirty = false;
// For each component that rendered, see if a component that triggered
// a DOM op is in its subtree.
for (var i = 0; i < dirtyLeafIDs.length; i++) {
if (dirtyLeafIDs[i].indexOf(id) === 0) {
isDirty = true;
break;
}
}
if (!isDirty && measurement.counts[id] > 0) {
cleanComponents[id] = true;
}
}
return cleanComponents;
}
var ReactDefaultPerfAnalysis = {
getExclusiveSummary: getExclusiveSummary,
getInclusiveSummary: getInclusiveSummary,
getDOMSummary: getDOMSummary,
getTotalTime: getTotalTime
};
module.exports = ReactDefaultPerfAnalysis;
},{"./Object.assign":29}],58:[function(_dereq_,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 ReactElement
*/
"use strict";
var ReactContext = _dereq_("./ReactContext");
var ReactCurrentOwner = _dereq_("./ReactCurrentOwner");
var warning = _dereq_("./warning");
var RESERVED_PROPS = {
key: true,
ref: true
};
/**
* Warn for mutations.
*
* @internal
* @param {object} object
* @param {string} key
*/
function defineWarningProperty(object, key) {
Object.defineProperty(object, key, {
configurable: false,
enumerable: true,
get: function() {
if (!this._store) {
return null;
}
return this._store[key];
},
set: function(value) {
("production" !== "development" ? warning(
false,
'Don\'t set the ' + key + ' property of the component. ' +
'Mutate the existing props object instead.'
) : null);
this._store[key] = value;
}
});
}
/**
* This is updated to true if the membrane is successfully created.
*/
var useMutationMembrane = false;
/**
* Warn for mutations.
*
* @internal
* @param {object} element
*/
function defineMutationMembrane(prototype) {
try {
var pseudoFrozenProperties = {
props: true
};
for (var key in pseudoFrozenProperties) {
defineWarningProperty(prototype, key);
}
useMutationMembrane = true;
} catch (x) {
// IE will fail on defineProperty
}
}
/**
* Base constructor for all React elements. This is only used to make this
* work with a dynamic instanceof check. Nothing should live on this prototype.
*
* @param {*} type
* @param {string|object} ref
* @param {*} key
* @params {*} props
* @internal
*/
var ReactElement = function(type, key, ref, owner, context, props) {
// Built-in properties that belong on the element
this.type = type;
this.key = key;
this.ref = ref;
// Record the component responsible for creating this element.
this._owner = owner;
// TODO: Deprecate withContext, and then the context becomes accessible
// through the owner.
this._context = context;
if ("production" !== "development") {
// The validation flag and props are currently mutative. We put them 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.
this._store = { validated: false, props: props };
// We're not allowed to set props directly on the object so we early
// return and rely on the prototype membrane to forward to the backing
// store.
if (useMutationMembrane) {
Object.freeze(this);
return;
}
}
this.props = props;
};
if ("production" !== "development") {
defineMutationMembrane(ReactElement.prototype);
}
ReactElement.prototype._isReactElement = true;
ReactElement.createElement = function(type, config, children) {
var propName;
// Reserved names are extracted
var props = {};
var key = null;
var ref = null;
if (config != null) {
ref = config.ref === undefined ? null : config.ref;
key = config.key === undefined ? null : '' + config.key;
// 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.defaultProps) {
var defaultProps = type.defaultProps;
for (propName in defaultProps) {
if (typeof props[propName] === 'undefined') {
props[propName] = defaultProps[propName];
}
}
}
return new ReactElement(
type,
key,
ref,
ReactCurrentOwner.current,
ReactContext.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.type.
// 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.
factory.type = type;
return factory;
};
ReactElement.cloneAndReplaceProps = function(oldElement, newProps) {
var newElement = new ReactElement(
oldElement.type,
oldElement.key,
oldElement.ref,
oldElement._owner,
oldElement._context,
newProps
);
if ("production" !== "development") {
// If the key on the original is valid, then the clone is valid
newElement._store.validated = oldElement._store.validated;
}
return newElement;
};
/**
* @param {?object} object
* @return {boolean} True if `object` is a valid component.
* @final
*/
ReactElement.isValidElement = function(object) {
// ReactTestUtils is often used outside of beforeEach where as React is
// within it. This leads to two different instances of React on the same
// page. To identify a element from a different React instance we use
// a flag instead of an instanceof check.
var isElement = !!(object && object._isReactElement);
// if (isElement && !(object instanceof ReactElement)) {
// This is an indicator that you're using multiple versions of React at the
// same time. This will screw with ownership and stuff. Fix it, please.
// TODO: We could possibly warn here.
// }
return isElement;
};
module.exports = ReactElement;
},{"./ReactContext":41,"./ReactCurrentOwner":42,"./warning":160}],59:[function(_dereq_,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 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_("./ReactElement");
var ReactPropTypeLocations = _dereq_("./ReactPropTypeLocations");
var ReactCurrentOwner = _dereq_("./ReactCurrentOwner");
var monitorCodeUse = _dereq_("./monitorCodeUse");
/**
* 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 = {
'react_key_warning': {},
'react_numeric_key_warning': {}
};
var ownerHasMonitoredObjectMap = {};
var loggedTypeFailures = {};
var NUMERIC_PROPERTY_REGEX = /^\d+$/;
/**
* Gets the current owner's displayName for use in warnings.
*
* @internal
* @return {?string} Display name or undefined
*/
function getCurrentOwnerDisplayName() {
var current = ReactCurrentOwner.current;
return current && current.constructor.displayName || undefined;
}
/**
* Warn if the component doesn't have an explicit key assigned to it.
* This component 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 {ReactComponent} component Component that requires a key.
* @param {*} parentType component's parent's type.
*/
function validateExplicitKey(component, parentType) {
if (component._store.validated || component.key != null) {
return;
}
component._store.validated = true;
warnAndMonitorForKeyUse(
'react_key_warning',
'Each child in an array should have a unique "key" prop.',
component,
parentType
);
}
/**
* Warn if the key is being defined as an object property but has an incorrect
* value.
*
* @internal
* @param {string} name Property name of the key.
* @param {ReactComponent} component Component that requires a key.
* @param {*} parentType component's parent's type.
*/
function validatePropertyKey(name, component, parentType) {
if (!NUMERIC_PROPERTY_REGEX.test(name)) {
return;
}
warnAndMonitorForKeyUse(
'react_numeric_key_warning',
'Child objects should have non-numeric keys so ordering is preserved.',
component,
parentType
);
}
/**
* Shared warning and monitoring code for the key warnings.
*
* @internal
* @param {string} warningID The id used when logging.
* @param {string} message The base warning that gets output.
* @param {ReactComponent} component Component that requires a key.
* @param {*} parentType component's parent's type.
*/
function warnAndMonitorForKeyUse(warningID, message, component, parentType) {
var ownerName = getCurrentOwnerDisplayName();
var parentName = parentType.displayName;
var useName = ownerName || parentName;
var memoizer = ownerHasKeyUseWarning[warningID];
if (memoizer.hasOwnProperty(useName)) {
return;
}
memoizer[useName] = true;
message += ownerName ?
(" Check the render method of " + ownerName + ".") :
(" Check the renderComponent call using <" + parentName + ">.");
// 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.
var childOwnerName = null;
if (component._owner && component._owner !== ReactCurrentOwner.current) {
// Name of the component that originally created this child.
childOwnerName = component._owner.constructor.displayName;
message += (" It was passed a child from " + childOwnerName + ".");
}
message += ' See http://fb.me/react-warning-keys for more information.';
monitorCodeUse(warningID, {
component: useName,
componentOwner: childOwnerName
});
console.warn(message);
}
/**
* Log that we're using an object map. We're considering deprecating this
* feature and replace it with proper Map and ImmutableMap data structures.
*
* @internal
*/
function monitorUseOfObjectMap() {
var currentName = getCurrentOwnerDisplayName() || '';
if (ownerHasMonitoredObjectMap.hasOwnProperty(currentName)) {
return;
}
ownerHasMonitoredObjectMap[currentName] = true;
monitorCodeUse('react_object_map_children');
}
/**
* Ensure that every component 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 {*} component Statically passed child of any type.
* @param {*} parentType component's parent's type.
* @return {boolean}
*/
function validateChildKeys(component, parentType) {
if (Array.isArray(component)) {
for (var i = 0; i < component.length; i++) {
var child = component[i];
if (ReactElement.isValidElement(child)) {
validateExplicitKey(child, parentType);
}
}
} else if (ReactElement.isValidElement(component)) {
// This component was passed in a valid location.
component._store.validated = true;
} else if (component && typeof component === 'object') {
monitorUseOfObjectMap();
for (var name in component) {
validatePropertyKey(name, component[name], 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 {
error = propTypes[propName](props, propName, componentName, location);
} catch (ex) {
error = ex;
}
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;
// This will soon use the warning module
monitorCodeUse(
'react_failed_descriptor_type_check',
{ message: error.message }
);
}
}
}
}
var ReactElementValidator = {
createElement: function(type, props, children) {
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;
}
for (var i = 2; i < arguments.length; i++) {
validateChildKeys(arguments[i], type);
}
var name = type.displayName;
if (type.propTypes) {
checkPropTypes(
name,
type.propTypes,
element.props,
ReactPropTypeLocations.prop
);
}
if (type.contextTypes) {
checkPropTypes(
name,
type.contextTypes,
element._context,
ReactPropTypeLocations.context
);
}
return element;
},
createFactory: function(type) {
var validatedFactory = ReactElementValidator.createElement.bind(
null,
type
);
validatedFactory.type = type;
return validatedFactory;
}
};
module.exports = ReactElementValidator;
},{"./ReactCurrentOwner":42,"./ReactElement":58,"./ReactPropTypeLocations":78,"./monitorCodeUse":150}],60:[function(_dereq_,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 ReactEmptyComponent
*/
"use strict";
var ReactElement = _dereq_("./ReactElement");
var invariant = _dereq_("./invariant");
var component;
// This registry keeps track of the React IDs of the components that rendered to
// `null` (in reality a placeholder such as `noscript`)
var nullComponentIdsRegistry = {};
var ReactEmptyComponentInjection = {
injectEmptyComponent: function(emptyComponent) {
component = ReactElement.createFactory(emptyComponent);
}
};
/**
* @return {ReactComponent} component The injected empty component.
*/
function getEmptyComponent() {
("production" !== "development" ? invariant(
component,
'Trying to return null from a render, but no null placeholder component ' +
'was injected.'
) : invariant(component));
return component();
}
/**
* Mark the component as having rendered to null.
* @param {string} id Component's `_rootNodeID`.
*/
function registerNullComponentID(id) {
nullComponentIdsRegistry[id] = true;
}
/**
* Unmark the component as having rendered to null: it renders to something now.
* @param {string} id Component's `_rootNodeID`.
*/
function deregisterNullComponentID(id) {
delete nullComponentIdsRegistry[id];
}
/**
* @param {string} id Component's `_rootNodeID`.
* @return {boolean} True if the component is rendered to null.
*/
function isNullComponentID(id) {
return nullComponentIdsRegistry[id];
}
var ReactEmptyComponent = {
deregisterNullComponentID: deregisterNullComponentID,
getEmptyComponent: getEmptyComponent,
injection: ReactEmptyComponentInjection,
isNullComponentID: isNullComponentID,
registerNullComponentID: registerNullComponentID
};
module.exports = ReactEmptyComponent;
},{"./ReactElement":58,"./invariant":140}],61:[function(_dereq_,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 ReactErrorUtils
* @typechecks
*/
"use strict";
var ReactErrorUtils = {
/**
* Creates a guarded version of a function. This is supposed to make debugging
* of event handlers easier. To aid debugging with the browser's debugger,
* this currently simply returns the original function.
*
* @param {function} func Function to be executed
* @param {string} name The name of the guard
* @return {function}
*/
guard: function(func, name) {
return func;
}
};
module.exports = ReactErrorUtils;
},{}],62:[function(_dereq_,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 ReactEventEmitterMixin
*/
"use strict";
var EventPluginHub = _dereq_("./EventPluginHub");
function runEventQueueInBatch(events) {
EventPluginHub.enqueueEvents(events);
EventPluginHub.processEventQueue();
}
var ReactEventEmitterMixin = {
/**
* Streams a fired top-level event to `EventPluginHub` where plugins have the
* opportunity to create `ReactEvent`s to be dispatched.
*
* @param {string} topLevelType Record from `EventConstants`.
* @param {object} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native environment event.
*/
handleTopLevel: function(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent) {
var events = EventPluginHub.extractEvents(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent
);
runEventQueueInBatch(events);
}
};
module.exports = ReactEventEmitterMixin;
},{"./EventPluginHub":19}],63:[function(_dereq_,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 ReactEventListener
* @typechecks static-only
*/
"use strict";
var EventListener = _dereq_("./EventListener");
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
var PooledClass = _dereq_("./PooledClass");
var ReactInstanceHandles = _dereq_("./ReactInstanceHandles");
var ReactMount = _dereq_("./ReactMount");
var ReactUpdates = _dereq_("./ReactUpdates");
var assign = _dereq_("./Object.assign");
var getEventTarget = _dereq_("./getEventTarget");
var getUnboundedScrollPosition = _dereq_("./getUnboundedScrollPosition");
/**
* Finds the parent React component of `node`.
*
* @param {*} node
* @return {?DOMEventTarget} Parent container, or `null` if the specified node
* is not nested.
*/
function findParent(node) {
// 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.
var nodeID = ReactMount.getID(node);
var rootID = ReactInstanceHandles.getReactRootIDFromNodeID(nodeID);
var container = ReactMount.findReactContainerForID(rootID);
var parent = ReactMount.getFirstReactDOM(container);
return parent;
}
// 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 topLevelTarget = ReactMount.getFirstReactDOM(
getEventTarget(bookKeeping.nativeEvent)
) || window;
// 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 = topLevelTarget;
while (ancestor) {
bookKeeping.ancestors.push(ancestor);
ancestor = findParent(ancestor);
}
for (var i = 0, l = bookKeeping.ancestors.length; i < l; i++) {
topLevelTarget = bookKeeping.ancestors[i];
var topLevelTargetID = ReactMount.getID(topLevelTarget) || '';
ReactEventListener._handleTopLevel(
bookKeeping.topLevelType,
topLevelTarget,
topLevelTargetID,
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;
}
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;
}
return EventListener.capture(
element,
handlerBaseName,
ReactEventListener.dispatchEvent.bind(null, topLevelType)
);
},
monitorScrollValue: function(refresh) {
var callback = scrollValueMonitor.bind(null, refresh);
EventListener.listen(window, 'scroll', callback);
EventListener.listen(window, 'resize', 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;
},{"./EventListener":18,"./ExecutionEnvironment":23,"./Object.assign":29,"./PooledClass":30,"./ReactInstanceHandles":66,"./ReactMount":70,"./ReactUpdates":91,"./getEventTarget":131,"./getUnboundedScrollPosition":136}],64:[function(_dereq_,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 ReactInjection
*/
"use strict";
var DOMProperty = _dereq_("./DOMProperty");
var EventPluginHub = _dereq_("./EventPluginHub");
var ReactComponent = _dereq_("./ReactComponent");
var ReactCompositeComponent = _dereq_("./ReactCompositeComponent");
var ReactEmptyComponent = _dereq_("./ReactEmptyComponent");
var ReactBrowserEventEmitter = _dereq_("./ReactBrowserEventEmitter");
var ReactNativeComponent = _dereq_("./ReactNativeComponent");
var ReactPerf = _dereq_("./ReactPerf");
var ReactRootIndex = _dereq_("./ReactRootIndex");
var ReactUpdates = _dereq_("./ReactUpdates");
var ReactInjection = {
Component: ReactComponent.injection,
CompositeComponent: ReactCompositeComponent.injection,
DOMProperty: DOMProperty.injection,
EmptyComponent: ReactEmptyComponent.injection,
EventPluginHub: EventPluginHub.injection,
EventEmitter: ReactBrowserEventEmitter.injection,
NativeComponent: ReactNativeComponent.injection,
Perf: ReactPerf.injection,
RootIndex: ReactRootIndex.injection,
Updates: ReactUpdates.injection
};
module.exports = ReactInjection;
},{"./DOMProperty":12,"./EventPluginHub":19,"./ReactBrowserEventEmitter":33,"./ReactComponent":37,"./ReactCompositeComponent":40,"./ReactEmptyComponent":60,"./ReactNativeComponent":73,"./ReactPerf":75,"./ReactRootIndex":82,"./ReactUpdates":91}],65:[function(_dereq_,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 ReactInputSelection
*/
"use strict";
var ReactDOMSelection = _dereq_("./ReactDOMSelection");
var containsNode = _dereq_("./containsNode");
var focusNode = _dereq_("./focusNode");
var getActiveElement = _dereq_("./getActiveElement");
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) {
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 &&
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') {
// 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 (typeof 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') {
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;
},{"./ReactDOMSelection":52,"./containsNode":114,"./focusNode":125,"./getActiveElement":127}],66:[function(_dereq_,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 ReactInstanceHandles
* @typechecks static-only
*/
"use strict";
var ReactRootIndex = _dereq_("./ReactRootIndex");
var invariant = _dereq_("./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;
/**
* Creates a DOM ID prefix to use when mounting React components.
*
* @param {number} index A unique integer
* @return {string} React root ID.
* @internal
*/
function getReactRootIDString(index) {
return SEPARATOR + index.toString(36);
}
/**
* 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 isBoundary(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
);
}
/**
* Checks if the first ID is an ancestor of or equal to the second ID.
*
* @param {string} ancestorID
* @param {string} descendantID
* @return {boolean} True if `ancestorID` is an ancestor of `descendantID`.
* @internal
*/
function isAncestorIDOf(ancestorID, descendantID) {
return (
descendantID.indexOf(ancestorID) === 0 &&
isBoundary(descendantID, ancestorID.length)
);
}
/**
* 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 getParentID(id) {
return id ? id.substr(0, id.lastIndexOf(SEPARATOR)) : '';
}
/**
* 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`.
* @private
*/
function getNextDescendantID(ancestorID, destinationID) {
("production" !== "development" ? invariant(
isValidID(ancestorID) && isValidID(destinationID),
'getNextDescendantID(%s, %s): Received an invalid React DOM ID.',
ancestorID,
destinationID
) : invariant(isValidID(ancestorID) && isValidID(destinationID)));
("production" !== "development" ? invariant(
isAncestorIDOf(ancestorID, destinationID),
'getNextDescendantID(...): React has made an invalid assumption about ' +
'the DOM hierarchy. Expected `%s` to be an ancestor of `%s`.',
ancestorID,
destinationID
) : invariant(isAncestorIDOf(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 (isBoundary(destinationID, i)) {
break;
}
}
return destinationID.substr(0, i);
}
/**
* 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.
* @private
*/
function getFirstCommonAncestorID(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 (isBoundary(oneID, i) && isBoundary(twoID, i)) {
lastCommonMarkerIndex = i;
} else if (oneID.charAt(i) !== twoID.charAt(i)) {
break;
}
}
var longestCommonID = oneID.substr(0, lastCommonMarkerIndex);
("production" !== "development" ? invariant(
isValidID(longestCommonID),
'getFirstCommonAncestorID(%s, %s): Expected a valid React DOM ID: %s',
oneID,
twoID,
longestCommonID
) : invariant(isValidID(longestCommonID)));
return longestCommonID;
}
/**
* 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. If the
* callback returns `false`, traversal is stopped.
*
* @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 || '';
("production" !== "development" ? invariant(
start !== stop,
'traverseParentPath(...): Cannot traverse from and to the same ID, `%s`.',
start
) : invariant(start !== stop));
var traverseUp = isAncestorIDOf(stop, start);
("production" !== "development" ? invariant(
traverseUp || isAncestorIDOf(start, stop),
'traverseParentPath(%s, %s, ...): Cannot traverse from two IDs that do ' +
'not have a parent path.',
start,
stop
) : invariant(traverseUp || isAncestorIDOf(start, stop)));
// Traverse from `start` to `stop` one depth at a time.
var depth = 0;
var traverse = traverseUp ? getParentID : getNextDescendantID;
for (var id = start; /* until break */; id = traverse(id, stop)) {
var ret;
if ((!skipFirst || id !== start) && (!skipLast || id !== stop)) {
ret = cb(id, traverseUp, arg);
}
if (ret === false || id === stop) {
// Only break //after// visiting `stop`.
break;
}
("production" !== "development" ? 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
) : invariant(depth++ < MAX_TREE_DEPTH));
}
}
/**
* 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 = {
/**
* Constructs a React root ID
* @return {string} A React root ID.
*/
createReactRootID: function() {
return getReactRootIDString(ReactRootIndex.createReactRootIndex());
},
/**
* Constructs a React ID by joining a root ID with a name.
*
* @param {string} rootID Root ID of a parent component.
* @param {string} name A component's name (as flattened children).
* @return {string} A React ID.
* @internal
*/
createReactID: function(rootID, name) {
return rootID + name;
},
/**
* 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) {
if (id && id.charAt(0) === SEPARATOR && id.length > 1) {
var index = id.indexOf(SEPARATOR, 1);
return index > -1 ? id.substr(0, index) : id;
}
return null;
},
/**
* 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 ancestorID = getFirstCommonAncestorID(leaveID, enterID);
if (ancestorID !== leaveID) {
traverseParentPath(leaveID, ancestorID, cb, upArg, false, true);
}
if (ancestorID !== enterID) {
traverseParentPath(ancestorID, 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);
}
},
/**
* Traverse a node ID, calling the supplied `cb` for each ancestor ID. For
* example, passing `.0.$row-0.1` would result in `cb` getting called
* with `.0`, `.0.$row-0`, and `.0.$row-0.1`.
*
* 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
*/
traverseAncestors: function(targetID, cb, arg) {
traverseParentPath('', targetID, cb, arg, true, false);
},
/**
* Exposed for unit testing.
* @private
*/
_getFirstCommonAncestorID: getFirstCommonAncestorID,
/**
* Exposed for unit testing.
* @private
*/
_getNextDescendantID: getNextDescendantID,
isAncestorIDOf: isAncestorIDOf,
SEPARATOR: SEPARATOR
};
module.exports = ReactInstanceHandles;
},{"./ReactRootIndex":82,"./invariant":140}],67:[function(_dereq_,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 ReactLegacyElement
*/
"use strict";
var ReactCurrentOwner = _dereq_("./ReactCurrentOwner");
var invariant = _dereq_("./invariant");
var monitorCodeUse = _dereq_("./monitorCodeUse");
var warning = _dereq_("./warning");
var legacyFactoryLogs = {};
function warnForLegacyFactoryCall() {
if (!ReactLegacyElementFactory._isLegacyCallWarningEnabled) {
return;
}
var owner = ReactCurrentOwner.current;
var name = owner && owner.constructor ? owner.constructor.displayName : '';
if (!name) {
name = 'Something';
}
if (legacyFactoryLogs.hasOwnProperty(name)) {
return;
}
legacyFactoryLogs[name] = true;
("production" !== "development" ? warning(
false,
name + ' is calling a React component directly. ' +
'Use a factory or JSX instead. See: http://fb.me/react-legacyfactory'
) : null);
monitorCodeUse('react_legacy_factory_call', { version: 3, name: name });
}
function warnForPlainFunctionType(type) {
var isReactClass =
type.prototype &&
typeof type.prototype.mountComponent === 'function' &&
typeof type.prototype.receiveComponent === 'function';
if (isReactClass) {
("production" !== "development" ? warning(
false,
'Did not expect to get a React class here. Use `Component` instead ' +
'of `Component.type` or `this.constructor`.'
) : null);
} else {
if (!type._reactWarnedForThisType) {
try {
type._reactWarnedForThisType = true;
} catch (x) {
// just incase this is a frozen object or some special object
}
monitorCodeUse(
'react_non_component_in_jsx',
{ version: 3, name: type.name }
);
}
("production" !== "development" ? warning(
false,
'This JSX uses a plain function. Only React components are ' +
'valid in React\'s JSX transform.'
) : null);
}
}
function warnForNonLegacyFactory(type) {
("production" !== "development" ? warning(
false,
'Do not pass React.DOM.' + type.type + ' to JSX or createFactory. ' +
'Use the string "' + type + '" instead.'
) : null);
}
/**
* Transfer static properties from the source to the target. Functions are
* rebound to have this reflect the original source.
*/
function proxyStaticMethods(target, source) {
if (typeof source !== 'function') {
return;
}
for (var key in source) {
if (source.hasOwnProperty(key)) {
var value = source[key];
if (typeof value === 'function') {
var bound = value.bind(source);
// Copy any properties defined on the function, such as `isRequired` on
// a PropTypes validator.
for (var k in value) {
if (value.hasOwnProperty(k)) {
bound[k] = value[k];
}
}
target[key] = bound;
} else {
target[key] = value;
}
}
}
}
// We use an object instead of a boolean because booleans are ignored by our
// mocking libraries when these factories gets mocked.
var LEGACY_MARKER = {};
var NON_LEGACY_MARKER = {};
var ReactLegacyElementFactory = {};
ReactLegacyElementFactory.wrapCreateFactory = function(createFactory) {
var legacyCreateFactory = function(type) {
if (typeof type !== 'function') {
// Non-function types cannot be legacy factories
return createFactory(type);
}
if (type.isReactNonLegacyFactory) {
// This is probably a factory created by ReactDOM we unwrap it to get to
// the underlying string type. It shouldn't have been passed here so we
// warn.
if ("production" !== "development") {
warnForNonLegacyFactory(type);
}
return createFactory(type.type);
}
if (type.isReactLegacyFactory) {
// This is probably a legacy factory created by ReactCompositeComponent.
// We unwrap it to get to the underlying class.
return createFactory(type.type);
}
if ("production" !== "development") {
warnForPlainFunctionType(type);
}
// Unless it's a legacy factory, then this is probably a plain function,
// that is expecting to be invoked by JSX. We can just return it as is.
return type;
};
return legacyCreateFactory;
};
ReactLegacyElementFactory.wrapCreateElement = function(createElement) {
var legacyCreateElement = function(type, props, children) {
if (typeof type !== 'function') {
// Non-function types cannot be legacy factories
return createElement.apply(this, arguments);
}
var args;
if (type.isReactNonLegacyFactory) {
// This is probably a factory created by ReactDOM we unwrap it to get to
// the underlying string type. It shouldn't have been passed here so we
// warn.
if ("production" !== "development") {
warnForNonLegacyFactory(type);
}
args = Array.prototype.slice.call(arguments, 0);
args[0] = type.type;
return createElement.apply(this, args);
}
if (type.isReactLegacyFactory) {
// This is probably a legacy factory created by ReactCompositeComponent.
// We unwrap it to get to the underlying class.
if (type._isMockFunction) {
// If this is a mock function, people will expect it to be called. We
// will actually call the original mock factory function instead. This
// future proofs unit testing that assume that these are classes.
type.type._mockedReactClassConstructor = type;
}
args = Array.prototype.slice.call(arguments, 0);
args[0] = type.type;
return createElement.apply(this, args);
}
if ("production" !== "development") {
warnForPlainFunctionType(type);
}
// This is being called with a plain function we should invoke it
// immediately as if this was used with legacy JSX.
return type.apply(null, Array.prototype.slice.call(arguments, 1));
};
return legacyCreateElement;
};
ReactLegacyElementFactory.wrapFactory = function(factory) {
("production" !== "development" ? invariant(
typeof factory === 'function',
'This is suppose to accept a element factory'
) : invariant(typeof factory === 'function'));
var legacyElementFactory = function(config, children) {
// This factory should not be called when JSX is used. Use JSX instead.
if ("production" !== "development") {
warnForLegacyFactoryCall();
}
return factory.apply(this, arguments);
};
proxyStaticMethods(legacyElementFactory, factory.type);
legacyElementFactory.isReactLegacyFactory = LEGACY_MARKER;
legacyElementFactory.type = factory.type;
return legacyElementFactory;
};
// This is used to mark a factory that will remain. E.g. we're allowed to call
// it as a function. However, you're not suppose to pass it to createElement
// or createFactory, so it will warn you if you do.
ReactLegacyElementFactory.markNonLegacyFactory = function(factory) {
factory.isReactNonLegacyFactory = NON_LEGACY_MARKER;
return factory;
};
// Checks if a factory function is actually a legacy factory pretending to
// be a class.
ReactLegacyElementFactory.isValidFactory = function(factory) {
// TODO: This will be removed and moved into a class validator or something.
return typeof factory === 'function' &&
factory.isReactLegacyFactory === LEGACY_MARKER;
};
ReactLegacyElementFactory._isLegacyCallWarningEnabled = true;
module.exports = ReactLegacyElementFactory;
},{"./ReactCurrentOwner":42,"./invariant":140,"./monitorCodeUse":150,"./warning":160}],68:[function(_dereq_,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 ReactLink
* @typechecks static-only
*/
"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} />;
* },
* this._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_("./React");
/**
* @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: typeof 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;
},{"./React":31}],69:[function(_dereq_,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 ReactMarkupChecksum
*/
"use strict";
var adler32 = _dereq_("./adler32");
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);
return markup.replace(
'>',
' ' + 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;
},{"./adler32":110}],70:[function(_dereq_,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 ReactMount
*/
"use strict";
var DOMProperty = _dereq_("./DOMProperty");
var ReactBrowserEventEmitter = _dereq_("./ReactBrowserEventEmitter");
var ReactCurrentOwner = _dereq_("./ReactCurrentOwner");
var ReactElement = _dereq_("./ReactElement");
var ReactLegacyElement = _dereq_("./ReactLegacyElement");
var ReactInstanceHandles = _dereq_("./ReactInstanceHandles");
var ReactPerf = _dereq_("./ReactPerf");
var containsNode = _dereq_("./containsNode");
var deprecated = _dereq_("./deprecated");
var getReactRootElementInContainer = _dereq_("./getReactRootElementInContainer");
var instantiateReactComponent = _dereq_("./instantiateReactComponent");
var invariant = _dereq_("./invariant");
var shouldUpdateReactComponent = _dereq_("./shouldUpdateReactComponent");
var warning = _dereq_("./warning");
var createElement = ReactLegacyElement.wrapCreateElement(
ReactElement.createElement
);
var SEPARATOR = ReactInstanceHandles.SEPARATOR;
var ATTR_NAME = DOMProperty.ID_ATTRIBUTE_NAME;
var nodeCache = {};
var ELEMENT_NODE_TYPE = 1;
var DOC_NODE_TYPE = 9;
/** Mapping from reactRootID to React component instance. */
var instancesByReactRootID = {};
/** Mapping from reactRootID to `container` nodes. */
var containersByReactRootID = {};
if ("production" !== "development") {
/** __DEV__-only mapping from reactRootID to root elements. */
var rootElementsByReactRootID = {};
}
// Used to store breadth-first search state in findComponentRoot.
var findComponentRootReusableArray = [];
/**
* @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) {
var rootElement = getReactRootElementInContainer(container);
return rootElement && ReactMount.getID(rootElement);
}
/**
* Accessing node[ATTR_NAME] or calling getAttribute(ATTR_NAME) on a form
* element can return its control whose name or ID equals ATTR_NAME. All
* DOM nodes support `getAttributeNode` but this can also get called on
* other objects so just return '' if we're given something other than a
* DOM node (such as window).
*
* @param {?DOMElement|DOMWindow|DOMDocument|DOMTextNode} node DOM node.
* @return {string} ID of the supplied `domNode`.
*/
function getID(node) {
var id = internalGetID(node);
if (id) {
if (nodeCache.hasOwnProperty(id)) {
var cached = nodeCache[id];
if (cached !== node) {
("production" !== "development" ? invariant(
!isValid(cached, id),
'ReactMount: Two valid but unequal nodes with the same `%s`: %s',
ATTR_NAME, id
) : invariant(!isValid(cached, id)));
nodeCache[id] = node;
}
} else {
nodeCache[id] = node;
}
}
return id;
}
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 && node.getAttribute && node.getAttribute(ATTR_NAME) || '';
}
/**
* Sets the React-specific ID of the given node.
*
* @param {DOMElement} node The DOM node whose ID will be set.
* @param {string} id The value of the ID attribute.
*/
function setID(node, id) {
var oldID = internalGetID(node);
if (oldID !== id) {
delete nodeCache[oldID];
}
node.setAttribute(ATTR_NAME, id);
nodeCache[id] = node;
}
/**
* Finds the node with the supplied React-generated DOM ID.
*
* @param {string} id A React-generated DOM ID.
* @return {DOMElement} DOM node with the suppled `id`.
* @internal
*/
function getNode(id) {
if (!nodeCache.hasOwnProperty(id) || !isValid(nodeCache[id], id)) {
nodeCache[id] = ReactMount.findReactNodeByID(id);
}
return nodeCache[id];
}
/**
* A node is "valid" if it is contained by a currently mounted container.
*
* This means that the node does not have to be contained by a document in
* order to be considered valid.
*
* @param {?DOMElement} node The candidate DOM node.
* @param {string} id The expected ID of the node.
* @return {boolean} Whether the node is contained by a mounted container.
*/
function isValid(node, id) {
if (node) {
("production" !== "development" ? invariant(
internalGetID(node) === id,
'ReactMount: Unexpected modification of `%s`',
ATTR_NAME
) : invariant(internalGetID(node) === id));
var container = ReactMount.findReactContainerForID(id);
if (container && containsNode(container, node)) {
return true;
}
}
return false;
}
/**
* Causes the cache to forget about one React-specific ID.
*
* @param {string} id The ID to forget.
*/
function purgeID(id) {
delete nodeCache[id];
}
var deepestNodeSoFar = null;
function findDeepestCachedAncestorImpl(ancestorID) {
var ancestor = nodeCache[ancestorID];
if (ancestor && isValid(ancestor, ancestorID)) {
deepestNodeSoFar = ancestor;
} else {
// This node isn't populated in the cache, so presumably none of its
// descendants are. Break out of the loop.
return false;
}
}
/**
* Return the deepest cached node whose ID is a prefix of `targetID`.
*/
function findDeepestCachedAncestor(targetID) {
deepestNodeSoFar = null;
ReactInstanceHandles.traverseAncestors(
targetID,
findDeepestCachedAncestorImpl
);
var foundNode = deepestNodeSoFar;
deepestNodeSoFar = null;
return foundNode;
}
/**
* 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.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 = {
/** Exposed for debugging purposes **/
_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 {ReactComponent} nextComponent component instance to render
* @param {DOMElement} container container to render into
* @param {?function} callback function triggered on completion
*/
_updateRootComponent: function(
prevComponent,
nextComponent,
container,
callback) {
var nextProps = nextComponent.props;
ReactMount.scrollMonitor(container, function() {
prevComponent.replaceProps(nextProps, callback);
});
if ("production" !== "development") {
// Record the root element in case it later gets transplanted.
rootElementsByReactRootID[getReactRootID(container)] =
getReactRootElementInContainer(container);
}
return prevComponent;
},
/**
* Register a component into the instance map and starts scroll value
* monitoring
* @param {ReactComponent} nextComponent component instance to render
* @param {DOMElement} container container to render into
* @return {string} reactRoot ID prefix
*/
_registerComponent: function(nextComponent, container) {
("production" !== "development" ? invariant(
container && (
container.nodeType === ELEMENT_NODE_TYPE ||
container.nodeType === DOC_NODE_TYPE
),
'_registerComponent(...): Target container is not a DOM element.'
) : invariant(container && (
container.nodeType === ELEMENT_NODE_TYPE ||
container.nodeType === DOC_NODE_TYPE
)));
ReactBrowserEventEmitter.ensureScrollValueMonitoring();
var reactRootID = ReactMount.registerContainer(container);
instancesByReactRootID[reactRootID] = nextComponent;
return reactRootID;
},
/**
* Render a new component into the DOM.
* @param {ReactComponent} nextComponent component instance to render
* @param {DOMElement} container container to render into
* @param {boolean} shouldReuseMarkup if we should skip the markup insertion
* @return {ReactComponent} nextComponent
*/
_renderNewRootComponent: ReactPerf.measure(
'ReactMount',
'_renderNewRootComponent',
function(
nextComponent,
container,
shouldReuseMarkup) {
// Various parts of our code (such as ReactCompositeComponent's
// _renderValidatedComponent) assume that calls to render aren't nested;
// verify that that's the case.
("production" !== "development" ? 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.'
) : null);
var componentInstance = instantiateReactComponent(nextComponent, null);
var reactRootID = ReactMount._registerComponent(
componentInstance,
container
);
componentInstance.mountComponentIntoNode(
reactRootID,
container,
shouldReuseMarkup
);
if ("production" !== "development") {
// Record the root element in case it later gets transplanted.
rootElementsByReactRootID[reactRootID] =
getReactRootElementInContainer(container);
}
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 {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) {
("production" !== "development" ? invariant(
ReactElement.isValidElement(nextElement),
'renderComponent(): Invalid component element.%s',
(
typeof nextElement === 'string' ?
' Instead of passing an element string, make sure to instantiate ' +
'it by passing it to React.createElement.' :
ReactLegacyElement.isValidFactory(nextElement) ?
' Instead of passing a component class, make sure to instantiate ' +
'it by passing it to React.createElement.' :
// Check if it quacks like a element
typeof nextElement.props !== "undefined" ?
' This may be caused by unintentionally loading two independent ' +
'copies of React.' :
''
)
) : invariant(ReactElement.isValidElement(nextElement)));
var prevComponent = instancesByReactRootID[getReactRootID(container)];
if (prevComponent) {
var prevElement = prevComponent._currentElement;
if (shouldUpdateReactComponent(prevElement, nextElement)) {
return ReactMount._updateRootComponent(
prevComponent,
nextElement,
container,
callback
);
} else {
ReactMount.unmountComponentAtNode(container);
}
}
var reactRootElement = getReactRootElementInContainer(container);
var containerHasReactMarkup =
reactRootElement && ReactMount.isRenderedByReact(reactRootElement);
var shouldReuseMarkup = containerHasReactMarkup && !prevComponent;
var component = ReactMount._renderNewRootComponent(
nextElement,
container,
shouldReuseMarkup
);
callback && callback.call(component);
return component;
},
/**
* 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) {
var element = createElement(constructor, props);
return ReactMount.render(element, 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) {
var domNode = document.getElementById(id);
("production" !== "development" ? invariant(
domNode,
'Tried to get element with id of "%s" but it is not present on the page.',
id
) : invariant(domNode));
return ReactMount.constructAndRenderComponent(constructor, props, domNode);
},
/**
* Registers a container node into which React components will be rendered.
* This also creates the "reactRoot" 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.createReactRootID();
}
containersByReactRootID[reactRootID] = container;
return reactRootID;
},
/**
* 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.)
("production" !== "development" ? 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.'
) : null);
var reactRootID = getReactRootID(container);
var component = instancesByReactRootID[reactRootID];
if (!component) {
return false;
}
ReactMount.unmountComponentFromNode(component, container);
delete instancesByReactRootID[reactRootID];
delete containersByReactRootID[reactRootID];
if ("production" !== "development") {
delete rootElementsByReactRootID[reactRootID];
}
return true;
},
/**
* 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}
*/
unmountComponentFromNode: function(instance, container) {
instance.unmountComponent();
if (container.nodeType === DOC_NODE_TYPE) {
container = container.documentElement;
}
// http://jsperf.com/emptying-a-node
while (container.lastChild) {
container.removeChild(container.lastChild);
}
},
/**
* 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 reactRootID = ReactInstanceHandles.getReactRootIDFromNodeID(id);
var container = containersByReactRootID[reactRootID];
if ("production" !== "development") {
var rootElement = rootElementsByReactRootID[reactRootID];
if (rootElement && rootElement.parentNode !== container) {
("production" !== "development" ? invariant(
// Call internalGetID here because getID calls isValid which calls
// findReactContainerForID (this function).
internalGetID(rootElement) === reactRootID,
'ReactMount: Root element ID differed from reactRootID.'
) : invariant(// Call internalGetID here because getID calls isValid which calls
// findReactContainerForID (this function).
internalGetID(rootElement) === reactRootID));
var containerChild = container.firstChild;
if (containerChild &&
reactRootID === internalGetID(containerChild)) {
// If the container has a new child with the same ID as the old
// root element, then rootElementsByReactRootID[reactRootID] is
// just stale and needs to be updated. The case that deserves a
// warning is when the container is empty.
rootElementsByReactRootID[reactRootID] = containerChild;
} else {
console.warn(
'ReactMount: Root element has been removed from its original ' +
'container. New container:', rootElement.parentNode
);
}
}
}
return container;
},
/**
* Finds an element rendered by React with the supplied ID.
*
* @param {string} id ID of a DOM node in the React component.
* @return {DOMElement} Root DOM node of the React component.
*/
findReactNodeByID: function(id) {
var reactRoot = ReactMount.findReactContainerForID(id);
return ReactMount.findComponentRoot(reactRoot, id);
},
/**
* True if the supplied `node` is rendered by React.
*
* @param {*} node DOM Element to check.
* @return {boolean} True if the DOM Element appears to be rendered by React.
* @internal
*/
isRenderedByReact: function(node) {
if (node.nodeType !== 1) {
// Not a DOMElement, therefore not a React component
return false;
}
var id = ReactMount.getID(node);
return id ? id.charAt(0) === SEPARATOR : false;
},
/**
* Traverses up the ancestors of the supplied node to find a node that is a
* DOM representation of a React component.
*
* @param {*} node
* @return {?DOMEventTarget}
* @internal
*/
getFirstReactDOM: function(node) {
var current = node;
while (current && current.parentNode !== current) {
if (ReactMount.isRenderedByReact(current)) {
return current;
}
current = current.parentNode;
}
return null;
},
/**
* Finds a node with the supplied `targetID` inside of the supplied
* `ancestorNode`. Exploits the ID naming scheme to perform the search
* quickly.
*
* @param {DOMEventTarget} ancestorNode Search from this root.
* @pararm {string} targetID ID of the DOM representation of the component.
* @return {DOMEventTarget} DOM node with the supplied `targetID`.
* @internal
*/
findComponentRoot: function(ancestorNode, targetID) {
var firstChildren = findComponentRootReusableArray;
var childIndex = 0;
var deepestAncestor = findDeepestCachedAncestor(targetID) || ancestorNode;
firstChildren[0] = deepestAncestor.firstChild;
firstChildren.length = 1;
while (childIndex < firstChildren.length) {
var child = firstChildren[childIndex++];
var targetChild;
while (child) {
var childID = ReactMount.getID(child);
if (childID) {
// Even if we find the node we're looking for, we finish looping
// through its siblings to ensure they're cached so that we don't have
// to revisit this node again. Otherwise, we make n^2 calls to getID
// when visiting the many children of a single node in order.
if (targetID === childID) {
targetChild = child;
} else if (ReactInstanceHandles.isAncestorIDOf(childID, targetID)) {
// If we find a child whose ID is an ancestor of the given ID,
// then we can be sure that we only want to search the subtree
// rooted at this child, so we can throw out the rest of the
// search state.
firstChildren.length = childIndex = 0;
firstChildren.push(child.firstChild);
}
} else {
// If this child had no ID, then there's a chance that it was
// injected automatically by the browser, as when a `<table>`
// element sprouts an extra `<tbody>` child as a side effect of
// `.innerHTML` parsing. Optimistically continue down this
// branch, but not before examining the other siblings.
firstChildren.push(child.firstChild);
}
child = child.nextSibling;
}
if (targetChild) {
// Emptying firstChildren/findComponentRootReusableArray is
// not necessary for correctness, but it helps the GC reclaim
// any nodes that were left at the end of the search.
firstChildren.length = 0;
return targetChild;
}
}
firstChildren.length = 0;
("production" !== "development" ? invariant(
false,
'findComponentRoot(..., %s): Unable to find element. This probably ' +
'means the DOM was unexpectedly mutated (e.g., by the browser), ' +
'usually due to forgetting a <tbody> when using tables, nesting tags ' +
'like <form>, <p>, or <a>, or using non-SVG elements in an <svg> ' +
'parent. ' +
'Try inspecting the child nodes of the element with React ID `%s`.',
targetID,
ReactMount.getID(ancestorNode)
) : invariant(false));
},
/**
* React ID utilities.
*/
getReactRootID: getReactRootID,
getID: getID,
setID: setID,
getNode: getNode,
purgeID: purgeID
};
// Deprecations (remove for 0.13)
ReactMount.renderComponent = deprecated(
'ReactMount',
'renderComponent',
'render',
this,
ReactMount.render
);
module.exports = ReactMount;
},{"./DOMProperty":12,"./ReactBrowserEventEmitter":33,"./ReactCurrentOwner":42,"./ReactElement":58,"./ReactInstanceHandles":66,"./ReactLegacyElement":67,"./ReactPerf":75,"./containsNode":114,"./deprecated":120,"./getReactRootElementInContainer":134,"./instantiateReactComponent":139,"./invariant":140,"./shouldUpdateReactComponent":156,"./warning":160}],71:[function(_dereq_,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 ReactMultiChild
* @typechecks static-only
*/
"use strict";
var ReactComponent = _dereq_("./ReactComponent");
var ReactMultiChildUpdateTypes = _dereq_("./ReactMultiChildUpdateTypes");
var flattenChildren = _dereq_("./flattenChildren");
var instantiateReactComponent = _dereq_("./instantiateReactComponent");
var shouldUpdateReactComponent = _dereq_("./shouldUpdateReactComponent");
/**
* Updating children of a component may trigger recursive updates. The depth is
* used to batch recursive updates to render markup more efficiently.
*
* @type {number}
* @private
*/
var updateDepth = 0;
/**
* Queue of update configuration objects.
*
* Each object has a `type` property that is in `ReactMultiChildUpdateTypes`.
*
* @type {array<object>}
* @private
*/
var updateQueue = [];
/**
* Queue of markup to be rendered.
*
* @type {array<string>}
* @private
*/
var markupQueue = [];
/**
* Enqueues markup to be rendered and inserted at a supplied index.
*
* @param {string} parentID ID of the parent component.
* @param {string} markup Markup that renders into an element.
* @param {number} toIndex Destination index.
* @private
*/
function enqueueMarkup(parentID, markup, toIndex) {
// NOTE: Null values reduce hidden classes.
updateQueue.push({
parentID: parentID,
parentNode: null,
type: ReactMultiChildUpdateTypes.INSERT_MARKUP,
markupIndex: markupQueue.push(markup) - 1,
textContent: null,
fromIndex: null,
toIndex: toIndex
});
}
/**
* Enqueues moving an existing element to another index.
*
* @param {string} parentID ID of the parent component.
* @param {number} fromIndex Source index of the existing element.
* @param {number} toIndex Destination index of the element.
* @private
*/
function enqueueMove(parentID, fromIndex, toIndex) {
// NOTE: Null values reduce hidden classes.
updateQueue.push({
parentID: parentID,
parentNode: null,
type: ReactMultiChildUpdateTypes.MOVE_EXISTING,
markupIndex: null,
textContent: null,
fromIndex: fromIndex,
toIndex: toIndex
});
}
/**
* Enqueues removing an element at an index.
*
* @param {string} parentID ID of the parent component.
* @param {number} fromIndex Index of the element to remove.
* @private
*/
function enqueueRemove(parentID, fromIndex) {
// NOTE: Null values reduce hidden classes.
updateQueue.push({
parentID: parentID,
parentNode: null,
type: ReactMultiChildUpdateTypes.REMOVE_NODE,
markupIndex: null,
textContent: null,
fromIndex: fromIndex,
toIndex: null
});
}
/**
* Enqueues setting the text content.
*
* @param {string} parentID ID of the parent component.
* @param {string} textContent Text content to set.
* @private
*/
function enqueueTextContent(parentID, textContent) {
// NOTE: Null values reduce hidden classes.
updateQueue.push({
parentID: parentID,
parentNode: null,
type: ReactMultiChildUpdateTypes.TEXT_CONTENT,
markupIndex: null,
textContent: textContent,
fromIndex: null,
toIndex: null
});
}
/**
* Processes any enqueued updates.
*
* @private
*/
function processQueue() {
if (updateQueue.length) {
ReactComponent.BackendIDOperations.dangerouslyProcessChildrenUpdates(
updateQueue,
markupQueue
);
clearQueue();
}
}
/**
* Clears any enqueued updates.
*
* @private
*/
function clearQueue() {
updateQueue.length = 0;
markupQueue.length = 0;
}
/**
* 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: {
/**
* 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) {
var children = flattenChildren(nestedChildren);
var mountImages = [];
var index = 0;
this._renderedChildren = children;
for (var name in children) {
var child = children[name];
if (children.hasOwnProperty(name)) {
// The rendered children must be turned into instances as they're
// mounted.
var childInstance = instantiateReactComponent(child, null);
children[name] = childInstance;
// Inlined for performance, see `ReactInstanceHandles.createReactID`.
var rootID = this._rootNodeID + name;
var mountImage = childInstance.mountComponent(
rootID,
transaction,
this._mountDepth + 1
);
childInstance._mountIndex = index;
mountImages.push(mountImage);
index++;
}
}
return mountImages;
},
/**
* Replaces any rendered children with a text content string.
*
* @param {string} nextContent String of content.
* @internal
*/
updateTextContent: function(nextContent) {
updateDepth++;
var errorThrown = true;
try {
var prevChildren = this._renderedChildren;
// Remove any rendered children.
for (var name in prevChildren) {
if (prevChildren.hasOwnProperty(name)) {
this._unmountChildByName(prevChildren[name], name);
}
}
// Set new text content.
this.setTextContent(nextContent);
errorThrown = false;
} finally {
updateDepth--;
if (!updateDepth) {
errorThrown ? clearQueue() : processQueue();
}
}
},
/**
* Updates the rendered children with new children.
*
* @param {?object} nextNestedChildren Nested child maps.
* @param {ReactReconcileTransaction} transaction
* @internal
*/
updateChildren: function(nextNestedChildren, transaction) {
updateDepth++;
var errorThrown = true;
try {
this._updateChildren(nextNestedChildren, transaction);
errorThrown = false;
} finally {
updateDepth--;
if (!updateDepth) {
errorThrown ? clearQueue() : processQueue();
}
}
},
/**
* Improve performance by isolating this hot code path from the try/catch
* block in `updateChildren`.
*
* @param {?object} nextNestedChildren Nested child maps.
* @param {ReactReconcileTransaction} transaction
* @final
* @protected
*/
_updateChildren: function(nextNestedChildren, transaction) {
var nextChildren = flattenChildren(nextNestedChildren);
var prevChildren = this._renderedChildren;
if (!nextChildren && !prevChildren) {
return;
}
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;
for (name in nextChildren) {
if (!nextChildren.hasOwnProperty(name)) {
continue;
}
var prevChild = prevChildren && prevChildren[name];
var prevElement = prevChild && prevChild._currentElement;
var nextElement = nextChildren[name];
if (shouldUpdateReactComponent(prevElement, nextElement)) {
this.moveChild(prevChild, nextIndex, lastIndex);
lastIndex = Math.max(prevChild._mountIndex, lastIndex);
prevChild.receiveComponent(nextElement, transaction);
prevChild._mountIndex = nextIndex;
} else {
if (prevChild) {
// Update `lastIndex` before `_mountIndex` gets unset by unmounting.
lastIndex = Math.max(prevChild._mountIndex, lastIndex);
this._unmountChildByName(prevChild, name);
}
// The child must be instantiated before it's mounted.
var nextChildInstance = instantiateReactComponent(
nextElement,
null
);
this._mountChildByNameAtIndex(
nextChildInstance, name, nextIndex, transaction
);
}
nextIndex++;
}
// Remove children that are no longer present.
for (name in prevChildren) {
if (prevChildren.hasOwnProperty(name) &&
!(nextChildren && nextChildren[name])) {
this._unmountChildByName(prevChildren[name], name);
}
}
},
/**
* Unmounts all rendered children. This should be used to clean up children
* when this component is unmounted.
*
* @internal
*/
unmountChildren: function() {
var renderedChildren = this._renderedChildren;
for (var name in renderedChildren) {
var renderedChild = renderedChildren[name];
// TODO: When is this not true?
if (renderedChild.unmountComponent) {
renderedChild.unmountComponent();
}
}
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, 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) {
enqueueMove(this._rootNodeID, child._mountIndex, toIndex);
}
},
/**
* Creates a child component.
*
* @param {ReactComponent} child Component to create.
* @param {string} mountImage Markup to insert.
* @protected
*/
createChild: function(child, mountImage) {
enqueueMarkup(this._rootNodeID, mountImage, child._mountIndex);
},
/**
* Removes a child component.
*
* @param {ReactComponent} child Child to remove.
* @protected
*/
removeChild: function(child) {
enqueueRemove(this._rootNodeID, child._mountIndex);
},
/**
* Sets this text content string.
*
* @param {string} textContent Text content to set.
* @protected
*/
setTextContent: function(textContent) {
enqueueTextContent(this._rootNodeID, textContent);
},
/**
* 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
*/
_mountChildByNameAtIndex: function(child, name, index, transaction) {
// Inlined for performance, see `ReactInstanceHandles.createReactID`.
var rootID = this._rootNodeID + name;
var mountImage = child.mountComponent(
rootID,
transaction,
this._mountDepth + 1
);
child._mountIndex = index;
this.createChild(child, mountImage);
this._renderedChildren = this._renderedChildren || {};
this._renderedChildren[name] = child;
},
/**
* Unmounts a rendered child by name.
*
* NOTE: This is part of `updateChildren` and is here for readability.
*
* @param {ReactComponent} child Component to unmount.
* @param {string} name Name of the child in `this._renderedChildren`.
* @private
*/
_unmountChildByName: function(child, name) {
this.removeChild(child);
child._mountIndex = null;
child.unmountComponent();
delete this._renderedChildren[name];
}
}
};
module.exports = ReactMultiChild;
},{"./ReactComponent":37,"./ReactMultiChildUpdateTypes":72,"./flattenChildren":124,"./instantiateReactComponent":139,"./shouldUpdateReactComponent":156}],72:[function(_dereq_,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 ReactMultiChildUpdateTypes
*/
"use strict";
var keyMirror = _dereq_("./keyMirror");
/**
* 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,
TEXT_CONTENT: null
});
module.exports = ReactMultiChildUpdateTypes;
},{"./keyMirror":146}],73:[function(_dereq_,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 ReactNativeComponent
*/
"use strict";
var assign = _dereq_("./Object.assign");
var invariant = _dereq_("./invariant");
var genericComponentClass = null;
// This registry keeps track of wrapper classes around native tags
var tagToComponentClass = {};
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 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);
}
};
/**
* Create an internal class for a specific tag.
*
* @param {string} tag The tag for which to create an internal instance.
* @param {any} props The props passed to the instance constructor.
* @return {ReactComponent} component The injected empty component.
*/
function createInstanceForTag(tag, props, parentType) {
var componentClass = tagToComponentClass[tag];
if (componentClass == null) {
("production" !== "development" ? invariant(
genericComponentClass,
'There is no registered component for the tag %s',
tag
) : invariant(genericComponentClass));
return new genericComponentClass(tag, props);
}
if (parentType === tag) {
// Avoid recursion
("production" !== "development" ? invariant(
genericComponentClass,
'There is no registered component for the tag %s',
tag
) : invariant(genericComponentClass));
return new genericComponentClass(tag, props);
}
// Unwrap legacy factories
return new componentClass.type(props);
}
var ReactNativeComponent = {
createInstanceForTag: createInstanceForTag,
injection: ReactNativeComponentInjection
};
module.exports = ReactNativeComponent;
},{"./Object.assign":29,"./invariant":140}],74:[function(_dereq_,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 ReactOwner
*/
"use strict";
var emptyObject = _dereq_("./emptyObject");
var invariant = _dereq_("./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: 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) {
("production" !== "development" ? invariant(
ReactOwner.isValidOwner(owner),
'addComponentAsRefTo(...): Only a ReactOwner can have refs. This ' +
'usually means that you\'re trying to add a ref to a component that ' +
'doesn\'t have an owner (that is, was not created inside of another ' +
'component\'s `render` method). Try rendering this component inside of ' +
'a new top-level component which will hold the ref.'
) : invariant(ReactOwner.isValidOwner(owner)));
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) {
("production" !== "development" ? invariant(
ReactOwner.isValidOwner(owner),
'removeComponentAsRefFrom(...): Only a ReactOwner can have refs. This ' +
'usually means that you\'re trying to remove a ref to a component that ' +
'doesn\'t have an owner (that is, was not created inside of another ' +
'component\'s `render` method). Try rendering this component inside of ' +
'a new top-level component which will hold the ref.'
) : invariant(ReactOwner.isValidOwner(owner)));
// 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: {
construct: function() {
this.refs = emptyObject;
},
/**
* 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) {
("production" !== "development" ? invariant(
component.isOwnedBy(this),
'attachRef(%s, ...): Only a component\'s owner can store a ref to it.',
ref
) : invariant(component.isOwnedBy(this)));
var refs = this.refs === emptyObject ? (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;
},{"./emptyObject":122,"./invariant":140}],75:[function(_dereq_,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 ReactPerf
* @typechecks static-only
*/
"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,
/**
* 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 ("production" !== "development") {
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;
},{}],76:[function(_dereq_,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 ReactPropTransferer
*/
"use strict";
var assign = _dereq_("./Object.assign");
var emptyFunction = _dereq_("./emptyFunction");
var invariant = _dereq_("./invariant");
var joinClasses = _dereq_("./joinClasses");
var warning = _dereq_("./warning");
var didWarn = false;
/**
* 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);
}
};
}
var transferStrategyMerge = createTransferStrategy(function(a, b) {
// `merge` overrides the first object's (`props[key]` above) keys using the
// second object's (`value`) keys. An object's style's existing `propA` would
// get overridden. Flip the order here.
return assign({}, b, a);
});
/**
* Transfer strategies dictate how props are transferred by `transferPropsTo`.
* NOTE: if you add any more exceptions to this list you should be sure to
* update `cloneWithProps()` accordingly.
*/
var TransferStrategies = {
/**
* Never transfer `children`.
*/
children: emptyFunction,
/**
* Transfer the `className` prop by merging them.
*/
className: createTransferStrategy(joinClasses),
/**
* Transfer the `style` prop (which is an object) by merging them.
*/
style: transferStrategyMerge
};
/**
* Mutates the first argument by transferring the properties from the second
* argument.
*
* @param {object} props
* @param {object} newProps
* @return {object}
*/
function transferInto(props, newProps) {
for (var thisKey in newProps) {
if (!newProps.hasOwnProperty(thisKey)) {
continue;
}
var transferStrategy = TransferStrategies[thisKey];
if (transferStrategy && TransferStrategies.hasOwnProperty(thisKey)) {
transferStrategy(props, thisKey, newProps[thisKey]);
} else if (!props.hasOwnProperty(thisKey)) {
props[thisKey] = newProps[thisKey];
}
}
return props;
}
/**
* ReactPropTransferer are capable of transferring props to another component
* using a `transferPropsTo` method.
*
* @class ReactPropTransferer
*/
var ReactPropTransferer = {
TransferStrategies: TransferStrategies,
/**
* Merge two props objects using TransferStrategies.
*
* @param {object} oldProps original props (they take precedence)
* @param {object} newProps new props to merge in
* @return {object} a new object containing both sets of props merged.
*/
mergeProps: function(oldProps, newProps) {
return transferInto(assign({}, oldProps), newProps);
},
/**
* @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 {ReactElement} element Component receiving the properties.
* @return {ReactElement} The supplied `component`.
* @final
* @protected
*/
transferPropsTo: function(element) {
("production" !== "development" ? invariant(
element._owner === this,
'%s: You can\'t call transferPropsTo() on a component that you ' +
'don\'t own, %s. This usually means you are calling ' +
'transferPropsTo() on a component passed in as props or children.',
this.constructor.displayName,
typeof element.type === 'string' ?
element.type :
element.type.displayName
) : invariant(element._owner === this));
if ("production" !== "development") {
if (!didWarn) {
didWarn = true;
("production" !== "development" ? warning(
false,
'transferPropsTo is deprecated. ' +
'See http://fb.me/react-transferpropsto for more information.'
) : null);
}
}
// Because elements are immutable we have to merge into the existing
// props object rather than clone it.
transferInto(element.props, this.props);
return element;
}
}
};
module.exports = ReactPropTransferer;
},{"./Object.assign":29,"./emptyFunction":121,"./invariant":140,"./joinClasses":145,"./warning":160}],77:[function(_dereq_,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 ReactPropTypeLocationNames
*/
"use strict";
var ReactPropTypeLocationNames = {};
if ("production" !== "development") {
ReactPropTypeLocationNames = {
prop: 'prop',
context: 'context',
childContext: 'child context'
};
}
module.exports = ReactPropTypeLocationNames;
},{}],78:[function(_dereq_,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 ReactPropTypeLocations
*/
"use strict";
var keyMirror = _dereq_("./keyMirror");
var ReactPropTypeLocations = keyMirror({
prop: null,
context: null,
childContext: null
});
module.exports = ReactPropTypeLocations;
},{"./keyMirror":146}],79:[function(_dereq_,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 ReactPropTypes
*/
"use strict";
var ReactElement = _dereq_("./ReactElement");
var ReactPropTypeLocationNames = _dereq_("./ReactPropTypeLocationNames");
var deprecated = _dereq_("./deprecated");
var emptyFunction = _dereq_("./emptyFunction");
/**
* 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 elementTypeChecker = createElementTypeChecker();
var nodeTypeChecker = createNodeChecker();
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: elementTypeChecker,
instanceOf: createInstanceTypeChecker,
node: nodeTypeChecker,
objectOf: createObjectOfTypeChecker,
oneOf: createEnumTypeChecker,
oneOfType: createUnionTypeChecker,
shape: createShapeTypeChecker,
component: deprecated(
'React.PropTypes',
'component',
'element',
this,
elementTypeChecker
),
renderable: deprecated(
'React.PropTypes',
'renderable',
'node',
this,
nodeTypeChecker
)
};
function createChainableTypeChecker(validate) {
function checkType(isRequired, props, propName, componentName, location) {
componentName = componentName || ANONYMOUS;
if (props[propName] == null) {
var locationName = ReactPropTypeLocationNames[location];
if (isRequired) {
return new Error(
("Required " + locationName + " `" + propName + "` was not specified in ")+
("`" + componentName + "`.")
);
}
} else {
return validate(props, propName, componentName, location);
}
}
var chainedCheckType = checkType.bind(null, false);
chainedCheckType.isRequired = checkType.bind(null, true);
return chainedCheckType;
}
function createPrimitiveTypeChecker(expectedType) {
function validate(props, propName, componentName, location) {
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 + " `" + propName + "` of type `" + preciseType + "` ") +
("supplied to `" + componentName + "`, expected `" + expectedType + "`.")
);
}
}
return createChainableTypeChecker(validate);
}
function createAnyTypeChecker() {
return createChainableTypeChecker(emptyFunction.thatReturns());
}
function createArrayOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location) {
var propValue = props[propName];
if (!Array.isArray(propValue)) {
var locationName = ReactPropTypeLocationNames[location];
var propType = getPropType(propValue);
return new Error(
("Invalid " + locationName + " `" + propName + "` of type ") +
("`" + propType + "` supplied to `" + componentName + "`, expected an array.")
);
}
for (var i = 0; i < propValue.length; i++) {
var error = typeChecker(propValue, i, componentName, location);
if (error instanceof Error) {
return error;
}
}
}
return createChainableTypeChecker(validate);
}
function createElementTypeChecker() {
function validate(props, propName, componentName, location) {
if (!ReactElement.isValidElement(props[propName])) {
var locationName = ReactPropTypeLocationNames[location];
return new Error(
("Invalid " + locationName + " `" + propName + "` supplied to ") +
("`" + componentName + "`, expected a ReactElement.")
);
}
}
return createChainableTypeChecker(validate);
}
function createInstanceTypeChecker(expectedClass) {
function validate(props, propName, componentName, location) {
if (!(props[propName] instanceof expectedClass)) {
var locationName = ReactPropTypeLocationNames[location];
var expectedClassName = expectedClass.name || ANONYMOUS;
return new Error(
("Invalid " + locationName + " `" + propName + "` supplied to ") +
("`" + componentName + "`, expected instance of `" + expectedClassName + "`.")
);
}
}
return createChainableTypeChecker(validate);
}
function createEnumTypeChecker(expectedValues) {
function validate(props, propName, componentName, location) {
var propValue = props[propName];
for (var i = 0; i < expectedValues.length; i++) {
if (propValue === expectedValues[i]) {
return;
}
}
var locationName = ReactPropTypeLocationNames[location];
var valuesString = JSON.stringify(expectedValues);
return new Error(
("Invalid " + locationName + " `" + propName + "` of value `" + propValue + "` ") +
("supplied to `" + componentName + "`, expected one of " + valuesString + ".")
);
}
return createChainableTypeChecker(validate);
}
function createObjectOfTypeChecker(typeChecker) {
function validate(props, propName, componentName, location) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
var locationName = ReactPropTypeLocationNames[location];
return new Error(
("Invalid " + locationName + " `" + propName + "` 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);
if (error instanceof Error) {
return error;
}
}
}
}
return createChainableTypeChecker(validate);
}
function createUnionTypeChecker(arrayOfTypeCheckers) {
function validate(props, propName, componentName, location) {
for (var i = 0; i < arrayOfTypeCheckers.length; i++) {
var checker = arrayOfTypeCheckers[i];
if (checker(props, propName, componentName, location) == null) {
return;
}
}
var locationName = ReactPropTypeLocationNames[location];
return new Error(
("Invalid " + locationName + " `" + propName + "` supplied to ") +
("`" + componentName + "`.")
);
}
return createChainableTypeChecker(validate);
}
function createNodeChecker() {
function validate(props, propName, componentName, location) {
if (!isNode(props[propName])) {
var locationName = ReactPropTypeLocationNames[location];
return new Error(
("Invalid " + locationName + " `" + propName + "` supplied to ") +
("`" + componentName + "`, expected a ReactNode.")
);
}
}
return createChainableTypeChecker(validate);
}
function createShapeTypeChecker(shapeTypes) {
function validate(props, propName, componentName, location) {
var propValue = props[propName];
var propType = getPropType(propValue);
if (propType !== 'object') {
var locationName = ReactPropTypeLocationNames[location];
return new Error(
("Invalid " + locationName + " `" + propName + "` 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);
if (error) {
return error;
}
}
}
return createChainableTypeChecker(validate, 'expected `object`');
}
function isNode(propValue) {
switch(typeof propValue) {
case 'number':
case 'string':
return true;
case 'boolean':
return !propValue;
case 'object':
if (Array.isArray(propValue)) {
return propValue.every(isNode);
}
if (ReactElement.isValidElement(propValue)) {
return true;
}
for (var k in propValue) {
if (!isNode(propValue[k])) {
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;
}
module.exports = ReactPropTypes;
},{"./ReactElement":58,"./ReactPropTypeLocationNames":77,"./deprecated":120,"./emptyFunction":121}],80:[function(_dereq_,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 ReactPutListenerQueue
*/
"use strict";
var PooledClass = _dereq_("./PooledClass");
var ReactBrowserEventEmitter = _dereq_("./ReactBrowserEventEmitter");
var assign = _dereq_("./Object.assign");
function ReactPutListenerQueue() {
this.listenersToPut = [];
}
assign(ReactPutListenerQueue.prototype, {
enqueuePutListener: function(rootNodeID, propKey, propValue) {
this.listenersToPut.push({
rootNodeID: rootNodeID,
propKey: propKey,
propValue: propValue
});
},
putListeners: function() {
for (var i = 0; i < this.listenersToPut.length; i++) {
var listenerToPut = this.listenersToPut[i];
ReactBrowserEventEmitter.putListener(
listenerToPut.rootNodeID,
listenerToPut.propKey,
listenerToPut.propValue
);
}
},
reset: function() {
this.listenersToPut.length = 0;
},
destructor: function() {
this.reset();
}
});
PooledClass.addPoolingTo(ReactPutListenerQueue);
module.exports = ReactPutListenerQueue;
},{"./Object.assign":29,"./PooledClass":30,"./ReactBrowserEventEmitter":33}],81:[function(_dereq_,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 ReactReconcileTransaction
* @typechecks static-only
*/
"use strict";
var CallbackQueue = _dereq_("./CallbackQueue");
var PooledClass = _dereq_("./PooledClass");
var ReactBrowserEventEmitter = _dereq_("./ReactBrowserEventEmitter");
var ReactInputSelection = _dereq_("./ReactInputSelection");
var ReactPutListenerQueue = _dereq_("./ReactPutListenerQueue");
var Transaction = _dereq_("./Transaction");
var assign = _dereq_("./Object.assign");
/**
* 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 occured. `close`
* restores the previous value.
*/
close: function(previouslyEnabled) {
ReactBrowserEventEmitter.setEnabled(previouslyEnabled);
}
};
/**
* Provides a queue for collecting `componentDidMount` and
* `componentDidUpdate` callbacks during the 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();
}
};
var PUT_LISTENER_QUEUEING = {
initialize: function() {
this.putListenerQueue.reset();
},
close: function() {
this.putListenerQueue.putListeners();
}
};
/**
* 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 = [
PUT_LISTENER_QUEUEING,
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();
// 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.putListenerQueue = ReactPutListenerQueue.getPooled();
}
var Mixin = {
/**
* @see Transaction
* @abstract
* @final
* @return {array<object>} List of operation wrap proceedures.
* TODO: convert to array<TransactionWrapper>
*/
getTransactionWrappers: function() {
return TRANSACTION_WRAPPERS;
},
/**
* @return {object} The queue to collect `onDOMReady` callbacks with.
*/
getReactMountReady: function() {
return this.reactMountReady;
},
getPutListenerQueue: function() {
return this.putListenerQueue;
},
/**
* `PooledClass` looks for this, and will invoke this before allowing this
* instance to be resused.
*/
destructor: function() {
CallbackQueue.release(this.reactMountReady);
this.reactMountReady = null;
ReactPutListenerQueue.release(this.putListenerQueue);
this.putListenerQueue = null;
}
};
assign(ReactReconcileTransaction.prototype, Transaction.Mixin, Mixin);
PooledClass.addPoolingTo(ReactReconcileTransaction);
module.exports = ReactReconcileTransaction;
},{"./CallbackQueue":7,"./Object.assign":29,"./PooledClass":30,"./ReactBrowserEventEmitter":33,"./ReactInputSelection":65,"./ReactPutListenerQueue":80,"./Transaction":107}],82:[function(_dereq_,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 ReactRootIndex
* @typechecks
*/
"use strict";
var ReactRootIndexInjection = {
/**
* @param {function} _createReactRootIndex
*/
injectCreateReactRootIndex: function(_createReactRootIndex) {
ReactRootIndex.createReactRootIndex = _createReactRootIndex;
}
};
var ReactRootIndex = {
createReactRootIndex: null,
injection: ReactRootIndexInjection
};
module.exports = ReactRootIndex;
},{}],83:[function(_dereq_,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.
*
* @typechecks static-only
* @providesModule ReactServerRendering
*/
"use strict";
var ReactElement = _dereq_("./ReactElement");
var ReactInstanceHandles = _dereq_("./ReactInstanceHandles");
var ReactMarkupChecksum = _dereq_("./ReactMarkupChecksum");
var ReactServerRenderingTransaction =
_dereq_("./ReactServerRenderingTransaction");
var instantiateReactComponent = _dereq_("./instantiateReactComponent");
var invariant = _dereq_("./invariant");
/**
* @param {ReactElement} element
* @return {string} the HTML markup
*/
function renderToString(element) {
("production" !== "development" ? invariant(
ReactElement.isValidElement(element),
'renderToString(): You must pass a valid ReactElement.'
) : invariant(ReactElement.isValidElement(element)));
var transaction;
try {
var id = ReactInstanceHandles.createReactRootID();
transaction = ReactServerRenderingTransaction.getPooled(false);
return transaction.perform(function() {
var componentInstance = instantiateReactComponent(element, null);
var markup = componentInstance.mountComponent(id, transaction, 0);
return ReactMarkupChecksum.addChecksumToMarkup(markup);
}, null);
} finally {
ReactServerRenderingTransaction.release(transaction);
}
}
/**
* @param {ReactElement} element
* @return {string} the HTML markup, without the extra React ID and checksum
* (for generating static pages)
*/
function renderToStaticMarkup(element) {
("production" !== "development" ? invariant(
ReactElement.isValidElement(element),
'renderToStaticMarkup(): You must pass a valid ReactElement.'
) : invariant(ReactElement.isValidElement(element)));
var transaction;
try {
var id = ReactInstanceHandles.createReactRootID();
transaction = ReactServerRenderingTransaction.getPooled(true);
return transaction.perform(function() {
var componentInstance = instantiateReactComponent(element, null);
return componentInstance.mountComponent(id, transaction, 0);
}, null);
} finally {
ReactServerRenderingTransaction.release(transaction);
}
}
module.exports = {
renderToString: renderToString,
renderToStaticMarkup: renderToStaticMarkup
};
},{"./ReactElement":58,"./ReactInstanceHandles":66,"./ReactMarkupChecksum":69,"./ReactServerRenderingTransaction":84,"./instantiateReactComponent":139,"./invariant":140}],84:[function(_dereq_,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 ReactServerRenderingTransaction
* @typechecks
*/
"use strict";
var PooledClass = _dereq_("./PooledClass");
var CallbackQueue = _dereq_("./CallbackQueue");
var ReactPutListenerQueue = _dereq_("./ReactPutListenerQueue");
var Transaction = _dereq_("./Transaction");
var assign = _dereq_("./Object.assign");
var emptyFunction = _dereq_("./emptyFunction");
/**
* Provides a `CallbackQueue` queue for collecting `onDOMReady` callbacks
* during the performing of the transaction.
*/
var ON_DOM_READY_QUEUEING = {
/**
* Initializes the internal `onDOMReady` queue.
*/
initialize: function() {
this.reactMountReady.reset();
},
close: emptyFunction
};
var PUT_LISTENER_QUEUEING = {
initialize: function() {
this.putListenerQueue.reset();
},
close: emptyFunction
};
/**
* 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 = [
PUT_LISTENER_QUEUEING,
ON_DOM_READY_QUEUEING
];
/**
* @class ReactServerRenderingTransaction
* @param {boolean} renderToStaticMarkup
*/
function ReactServerRenderingTransaction(renderToStaticMarkup) {
this.reinitializeTransaction();
this.renderToStaticMarkup = renderToStaticMarkup;
this.reactMountReady = CallbackQueue.getPooled(null);
this.putListenerQueue = ReactPutListenerQueue.getPooled();
}
var Mixin = {
/**
* @see Transaction
* @abstract
* @final
* @return {array} Empty list of operation wrap proceedures.
*/
getTransactionWrappers: function() {
return TRANSACTION_WRAPPERS;
},
/**
* @return {object} The queue to collect `onDOMReady` callbacks with.
*/
getReactMountReady: function() {
return this.reactMountReady;
},
getPutListenerQueue: function() {
return this.putListenerQueue;
},
/**
* `PooledClass` looks for this, and will invoke this before allowing this
* instance to be resused.
*/
destructor: function() {
CallbackQueue.release(this.reactMountReady);
this.reactMountReady = null;
ReactPutListenerQueue.release(this.putListenerQueue);
this.putListenerQueue = null;
}
};
assign(
ReactServerRenderingTransaction.prototype,
Transaction.Mixin,
Mixin
);
PooledClass.addPoolingTo(ReactServerRenderingTransaction);
module.exports = ReactServerRenderingTransaction;
},{"./CallbackQueue":7,"./Object.assign":29,"./PooledClass":30,"./ReactPutListenerQueue":80,"./Transaction":107,"./emptyFunction":121}],85:[function(_dereq_,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 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;
},{}],86:[function(_dereq_,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 ReactTestUtils
*/
"use strict";
var EventConstants = _dereq_("./EventConstants");
var EventPluginHub = _dereq_("./EventPluginHub");
var EventPropagators = _dereq_("./EventPropagators");
var React = _dereq_("./React");
var ReactElement = _dereq_("./ReactElement");
var ReactBrowserEventEmitter = _dereq_("./ReactBrowserEventEmitter");
var ReactMount = _dereq_("./ReactMount");
var ReactTextComponent = _dereq_("./ReactTextComponent");
var ReactUpdates = _dereq_("./ReactUpdates");
var SyntheticEvent = _dereq_("./SyntheticEvent");
var assign = _dereq_("./Object.assign");
var topLevelTypes = EventConstants.topLevelTypes;
function Event(suffix) {}
/**
* @class ReactTestUtils
*/
/**
* 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 React.render(instance, div);
},
isElement: function(element) {
return ReactElement.isValidElement(element);
},
isElementOfType: function(inst, convenienceConstructor) {
return (
ReactElement.isValidElement(inst) &&
inst.type === convenienceConstructor.type
);
},
isDOMComponent: function(inst) {
return !!(inst && inst.mountComponent && inst.tagName);
},
isDOMComponentElement: function(inst) {
return !!(inst &&
ReactElement.isValidElement(inst) &&
!!inst.tagName);
},
isCompositeComponent: function(inst) {
return typeof inst.render === 'function' &&
typeof inst.setState === 'function';
},
isCompositeComponentWithType: function(inst, type) {
return !!(ReactTestUtils.isCompositeComponent(inst) &&
(inst.constructor === type.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) {
return !!(ReactTestUtils.isCompositeComponentElement(inst) &&
(inst.constructor === type));
},
isTextComponent: function(inst) {
return inst instanceof ReactTextComponent.type;
},
findAllInRenderedTree: function(inst, test) {
if (!inst) {
return [];
}
var ret = test(inst) ? [inst] : [];
if (ReactTestUtils.isDOMComponent(inst)) {
var renderedChildren = inst._renderedChildren;
var key;
for (key in renderedChildren) {
if (!renderedChildren.hasOwnProperty(key)) {
continue;
}
ret = ret.concat(
ReactTestUtils.findAllInRenderedTree(renderedChildren[key], test)
);
}
} else if (ReactTestUtils.isCompositeComponent(inst)) {
ret = ret.concat(
ReactTestUtils.findAllInRenderedTree(inst._renderedComponent, test)
);
}
return ret;
},
/**
* Finds all instance of components in the rendered tree that are DOM
* components with the class name matching `className`.
* @return an array of all the matches.
*/
scryRenderedDOMComponentsWithClass: function(root, className) {
return ReactTestUtils.findAllInRenderedTree(root, function(inst) {
var instClassName = inst.props.className;
return ReactTestUtils.isDOMComponent(inst) && (
instClassName &&
(' ' + instClassName + ' ').indexOf(' ' + className + ' ') !== -1
);
});
},
/**
* 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 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 an array of all the matches.
*/
scryRenderedDOMComponentsWithTag: function(root, tagName) {
return ReactTestUtils.findAllInRenderedTree(root, function(inst) {
return ReactTestUtils.isDOMComponent(inst) &&
inst.tagName === 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 for tag:' + tagName);
}
return all[0];
},
/**
* Finds all instances of components with type equal to `componentType`.
* @return 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 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";
var ConvenienceConstructor = React.createClass({displayName: 'ConvenienceConstructor',
render: function() {
return React.createElement(
mockTagName,
null,
this.props.children
);
}
});
module.mockImplementation(ConvenienceConstructor);
module.type = ConvenienceConstructor.type;
module.isReactLegacyFactory = true;
return this;
},
/**
* Simulates a top level event being dispatched from a raw event that occured
* on an `Element` node.
* @param topLevelType {Object} 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 occured
* on the `ReactDOMComponent` `comp`.
* @param topLevelType {Object} A type from `EventConstants.topLevelTypes`.
* @param comp {!ReactDOMComponent}
* @param {?Event} fakeNativeEvent Fake native event to use in SyntheticEvent.
*/
simulateNativeEventOnDOMComponent: function(
topLevelType,
comp,
fakeNativeEvent) {
ReactTestUtils.simulateNativeEventOnNode(
topLevelType,
comp.getDOMNode(),
fakeNativeEvent
);
},
nativeTouchData: function(x, y) {
return {
touches: [
{pageX: x, pageY: y}
]
};
},
Simulate: null,
SimulateNative: {}
};
/**
* 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;
if (ReactTestUtils.isDOMComponent(domComponentOrNode)) {
node = domComponentOrNode.getDOMNode();
} else if (domComponentOrNode.tagName) {
node = domComponentOrNode;
}
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(
ReactBrowserEventEmitter.eventNameDispatchConfigs[eventType],
ReactMount.getID(node),
fakeNativeEvent
);
assign(event, eventData);
EventPropagators.accumulateTwoPhaseDispatches(event);
ReactUpdates.batchedUpdates(function() {
EventPluginHub.enqueueEvents(event);
EventPluginHub.processEventQueue();
});
};
}
function buildSimulators() {
ReactTestUtils.Simulate = {};
var eventType;
for (eventType in ReactBrowserEventEmitter.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
);
}
};
}
var eventType;
for (eventType in topLevelTypes) {
// 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;
},{"./EventConstants":17,"./EventPluginHub":19,"./EventPropagators":22,"./Object.assign":29,"./React":31,"./ReactBrowserEventEmitter":33,"./ReactElement":58,"./ReactMount":70,"./ReactTextComponent":87,"./ReactUpdates":91,"./SyntheticEvent":99}],87:[function(_dereq_,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 ReactTextComponent
* @typechecks static-only
*/
"use strict";
var DOMPropertyOperations = _dereq_("./DOMPropertyOperations");
var ReactComponent = _dereq_("./ReactComponent");
var ReactElement = _dereq_("./ReactElement");
var assign = _dereq_("./Object.assign");
var escapeTextForBrowser = _dereq_("./escapeTextForBrowser");
/**
* 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(props) {
// This constructor and it's argument is currently used by mocks.
};
assign(ReactTextComponent.prototype, ReactComponent.Mixin, {
/**
* 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.
* @param {ReactReconcileTransaction|ReactServerRenderingTransaction} transaction
* @param {number} mountDepth number of components in the owner hierarchy
* @return {string} Markup for this text node.
* @internal
*/
mountComponent: function(rootID, transaction, mountDepth) {
ReactComponent.Mixin.mountComponent.call(
this,
rootID,
transaction,
mountDepth
);
var escapedText = escapeTextForBrowser(this.props);
if (transaction.renderToStaticMarkup) {
// Normally we'd wrap this in a `span` 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 (
'<span ' + DOMPropertyOperations.createMarkupForID(rootID) + '>' +
escapedText +
'</span>'
);
},
/**
* Updates this component by updating the text content.
*
* @param {object} nextComponent Contains the next text content.
* @param {ReactReconcileTransaction} transaction
* @internal
*/
receiveComponent: function(nextComponent, transaction) {
var nextProps = nextComponent.props;
if (nextProps !== this.props) {
this.props = nextProps;
ReactComponent.BackendIDOperations.updateTextContentByID(
this._rootNodeID,
nextProps
);
}
}
});
var ReactTextComponentFactory = function(text) {
// Bypass validation and configuration
return new ReactElement(ReactTextComponent, null, null, null, null, text);
};
ReactTextComponentFactory.type = ReactTextComponent;
module.exports = ReactTextComponentFactory;
},{"./DOMPropertyOperations":13,"./Object.assign":29,"./ReactComponent":37,"./ReactElement":58,"./escapeTextForBrowser":123}],88:[function(_dereq_,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.
*
* @typechecks static-only
* @providesModule ReactTransitionChildMapping
*/
"use strict";
var ReactChildren = _dereq_("./ReactChildren");
var ReactTransitionChildMapping = {
/**
* Given `this.props.children`, return an object mapping key to child. Just
* simple syntactic sugar around ReactChildren.map().
*
* @param {*} children `this.props.children`
* @return {object} Mapping of key to child
*/
getChildMapping: function(children) {
return ReactChildren.map(children, function(child) {
return child;
});
},
/**
* 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;
},{"./ReactChildren":36}],89:[function(_dereq_,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 ReactTransitionEvents
*/
"use strict";
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
/**
* EVENT_NAME_MAP is used to determine which event fired when a
* transition/animation ends, based on the style property used to
* define that event.
*/
var EVENT_NAME_MAP = {
transitionend: {
'transition': 'transitionend',
'WebkitTransition': 'webkitTransitionEnd',
'MozTransition': 'mozTransitionEnd',
'OTransition': 'oTransitionEnd',
'msTransition': 'MSTransitionEnd'
},
animationend: {
'animation': 'animationend',
'WebkitAnimation': 'webkitAnimationEnd',
'MozAnimation': 'mozAnimationEnd',
'OAnimation': 'oAnimationEnd',
'msAnimation': 'MSAnimationEnd'
}
};
var endEvents = [];
function detectEvents() {
var testEl = document.createElement('div');
var style = testEl.style;
// On some platforms, in particular some releases of Android 4.x,
// the un-prefixed "animation" and "transition" properties are defined on the
// style object but the events that fire will still be prefixed, so we need
// to check if the un-prefixed events are useable, and if not remove them
// from the map
if (!('AnimationEvent' in window)) {
delete EVENT_NAME_MAP.animationend.animation;
}
if (!('TransitionEvent' in window)) {
delete EVENT_NAME_MAP.transitionend.transition;
}
for (var baseEventName in EVENT_NAME_MAP) {
var baseEvents = EVENT_NAME_MAP[baseEventName];
for (var styleName in baseEvents) {
if (styleName in style) {
endEvents.push(baseEvents[styleName]);
break;
}
}
}
}
if (ExecutionEnvironment.canUseDOM) {
detectEvents();
}
// We use the raw {add|remove}EventListener() call because EventListener
// does not know how to remove event listeners and we really should
// clean up. Also, these events are not triggered in older browsers
// so we should be A-OK here.
function addEventListener(node, eventName, eventListener) {
node.addEventListener(eventName, eventListener, false);
}
function removeEventListener(node, eventName, eventListener) {
node.removeEventListener(eventName, eventListener, false);
}
var ReactTransitionEvents = {
addEndEventListener: function(node, eventListener) {
if (endEvents.length === 0) {
// If CSS transitions are not supported, trigger an "end animation"
// event immediately.
window.setTimeout(eventListener, 0);
return;
}
endEvents.forEach(function(endEvent) {
addEventListener(node, endEvent, eventListener);
});
},
removeEndEventListener: function(node, eventListener) {
if (endEvents.length === 0) {
return;
}
endEvents.forEach(function(endEvent) {
removeEventListener(node, endEvent, eventListener);
});
}
};
module.exports = ReactTransitionEvents;
},{"./ExecutionEnvironment":23}],90:[function(_dereq_,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 ReactTransitionGroup
*/
"use strict";
var React = _dereq_("./React");
var ReactTransitionChildMapping = _dereq_("./ReactTransitionChildMapping");
var assign = _dereq_("./Object.assign");
var cloneWithProps = _dereq_("./cloneWithProps");
var emptyFunction = _dereq_("./emptyFunction");
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)
};
},
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.
},
componentWillMount: function() {
this.currentlyTransitioningKeys = {};
this.keysToEnter = [];
this.keysToLeave = [];
},
componentDidUpdate: function() {
var keysToEnter = this.keysToEnter;
this.keysToEnter = [];
keysToEnter.forEach(this.performEnter);
var keysToLeave = this.keysToLeave;
this.keysToLeave = [];
keysToLeave.forEach(this.performLeave);
},
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 {
var newChildren = assign({}, this.state.children);
delete newChildren[key];
this.setState({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[key] = cloneWithProps(
this.props.childFactory(child),
{ref: key}
);
}
}
return React.createElement(
this.props.component,
this.props,
childrenToRender
);
}
});
module.exports = ReactTransitionGroup;
},{"./Object.assign":29,"./React":31,"./ReactTransitionChildMapping":88,"./cloneWithProps":113,"./emptyFunction":121}],91:[function(_dereq_,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 ReactUpdates
*/
"use strict";
var CallbackQueue = _dereq_("./CallbackQueue");
var PooledClass = _dereq_("./PooledClass");
var ReactCurrentOwner = _dereq_("./ReactCurrentOwner");
var ReactPerf = _dereq_("./ReactPerf");
var Transaction = _dereq_("./Transaction");
var assign = _dereq_("./Object.assign");
var invariant = _dereq_("./invariant");
var warning = _dereq_("./warning");
var dirtyComponents = [];
var asapCallbackQueue = CallbackQueue.getPooled();
var asapEnqueued = false;
var batchingStrategy = null;
function ensureInjected() {
("production" !== "development" ? invariant(
ReactUpdates.ReactReconcileTransaction && batchingStrategy,
'ReactUpdates: must inject a reconcile transaction class and batching ' +
'strategy'
) : invariant(ReactUpdates.ReactReconcileTransaction && batchingStrategy));
}
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();
}
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) {
ensureInjected();
batchingStrategy.batchedUpdates(callback, a, b);
}
/**
* Array comparator for ReactComponents by owner depth
*
* @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 mountDepthComparator(c1, c2) {
return c1._mountDepth - c2._mountDepth;
}
function runBatchedUpdates(transaction) {
var len = transaction.dirtyComponentsLength;
("production" !== "development" ? invariant(
len === dirtyComponents.length,
'Expected flush transaction\'s stored dirty-components length (%s) to ' +
'match dirty-components array length (%s).',
len,
dirtyComponents.length
) : invariant(len === dirtyComponents.length));
// 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(mountDepthComparator);
for (var i = 0; i < len; i++) {
// If a component is unmounted before pending changes apply, ignore them
// TODO: Queue unmounts in the same list to avoid this happening at all
var component = dirtyComponents[i];
if (component.isMounted()) {
// 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;
component.performUpdateIfNecessary(transaction.reconcileTransaction);
if (callbacks) {
for (var j = 0; j < callbacks.length; j++) {
transaction.callbackQueue.enqueue(
callbacks[j],
component
);
}
}
}
}
}
var flushBatchedUpdates = ReactPerf.measure(
'ReactUpdates',
'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);
}
}
}
);
/**
* 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, callback) {
("production" !== "development" ? invariant(
!callback || typeof callback === "function",
'enqueueUpdate(...): You called `setProps`, `replaceProps`, ' +
'`setState`, `replaceState`, or `forceUpdate` with a callback that ' +
'isn\'t callable.'
) : invariant(!callback || typeof callback === "function"));
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.)
("production" !== "development" ? warning(
ReactCurrentOwner.current == null,
'enqueueUpdate(): Render methods should be a pure function of props ' +
'and state; triggering nested component updates from render is not ' +
'allowed. If necessary, trigger nested updates in ' +
'componentDidUpdate.'
) : null);
if (!batchingStrategy.isBatchingUpdates) {
batchingStrategy.batchedUpdates(enqueueUpdate, component, callback);
return;
}
dirtyComponents.push(component);
if (callback) {
if (component._pendingCallbacks) {
component._pendingCallbacks.push(callback);
} else {
component._pendingCallbacks = [callback];
}
}
}
/**
* 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) {
("production" !== "development" ? invariant(
batchingStrategy.isBatchingUpdates,
'ReactUpdates.asap: Can\'t enqueue an asap callback in a context where' +
'updates are not being batched.'
) : invariant(batchingStrategy.isBatchingUpdates));
asapCallbackQueue.enqueue(callback, context);
asapEnqueued = true;
}
var ReactUpdatesInjection = {
injectReconcileTransaction: function(ReconcileTransaction) {
("production" !== "development" ? invariant(
ReconcileTransaction,
'ReactUpdates: must provide a reconcile transaction class'
) : invariant(ReconcileTransaction));
ReactUpdates.ReactReconcileTransaction = ReconcileTransaction;
},
injectBatchingStrategy: function(_batchingStrategy) {
("production" !== "development" ? invariant(
_batchingStrategy,
'ReactUpdates: must provide a batching strategy'
) : invariant(_batchingStrategy));
("production" !== "development" ? invariant(
typeof _batchingStrategy.batchedUpdates === 'function',
'ReactUpdates: must provide a batchedUpdates() function'
) : invariant(typeof _batchingStrategy.batchedUpdates === 'function'));
("production" !== "development" ? invariant(
typeof _batchingStrategy.isBatchingUpdates === 'boolean',
'ReactUpdates: must provide an isBatchingUpdates boolean attribute'
) : invariant(typeof _batchingStrategy.isBatchingUpdates === 'boolean'));
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;
},{"./CallbackQueue":7,"./Object.assign":29,"./PooledClass":30,"./ReactCurrentOwner":42,"./ReactPerf":75,"./Transaction":107,"./invariant":140,"./warning":160}],92:[function(_dereq_,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 SVGDOMPropertyConfig
*/
/*jslint bitwise: true*/
"use strict";
var DOMProperty = _dereq_("./DOMProperty");
var MUST_USE_ATTRIBUTE = DOMProperty.injection.MUST_USE_ATTRIBUTE;
var SVGDOMPropertyConfig = {
Properties: {
cx: MUST_USE_ATTRIBUTE,
cy: MUST_USE_ATTRIBUTE,
d: MUST_USE_ATTRIBUTE,
dx: MUST_USE_ATTRIBUTE,
dy: MUST_USE_ATTRIBUTE,
fill: MUST_USE_ATTRIBUTE,
fillOpacity: MUST_USE_ATTRIBUTE,
fontFamily: MUST_USE_ATTRIBUTE,
fontSize: MUST_USE_ATTRIBUTE,
fx: MUST_USE_ATTRIBUTE,
fy: MUST_USE_ATTRIBUTE,
gradientTransform: MUST_USE_ATTRIBUTE,
gradientUnits: MUST_USE_ATTRIBUTE,
markerEnd: MUST_USE_ATTRIBUTE,
markerMid: MUST_USE_ATTRIBUTE,
markerStart: MUST_USE_ATTRIBUTE,
offset: MUST_USE_ATTRIBUTE,
opacity: MUST_USE_ATTRIBUTE,
patternContentUnits: MUST_USE_ATTRIBUTE,
patternUnits: MUST_USE_ATTRIBUTE,
points: MUST_USE_ATTRIBUTE,
preserveAspectRatio: MUST_USE_ATTRIBUTE,
r: MUST_USE_ATTRIBUTE,
rx: MUST_USE_ATTRIBUTE,
ry: MUST_USE_ATTRIBUTE,
spreadMethod: MUST_USE_ATTRIBUTE,
stopColor: MUST_USE_ATTRIBUTE,
stopOpacity: MUST_USE_ATTRIBUTE,
stroke: MUST_USE_ATTRIBUTE,
strokeDasharray: MUST_USE_ATTRIBUTE,
strokeLinecap: MUST_USE_ATTRIBUTE,
strokeOpacity: MUST_USE_ATTRIBUTE,
strokeWidth: MUST_USE_ATTRIBUTE,
textAnchor: MUST_USE_ATTRIBUTE,
transform: MUST_USE_ATTRIBUTE,
version: MUST_USE_ATTRIBUTE,
viewBox: MUST_USE_ATTRIBUTE,
x1: MUST_USE_ATTRIBUTE,
x2: MUST_USE_ATTRIBUTE,
x: MUST_USE_ATTRIBUTE,
y1: MUST_USE_ATTRIBUTE,
y2: MUST_USE_ATTRIBUTE,
y: MUST_USE_ATTRIBUTE
},
DOMAttributeNames: {
fillOpacity: 'fill-opacity',
fontFamily: 'font-family',
fontSize: 'font-size',
gradientTransform: 'gradientTransform',
gradientUnits: 'gradientUnits',
markerEnd: 'marker-end',
markerMid: 'marker-mid',
markerStart: 'marker-start',
patternContentUnits: 'patternContentUnits',
patternUnits: 'patternUnits',
preserveAspectRatio: 'preserveAspectRatio',
spreadMethod: 'spreadMethod',
stopColor: 'stop-color',
stopOpacity: 'stop-opacity',
strokeDasharray: 'stroke-dasharray',
strokeLinecap: 'stroke-linecap',
strokeOpacity: 'stroke-opacity',
strokeWidth: 'stroke-width',
textAnchor: 'text-anchor',
viewBox: 'viewBox'
}
};
module.exports = SVGDOMPropertyConfig;
},{"./DOMProperty":12}],93:[function(_dereq_,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 SelectEventPlugin
*/
"use strict";
var EventConstants = _dereq_("./EventConstants");
var EventPropagators = _dereq_("./EventPropagators");
var ReactInputSelection = _dereq_("./ReactInputSelection");
var SyntheticEvent = _dereq_("./SyntheticEvent");
var getActiveElement = _dereq_("./getActiveElement");
var isTextInputElement = _dereq_("./isTextInputElement");
var keyOf = _dereq_("./keyOf");
var shallowEqual = _dereq_("./shallowEqual");
var topLevelTypes = EventConstants.topLevelTypes;
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 activeElementID = null;
var lastSelection = null;
var mouseDown = false;
/**
* 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
* @param {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) {
// 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;
}
// Only fire when selection has actually changed.
var currentSelection = getSelection(activeElement);
if (!lastSelection || !shallowEqual(lastSelection, currentSelection)) {
lastSelection = currentSelection;
var syntheticEvent = SyntheticEvent.getPooled(
eventTypes.select,
activeElementID,
nativeEvent
);
syntheticEvent.type = 'select';
syntheticEvent.target = activeElement;
EventPropagators.accumulateTwoPhaseDispatches(syntheticEvent);
return syntheticEvent;
}
}
/**
* 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,
/**
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @see {EventPluginHub.extractEvents}
*/
extractEvents: function(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent) {
switch (topLevelType) {
// Track the input node that has focus.
case topLevelTypes.topFocus:
if (isTextInputElement(topLevelTarget) ||
topLevelTarget.contentEditable === 'true') {
activeElement = topLevelTarget;
activeElementID = topLevelTargetID;
lastSelection = null;
}
break;
case topLevelTypes.topBlur:
activeElement = null;
activeElementID = 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);
// Chrome and IE fire non-standard event when selection is changed (and
// sometimes when it hasn't).
// 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.
case topLevelTypes.topSelectionChange:
case topLevelTypes.topKeyDown:
case topLevelTypes.topKeyUp:
return constructSelectEvent(nativeEvent);
}
}
};
module.exports = SelectEventPlugin;
},{"./EventConstants":17,"./EventPropagators":22,"./ReactInputSelection":65,"./SyntheticEvent":99,"./getActiveElement":127,"./isTextInputElement":143,"./keyOf":147,"./shallowEqual":155}],94:[function(_dereq_,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 ServerReactRootIndex
* @typechecks
*/
"use strict";
/**
* Size of the reactRoot ID space. We generate random numbers for React root
* IDs and if there's a collision the events and DOM update system will
* get confused. In the future we need a way to generate GUIDs but for
* now this will work on a smaller scale.
*/
var GLOBAL_MOUNT_POINT_MAX = Math.pow(2, 53);
var ServerReactRootIndex = {
createReactRootIndex: function() {
return Math.ceil(Math.random() * GLOBAL_MOUNT_POINT_MAX);
}
};
module.exports = ServerReactRootIndex;
},{}],95:[function(_dereq_,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 SimpleEventPlugin
*/
"use strict";
var EventConstants = _dereq_("./EventConstants");
var EventPluginUtils = _dereq_("./EventPluginUtils");
var EventPropagators = _dereq_("./EventPropagators");
var SyntheticClipboardEvent = _dereq_("./SyntheticClipboardEvent");
var SyntheticEvent = _dereq_("./SyntheticEvent");
var SyntheticFocusEvent = _dereq_("./SyntheticFocusEvent");
var SyntheticKeyboardEvent = _dereq_("./SyntheticKeyboardEvent");
var SyntheticMouseEvent = _dereq_("./SyntheticMouseEvent");
var SyntheticDragEvent = _dereq_("./SyntheticDragEvent");
var SyntheticTouchEvent = _dereq_("./SyntheticTouchEvent");
var SyntheticUIEvent = _dereq_("./SyntheticUIEvent");
var SyntheticWheelEvent = _dereq_("./SyntheticWheelEvent");
var getEventCharCode = _dereq_("./getEventCharCode");
var invariant = _dereq_("./invariant");
var keyOf = _dereq_("./keyOf");
var warning = _dereq_("./warning");
var topLevelTypes = EventConstants.topLevelTypes;
var eventTypes = {
blur: {
phasedRegistrationNames: {
bubbled: keyOf({onBlur: true}),
captured: keyOf({onBlurCapture: 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})
}
},
focus: {
phasedRegistrationNames: {
bubbled: keyOf({onFocus: true}),
captured: keyOf({onFocusCapture: true})
}
},
input: {
phasedRegistrationNames: {
bubbled: keyOf({onInput: true}),
captured: keyOf({onInputCapture: 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})
}
},
error: {
phasedRegistrationNames: {
bubbled: keyOf({onError: true}),
captured: keyOf({onErrorCapture: 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})
}
},
reset: {
phasedRegistrationNames: {
bubbled: keyOf({onReset: true}),
captured: keyOf({onResetCapture: true})
}
},
scroll: {
phasedRegistrationNames: {
bubbled: keyOf({onScroll: true}),
captured: keyOf({onScrollCapture: true})
}
},
submit: {
phasedRegistrationNames: {
bubbled: keyOf({onSubmit: true}),
captured: keyOf({onSubmitCapture: 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})
}
},
wheel: {
phasedRegistrationNames: {
bubbled: keyOf({onWheel: true}),
captured: keyOf({onWheelCapture: true})
}
}
};
var topLevelEventsToDispatchConfig = {
topBlur: eventTypes.blur,
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,
topError: eventTypes.error,
topFocus: eventTypes.focus,
topInput: eventTypes.input,
topKeyDown: eventTypes.keyDown,
topKeyPress: eventTypes.keyPress,
topKeyUp: eventTypes.keyUp,
topLoad: eventTypes.load,
topMouseDown: eventTypes.mouseDown,
topMouseMove: eventTypes.mouseMove,
topMouseOut: eventTypes.mouseOut,
topMouseOver: eventTypes.mouseOver,
topMouseUp: eventTypes.mouseUp,
topPaste: eventTypes.paste,
topReset: eventTypes.reset,
topScroll: eventTypes.scroll,
topSubmit: eventTypes.submit,
topTouchCancel: eventTypes.touchCancel,
topTouchEnd: eventTypes.touchEnd,
topTouchMove: eventTypes.touchMove,
topTouchStart: eventTypes.touchStart,
topWheel: eventTypes.wheel
};
for (var topLevelType in topLevelEventsToDispatchConfig) {
topLevelEventsToDispatchConfig[topLevelType].dependencies = [topLevelType];
}
var SimpleEventPlugin = {
eventTypes: eventTypes,
/**
* Same as the default implementation, except cancels the event when return
* value is false. This behavior will be disabled in a future release.
*
* @param {object} Event to be dispatched.
* @param {function} Application-level callback.
* @param {string} domID DOM ID to pass to the callback.
*/
executeDispatch: function(event, listener, domID) {
var returnValue = EventPluginUtils.executeDispatch(event, listener, domID);
("production" !== "development" ? warning(
typeof returnValue !== 'boolean',
'Returning `false` from an event handler is deprecated and will be ' +
'ignored in a future release. Instead, manually call ' +
'e.stopPropagation() or e.preventDefault(), as appropriate.'
) : null);
if (returnValue === false) {
event.stopPropagation();
event.preventDefault();
}
},
/**
* @param {string} topLevelType Record from `EventConstants`.
* @param {DOMEventTarget} topLevelTarget The listening component root node.
* @param {string} topLevelTargetID ID of `topLevelTarget`.
* @param {object} nativeEvent Native browser event.
* @return {*} An accumulation of synthetic events.
* @see {EventPluginHub.extractEvents}
*/
extractEvents: function(
topLevelType,
topLevelTarget,
topLevelTargetID,
nativeEvent) {
var dispatchConfig = topLevelEventsToDispatchConfig[topLevelType];
if (!dispatchConfig) {
return null;
}
var EventConstructor;
switch (topLevelType) {
case topLevelTypes.topInput:
case topLevelTypes.topLoad:
case topLevelTypes.topError:
case topLevelTypes.topReset:
case topLevelTypes.topSubmit:
// 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.topScroll:
EventConstructor = SyntheticUIEvent;
break;
case topLevelTypes.topWheel:
EventConstructor = SyntheticWheelEvent;
break;
case topLevelTypes.topCopy:
case topLevelTypes.topCut:
case topLevelTypes.topPaste:
EventConstructor = SyntheticClipboardEvent;
break;
}
("production" !== "development" ? invariant(
EventConstructor,
'SimpleEventPlugin: Unhandled event type, `%s`.',
topLevelType
) : invariant(EventConstructor));
var event = EventConstructor.getPooled(
dispatchConfig,
topLevelTargetID,
nativeEvent
);
EventPropagators.accumulateTwoPhaseDispatches(event);
return event;
}
};
module.exports = SimpleEventPlugin;
},{"./EventConstants":17,"./EventPluginUtils":21,"./EventPropagators":22,"./SyntheticClipboardEvent":96,"./SyntheticDragEvent":98,"./SyntheticEvent":99,"./SyntheticFocusEvent":100,"./SyntheticKeyboardEvent":102,"./SyntheticMouseEvent":103,"./SyntheticTouchEvent":104,"./SyntheticUIEvent":105,"./SyntheticWheelEvent":106,"./getEventCharCode":128,"./invariant":140,"./keyOf":147,"./warning":160}],96:[function(_dereq_,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 SyntheticClipboardEvent
* @typechecks static-only
*/
"use strict";
var SyntheticEvent = _dereq_("./SyntheticEvent");
/**
* @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) {
SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticEvent.augmentClass(SyntheticClipboardEvent, ClipboardEventInterface);
module.exports = SyntheticClipboardEvent;
},{"./SyntheticEvent":99}],97:[function(_dereq_,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 SyntheticCompositionEvent
* @typechecks static-only
*/
"use strict";
var SyntheticEvent = _dereq_("./SyntheticEvent");
/**
* @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) {
SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticEvent.augmentClass(
SyntheticCompositionEvent,
CompositionEventInterface
);
module.exports = SyntheticCompositionEvent;
},{"./SyntheticEvent":99}],98:[function(_dereq_,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 SyntheticDragEvent
* @typechecks static-only
*/
"use strict";
var SyntheticMouseEvent = _dereq_("./SyntheticMouseEvent");
/**
* @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) {
SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticMouseEvent.augmentClass(SyntheticDragEvent, DragEventInterface);
module.exports = SyntheticDragEvent;
},{"./SyntheticMouseEvent":103}],99:[function(_dereq_,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 SyntheticEvent
* @typechecks static-only
*/
"use strict";
var PooledClass = _dereq_("./PooledClass");
var assign = _dereq_("./Object.assign");
var emptyFunction = _dereq_("./emptyFunction");
var getEventTarget = _dereq_("./getEventTarget");
/**
* @interface Event
* @see http://www.w3.org/TR/DOM-Level-3-Events/
*/
var EventInterface = {
type: null,
target: getEventTarget,
// 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 {string} dispatchMarker Marker identifying the event target.
* @param {object} nativeEvent Native browser event.
*/
function SyntheticEvent(dispatchConfig, dispatchMarker, nativeEvent) {
this.dispatchConfig = dispatchConfig;
this.dispatchMarker = dispatchMarker;
this.nativeEvent = nativeEvent;
var Interface = this.constructor.Interface;
for (var propName in Interface) {
if (!Interface.hasOwnProperty(propName)) {
continue;
}
var normalize = Interface[propName];
if (normalize) {
this[propName] = normalize(nativeEvent);
} 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;
}
assign(SyntheticEvent.prototype, {
preventDefault: function() {
this.defaultPrevented = true;
var event = this.nativeEvent;
event.preventDefault ? event.preventDefault() : event.returnValue = false;
this.isDefaultPrevented = emptyFunction.thatReturnsTrue;
},
stopPropagation: function() {
var event = this.nativeEvent;
event.stopPropagation ? event.stopPropagation() : 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) {
this[propName] = null;
}
this.dispatchConfig = null;
this.dispatchMarker = null;
this.nativeEvent = null;
}
});
SyntheticEvent.Interface = EventInterface;
/**
* Helper to reduce boilerplate when creating subclasses.
*
* @param {function} Class
* @param {?object} Interface
*/
SyntheticEvent.augmentClass = function(Class, Interface) {
var Super = this;
var prototype = Object.create(Super.prototype);
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.threeArgumentPooler);
};
PooledClass.addPoolingTo(SyntheticEvent, PooledClass.threeArgumentPooler);
module.exports = SyntheticEvent;
},{"./Object.assign":29,"./PooledClass":30,"./emptyFunction":121,"./getEventTarget":131}],100:[function(_dereq_,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 SyntheticFocusEvent
* @typechecks static-only
*/
"use strict";
var SyntheticUIEvent = _dereq_("./SyntheticUIEvent");
/**
* @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) {
SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticUIEvent.augmentClass(SyntheticFocusEvent, FocusEventInterface);
module.exports = SyntheticFocusEvent;
},{"./SyntheticUIEvent":105}],101:[function(_dereq_,module,exports){
/**
* Copyright 2013 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
* @typechecks static-only
*/
"use strict";
var SyntheticEvent = _dereq_("./SyntheticEvent");
/**
* @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) {
SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticEvent.augmentClass(
SyntheticInputEvent,
InputEventInterface
);
module.exports = SyntheticInputEvent;
},{"./SyntheticEvent":99}],102:[function(_dereq_,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 SyntheticKeyboardEvent
* @typechecks static-only
*/
"use strict";
var SyntheticUIEvent = _dereq_("./SyntheticUIEvent");
var getEventCharCode = _dereq_("./getEventCharCode");
var getEventKey = _dereq_("./getEventKey");
var getEventModifierState = _dereq_("./getEventModifierState");
/**
* @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) {
SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticUIEvent.augmentClass(SyntheticKeyboardEvent, KeyboardEventInterface);
module.exports = SyntheticKeyboardEvent;
},{"./SyntheticUIEvent":105,"./getEventCharCode":128,"./getEventKey":129,"./getEventModifierState":130}],103:[function(_dereq_,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 SyntheticMouseEvent
* @typechecks static-only
*/
"use strict";
var SyntheticUIEvent = _dereq_("./SyntheticUIEvent");
var ViewportMetrics = _dereq_("./ViewportMetrics");
var getEventModifierState = _dereq_("./getEventModifierState");
/**
* @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) {
SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticUIEvent.augmentClass(SyntheticMouseEvent, MouseEventInterface);
module.exports = SyntheticMouseEvent;
},{"./SyntheticUIEvent":105,"./ViewportMetrics":108,"./getEventModifierState":130}],104:[function(_dereq_,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 SyntheticTouchEvent
* @typechecks static-only
*/
"use strict";
var SyntheticUIEvent = _dereq_("./SyntheticUIEvent");
var getEventModifierState = _dereq_("./getEventModifierState");
/**
* @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) {
SyntheticUIEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticUIEvent.augmentClass(SyntheticTouchEvent, TouchEventInterface);
module.exports = SyntheticTouchEvent;
},{"./SyntheticUIEvent":105,"./getEventModifierState":130}],105:[function(_dereq_,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 SyntheticUIEvent
* @typechecks static-only
*/
"use strict";
var SyntheticEvent = _dereq_("./SyntheticEvent");
var getEventTarget = _dereq_("./getEventTarget");
/**
* @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) {
SyntheticEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticEvent.augmentClass(SyntheticUIEvent, UIEventInterface);
module.exports = SyntheticUIEvent;
},{"./SyntheticEvent":99,"./getEventTarget":131}],106:[function(_dereq_,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 SyntheticWheelEvent
* @typechecks static-only
*/
"use strict";
var SyntheticMouseEvent = _dereq_("./SyntheticMouseEvent");
/**
* @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) {
SyntheticMouseEvent.call(this, dispatchConfig, dispatchMarker, nativeEvent);
}
SyntheticMouseEvent.augmentClass(SyntheticWheelEvent, WheelEventInterface);
module.exports = SyntheticWheelEvent;
},{"./SyntheticMouseEvent":103}],107:[function(_dereq_,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 Transaction
*/
"use strict";
var invariant = _dereq_("./invariant");
/**
* `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 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;
}
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.
* @return Return value from `method`.
*/
perform: function(method, scope, a, b, c, d, e, f) {
("production" !== "development" ? invariant(
!this.isInTransaction(),
'Transaction.perform(...): Cannot initialize a transaction when there ' +
'is already an outstanding transaction.'
) : invariant(!this.isInTransaction()));
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) {
("production" !== "development" ? invariant(
this.isInTransaction(),
'Transaction.closeAll(): Cannot close transaction when none are open.'
) : invariant(this.isInTransaction()));
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 occured.
*/
OBSERVED_ERROR: {}
};
module.exports = Transaction;
},{"./invariant":140}],108:[function(_dereq_,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 ViewportMetrics
*/
"use strict";
var getUnboundedScrollPosition = _dereq_("./getUnboundedScrollPosition");
var ViewportMetrics = {
currentScrollLeft: 0,
currentScrollTop: 0,
refreshScrollValues: function() {
var scrollPosition = getUnboundedScrollPosition(window);
ViewportMetrics.currentScrollLeft = scrollPosition.x;
ViewportMetrics.currentScrollTop = scrollPosition.y;
}
};
module.exports = ViewportMetrics;
},{"./getUnboundedScrollPosition":136}],109:[function(_dereq_,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 accumulateInto
*/
"use strict";
var invariant = _dereq_("./invariant");
/**
*
* 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) {
("production" !== "development" ? invariant(
next != null,
'accumulateInto(...): Accumulated items must not be null or undefined.'
) : invariant(next != null));
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;
},{"./invariant":140}],110:[function(_dereq_,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 adler32
*/
/* jslint bitwise:true */
"use strict";
var MOD = 65521;
// This is a clean-room implementation of adler32 designed for detecting
// if markup is not what we expect it to be. It does not need to be
// cryptographically strong, only reasonably good at detecting if markup
// generated on the server is different than that on the client.
function adler32(data) {
var a = 1;
var b = 0;
for (var i = 0; i < data.length; i++) {
a = (a + data.charCodeAt(i)) % MOD;
b = (b + a) % MOD;
}
return a | (b << 16);
}
module.exports = adler32;
},{}],111:[function(_dereq_,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 camelize
* @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;
},{}],112:[function(_dereq_,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 camelizeStyleName
* @typechecks
*/
"use strict";
var camelize = _dereq_("./camelize");
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;
},{"./camelize":111}],113:[function(_dereq_,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.
*
* @typechecks
* @providesModule cloneWithProps
*/
"use strict";
var ReactElement = _dereq_("./ReactElement");
var ReactPropTransferer = _dereq_("./ReactPropTransferer");
var keyOf = _dereq_("./keyOf");
var warning = _dereq_("./warning");
var CHILDREN_PROP = keyOf({children: null});
/**
* Sometimes you want to change the props of a child passed to you. Usually
* this is to add a CSS class.
*
* @param {object} child child component you'd like to clone
* @param {object} props props you'd like to modify. They will be merged
* as if you used `transferPropsTo()`.
* @return {object} a clone of child with props merged in.
*/
function cloneWithProps(child, props) {
if ("production" !== "development") {
("production" !== "development" ? warning(
!child.ref,
'You are calling cloneWithProps() on a child with a ref. This is ' +
'dangerous because you\'re creating a new child which will not be ' +
'added as a ref to its parent.'
) : null);
}
var newProps = ReactPropTransferer.mergeProps(props, child.props);
// Use `child.props.children` if it is provided.
if (!newProps.hasOwnProperty(CHILDREN_PROP) &&
child.props.hasOwnProperty(CHILDREN_PROP)) {
newProps.children = child.props.children;
}
// The current API doesn't retain _owner and _context, which is why this
// doesn't use ReactElement.cloneAndReplaceProps.
return ReactElement.createElement(child.type, newProps);
}
module.exports = cloneWithProps;
},{"./ReactElement":58,"./ReactPropTransferer":76,"./keyOf":147,"./warning":160}],114:[function(_dereq_,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 containsNode
* @typechecks
*/
var isTextNode = _dereq_("./isTextNode");
/*jslint bitwise:true */
/**
* 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;
},{"./isTextNode":144}],115:[function(_dereq_,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 createArrayFrom
* @typechecks
*/
var toArray = _dereq_("./toArray");
/**
* 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
(// HTMLCollection/NodeList
(Array.isArray(obj) ||
// arguments
('callee' in obj) || '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 createArrayFrom = require('createArrayFrom');
*
* function takesOneOrMoreThings(things) {
* things = createArrayFrom(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 createArrayFrom(obj) {
if (!hasArrayNature(obj)) {
return [obj];
} else if (Array.isArray(obj)) {
return obj.slice();
} else {
return toArray(obj);
}
}
module.exports = createArrayFrom;
},{"./toArray":157}],116:[function(_dereq_,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 createFullPageComponent
* @typechecks
*/
"use strict";
// Defeat circular references by requiring this directly.
var ReactCompositeComponent = _dereq_("./ReactCompositeComponent");
var ReactElement = _dereq_("./ReactElement");
var invariant = _dereq_("./invariant");
/**
* Create a component that will throw an exception when unmounted.
*
* 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.
*
* @param {string} tag The tag to wrap
* @return {function} convenience constructor of new component
*/
function createFullPageComponent(tag) {
var elementFactory = ReactElement.createFactory(tag);
var FullPageComponent = ReactCompositeComponent.createClass({
displayName: 'ReactFullPageComponent' + tag,
componentWillUnmount: function() {
("production" !== "development" ? 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.constructor.displayName
) : invariant(false));
},
render: function() {
return elementFactory(this.props);
}
});
return FullPageComponent;
}
module.exports = createFullPageComponent;
},{"./ReactCompositeComponent":40,"./ReactElement":58,"./invariant":140}],117:[function(_dereq_,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 createNodesFromMarkup
* @typechecks
*/
/*jslint evil: true, sub: true */
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
var createArrayFrom = _dereq_("./createArrayFrom");
var getMarkupWrap = _dereq_("./getMarkupWrap");
var invariant = _dereq_("./invariant");
/**
* 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;
("production" !== "development" ? invariant(!!dummyNode, 'createNodesFromMarkup dummy not initialized') : invariant(!!dummyNode));
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) {
("production" !== "development" ? invariant(
handleScript,
'createNodesFromMarkup(...): Unexpected <script> element rendered.'
) : invariant(handleScript));
createArrayFrom(scripts).forEach(handleScript);
}
var nodes = createArrayFrom(node.childNodes);
while (node.lastChild) {
node.removeChild(node.lastChild);
}
return nodes;
}
module.exports = createNodesFromMarkup;
},{"./ExecutionEnvironment":23,"./createArrayFrom":115,"./getMarkupWrap":132,"./invariant":140}],118:[function(_dereq_,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 cx
*/
/**
* This function is used to mark string literals representing CSS class names
* so that they can be transformed statically. This allows for modularization
* and minification of CSS class names.
*
* In static_upstream, this function is actually implemented, but it should
* eventually be replaced with something more descriptive, and the transform
* that is used in the main stack should be ported for use elsewhere.
*
* @param string|object className to modularize, or an object of key/values.
* In the object case, the values are conditions that
* determine if the className keys should be included.
* @param [string ...] Variable list of classNames in the string case.
* @return string Renderable space-separated CSS className.
*/
function cx(classNames) {
if (typeof classNames == 'object') {
return Object.keys(classNames).filter(function(className) {
return classNames[className];
}).join(' ');
} else {
return Array.prototype.join.call(arguments, ' ');
}
}
module.exports = cx;
},{}],119:[function(_dereq_,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 dangerousStyleValue
* @typechecks static-only
*/
"use strict";
var CSSProperty = _dereq_("./CSSProperty");
var isUnitlessNumber = CSSProperty.isUnitlessNumber;
/**
* 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`.
* @return {string} Normalized style value with dimensions applied.
*/
function dangerousStyleValue(name, 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
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') {
value = value.trim();
}
return value + 'px';
}
module.exports = dangerousStyleValue;
},{"./CSSProperty":5}],120:[function(_dereq_,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 deprecated
*/
var assign = _dereq_("./Object.assign");
var warning = _dereq_("./warning");
/**
* This will log a single deprecation notice per function and forward the call
* on to the new API.
*
* @param {string} namespace The namespace of the call, eg 'React'
* @param {string} oldName The old function name, eg 'renderComponent'
* @param {string} newName The new function name, eg 'render'
* @param {*} ctx The context this forwarded call should run in
* @param {function} fn The function to forward on to
* @return {*} Will be the value as returned from `fn`
*/
function deprecated(namespace, oldName, newName, ctx, fn) {
var warned = false;
if ("production" !== "development") {
var newFn = function() {
("production" !== "development" ? warning(
warned,
(namespace + "." + oldName + " will be deprecated in a future version. ") +
("Use " + namespace + "." + newName + " instead.")
) : null);
warned = true;
return fn.apply(ctx, arguments);
};
newFn.displayName = (namespace + "_" + oldName);
// We need to make sure all properties of the original fn are copied over.
// In particular, this is needed to support PropTypes
return assign(newFn, fn);
}
return fn;
}
module.exports = deprecated;
},{"./Object.assign":29,"./warning":160}],121:[function(_dereq_,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 emptyFunction
*/
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;
},{}],122:[function(_dereq_,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 emptyObject
*/
"use strict";
var emptyObject = {};
if ("production" !== "development") {
Object.freeze(emptyObject);
}
module.exports = emptyObject;
},{}],123:[function(_dereq_,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 escapeTextForBrowser
* @typechecks static-only
*/
"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 escapeTextForBrowser(text) {
return ('' + text).replace(ESCAPE_REGEX, escaper);
}
module.exports = escapeTextForBrowser;
},{}],124:[function(_dereq_,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 flattenChildren
*/
"use strict";
var ReactTextComponent = _dereq_("./ReactTextComponent");
var traverseAllChildren = _dereq_("./traverseAllChildren");
var warning = _dereq_("./warning");
/**
* @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.hasOwnProperty(name);
("production" !== "development" ? 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
) : null);
if (keyUnique && child != null) {
var type = typeof child;
var normalizedValue;
if (type === 'string') {
normalizedValue = ReactTextComponent(child);
} else if (type === 'number') {
normalizedValue = ReactTextComponent('' + child);
} else {
normalizedValue = child;
}
result[name] = normalizedValue;
}
}
/**
* 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;
},{"./ReactTextComponent":87,"./traverseAllChildren":158,"./warning":160}],125:[function(_dereq_,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 focusNode
*/
"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;
},{}],126:[function(_dereq_,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 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;
},{}],127:[function(_dereq_,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 getActiveElement
* @typechecks
*/
/**
* 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 body is not yet defined.
*/
function getActiveElement() /*?DOMElement*/ {
try {
return document.activeElement || document.body;
} catch (e) {
return document.body;
}
}
module.exports = getActiveElement;
},{}],128:[function(_dereq_,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 getEventCharCode
* @typechecks static-only
*/
"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 {string} 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;
},{}],129:[function(_dereq_,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 getEventKey
* @typechecks static-only
*/
"use strict";
var getEventCharCode = _dereq_("./getEventCharCode");
/**
* 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;
},{"./getEventCharCode":128}],130:[function(_dereq_,module,exports){
/**
* Copyright 2013 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
* @typechecks static-only
*/
"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) {
/*jshint validthis:true */
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;
},{}],131:[function(_dereq_,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 getEventTarget
* @typechecks static-only
*/
"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;
// 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;
},{}],132:[function(_dereq_,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 getMarkupWrap
*/
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
var invariant = _dereq_("./invariant");
/**
* 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 = {
// Force wrapping for SVG elements because if they get created inside a <div>,
// they will be initialized in the wrong namespace (and will not display).
'circle': true,
'defs': true,
'ellipse': true,
'g': true,
'line': true,
'linearGradient': true,
'path': true,
'polygon': true,
'polyline': true,
'radialGradient': true,
'rect': true,
'stop': true,
'text': true
};
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>', '</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,
'circle': svgWrap,
'defs': svgWrap,
'ellipse': svgWrap,
'g': svgWrap,
'line': svgWrap,
'linearGradient': svgWrap,
'path': svgWrap,
'polygon': svgWrap,
'polyline': svgWrap,
'radialGradient': svgWrap,
'rect': svgWrap,
'stop': svgWrap,
'text': svgWrap
};
/**
* 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) {
("production" !== "development" ? invariant(!!dummyNode, 'Markup wrapping node not initialized') : invariant(!!dummyNode));
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;
},{"./ExecutionEnvironment":23,"./invariant":140}],133:[function(_dereq_,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 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;
},{}],134:[function(_dereq_,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 getReactRootElementInContainer
*/
"use strict";
var DOC_NODE_TYPE = 9;
/**
* @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;
}
}
module.exports = getReactRootElementInContainer;
},{}],135:[function(_dereq_,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 getTextContentAccessor
*/
"use strict";
var ExecutionEnvironment = _dereq_("./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) {
// 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;
},{"./ExecutionEnvironment":23}],136:[function(_dereq_,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 getUnboundedScrollPosition
* @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;
},{}],137:[function(_dereq_,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 hyphenate
* @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;
},{}],138:[function(_dereq_,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 hyphenateStyleName
* @typechecks
*/
"use strict";
var hyphenate = _dereq_("./hyphenate");
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;
},{"./hyphenate":137}],139:[function(_dereq_,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 instantiateReactComponent
* @typechecks static-only
*/
"use strict";
var warning = _dereq_("./warning");
var ReactElement = _dereq_("./ReactElement");
var ReactLegacyElement = _dereq_("./ReactLegacyElement");
var ReactNativeComponent = _dereq_("./ReactNativeComponent");
var ReactEmptyComponent = _dereq_("./ReactEmptyComponent");
/**
* Given an `element` create an instance that will actually be mounted.
*
* @param {object} element
* @param {*} parentCompositeType The composite type that resolved this.
* @return {object} A new instance of the element's constructor.
* @protected
*/
function instantiateReactComponent(element, parentCompositeType) {
var instance;
if ("production" !== "development") {
("production" !== "development" ? warning(
element && (typeof element.type === 'function' ||
typeof element.type === 'string'),
'Only functions or strings can be mounted as React components.'
) : null);
// Resolve mock instances
if (element.type._mockedReactClassConstructor) {
// If this is a mocked class, we treat the legacy factory as if it was the
// class constructor for future proofing unit tests. Because this might
// be mocked as a legacy factory, we ignore any warnings triggerd by
// this temporary hack.
ReactLegacyElement._isLegacyCallWarningEnabled = false;
try {
instance = new element.type._mockedReactClassConstructor(
element.props
);
} finally {
ReactLegacyElement._isLegacyCallWarningEnabled = true;
}
// If the mock implementation was a legacy factory, then it returns a
// element. We need to turn this into a real component instance.
if (ReactElement.isValidElement(instance)) {
instance = new instance.type(instance.props);
}
var render = instance.render;
if (!render) {
// For auto-mocked factories, the prototype isn't shimmed and therefore
// there is no render function on the instance. We replace the whole
// component with an empty component instance instead.
element = ReactEmptyComponent.getEmptyComponent();
} else {
if (render._isMockFunction && !render._getMockImplementation()) {
// Auto-mocked components may have a prototype with a mocked render
// function. For those, we'll need to mock the result of the render
// since we consider undefined to be invalid results from render.
render.mockImplementation(
ReactEmptyComponent.getEmptyComponent
);
}
instance.construct(element);
return instance;
}
}
}
// Special case string values
if (typeof element.type === 'string') {
instance = ReactNativeComponent.createInstanceForTag(
element.type,
element.props,
parentCompositeType
);
} else {
// Normal case for non-mocks and non-strings
instance = new element.type(element.props);
}
if ("production" !== "development") {
("production" !== "development" ? warning(
typeof instance.construct === 'function' &&
typeof instance.mountComponent === 'function' &&
typeof instance.receiveComponent === 'function',
'Only React Components can be mounted.'
) : null);
}
// This actually sets up the internal instance. This will become decoupled
// from the public instance in a future diff.
instance.construct(element);
return instance;
}
module.exports = instantiateReactComponent;
},{"./ReactElement":58,"./ReactEmptyComponent":60,"./ReactLegacyElement":67,"./ReactNativeComponent":73,"./warning":160}],140:[function(_dereq_,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 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" !== "development") {
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;
},{}],141:[function(_dereq_,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 isEventSupported
*/
"use strict";
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
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;
},{"./ExecutionEnvironment":23}],142:[function(_dereq_,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 isNode
* @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;
},{}],143:[function(_dereq_,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 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) {
return elem && (
(elem.nodeName === 'INPUT' && supportedInputTypes[elem.type]) ||
elem.nodeName === 'TEXTAREA'
);
}
module.exports = isTextInputElement;
},{}],144:[function(_dereq_,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 isTextNode
* @typechecks
*/
var isNode = _dereq_("./isNode");
/**
* @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;
},{"./isNode":142}],145:[function(_dereq_,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 joinClasses
* @typechecks static-only
*/
"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];
if (nextClass) {
className = (className ? className + ' ' : '') + nextClass;
}
}
}
return className;
}
module.exports = joinClasses;
},{}],146:[function(_dereq_,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 keyMirror
* @typechecks static-only
*/
"use strict";
var invariant = _dereq_("./invariant");
/**
* 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;
("production" !== "development" ? invariant(
obj instanceof Object && !Array.isArray(obj),
'keyMirror(...): Argument must be an object.'
) : invariant(obj instanceof Object && !Array.isArray(obj)));
for (key in obj) {
if (!obj.hasOwnProperty(key)) {
continue;
}
ret[key] = key;
}
return ret;
};
module.exports = keyMirror;
},{"./invariant":140}],147:[function(_dereq_,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;
},{}],148:[function(_dereq_,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 mapObject
*/
'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;
},{}],149:[function(_dereq_,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 memoizeStringOnly
* @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)) {
return cache[string];
} else {
return cache[string] = callback.call(this, string);
}
};
}
module.exports = memoizeStringOnly;
},{}],150:[function(_dereq_,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 monitorCodeUse
*/
"use strict";
var invariant = _dereq_("./invariant");
/**
* Provides open-source compatible instrumentation for monitoring certain API
* uses before we're ready to issue a warning or refactor. It accepts an event
* name which may only contain the characters [a-z0-9_] and an optional data
* object with further information.
*/
function monitorCodeUse(eventName, data) {
("production" !== "development" ? invariant(
eventName && !/[^a-z0-9_]/.test(eventName),
'You must provide an eventName using only the characters [a-z0-9_]'
) : invariant(eventName && !/[^a-z0-9_]/.test(eventName)));
}
module.exports = monitorCodeUse;
},{"./invariant":140}],151:[function(_dereq_,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 onlyChild
*/
"use strict";
var ReactElement = _dereq_("./ReactElement");
var invariant = _dereq_("./invariant");
/**
* 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) {
("production" !== "development" ? invariant(
ReactElement.isValidElement(children),
'onlyChild must be passed a children with exactly one child.'
) : invariant(ReactElement.isValidElement(children)));
return children;
}
module.exports = onlyChild;
},{"./ReactElement":58,"./invariant":140}],152:[function(_dereq_,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 performance
* @typechecks
*/
"use strict";
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
var performance;
if (ExecutionEnvironment.canUseDOM) {
performance =
window.performance ||
window.msPerformance ||
window.webkitPerformance;
}
module.exports = performance || {};
},{"./ExecutionEnvironment":23}],153:[function(_dereq_,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 performanceNow
* @typechecks
*/
var performance = _dereq_("./performance");
/**
* 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 || !performance.now) {
performance = Date;
}
var performanceNow = performance.now.bind(performance);
module.exports = performanceNow;
},{"./performance":152}],154:[function(_dereq_,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 setInnerHTML
*/
"use strict";
var ExecutionEnvironment = _dereq_("./ExecutionEnvironment");
var WHITESPACE_TEST = /^[ \r\n\t\f]/;
var NONVISIBLE_TEST = /<(!--|link|noscript|meta|script|style)[ \r\n\t\f\/>]/;
/**
* Set the innerHTML property of a node, ensuring that whitespace is preserved
* even in IE8.
*
* @param {DOMElement} node
* @param {string} html
* @internal
*/
var setInnerHTML = 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.
node.innerHTML = '\uFEFF' + 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;
},{"./ExecutionEnvironment":23}],155:[function(_dereq_,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 shallowEqual
*/
"use strict";
/**
* Performs equality by iterating through keys on an object and returning
* false when any key has values which are not strictly equal between
* objA and objB. Returns true when the values of all keys are strictly equal.
*
* @return {boolean}
*/
function shallowEqual(objA, objB) {
if (objA === objB) {
return true;
}
var key;
// Test for A's keys different from B.
for (key in objA) {
if (objA.hasOwnProperty(key) &&
(!objB.hasOwnProperty(key) || objA[key] !== objB[key])) {
return false;
}
}
// Test for B's keys missing from A.
for (key in objB) {
if (objB.hasOwnProperty(key) && !objA.hasOwnProperty(key)) {
return false;
}
}
return true;
}
module.exports = shallowEqual;
},{}],156:[function(_dereq_,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 shouldUpdateReactComponent
* @typechecks static-only
*/
"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) {
if (prevElement && nextElement &&
prevElement.type === nextElement.type &&
prevElement.key === nextElement.key &&
prevElement._owner === nextElement._owner) {
return true;
}
return false;
}
module.exports = shouldUpdateReactComponent;
},{}],157:[function(_dereq_,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 toArray
* @typechecks
*/
var invariant = _dereq_("./invariant");
/**
* Convert array-like objects to arrays.
*
* This API assumes the caller knows the contents of the data type. For less
* well defined inputs use createArrayFrom.
*
* @param {object|function|filelist} obj
* @return {array}
*/
function toArray(obj) {
var length = obj.length;
// Some browse builtin objects can report typeof 'function' (e.g. NodeList in
// old versions of Safari).
("production" !== "development" ? invariant(
!Array.isArray(obj) &&
(typeof obj === 'object' || typeof obj === 'function'),
'toArray: Array-like object expected'
) : invariant(!Array.isArray(obj) &&
(typeof obj === 'object' || typeof obj === 'function')));
("production" !== "development" ? invariant(
typeof length === 'number',
'toArray: Object needs a length property'
) : invariant(typeof length === 'number'));
("production" !== "development" ? invariant(
length === 0 ||
(length - 1) in obj,
'toArray: Object should have keys for indices'
) : invariant(length === 0 ||
(length - 1) in obj));
// 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;
}
module.exports = toArray;
},{"./invariant":140}],158:[function(_dereq_,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 traverseAllChildren
*/
"use strict";
var ReactElement = _dereq_("./ReactElement");
var ReactInstanceHandles = _dereq_("./ReactInstanceHandles");
var invariant = _dereq_("./invariant");
var SEPARATOR = ReactInstanceHandles.SEPARATOR;
var SUBSEPARATOR = ':';
/**
* TODO: Test that:
* 1. `mapChildren` transforms strings and numbers into `ReactTextComponent`.
* 2. it('should fail when supplied duplicate key', function() {
* 3. That a single child and an array with one item have the same key pattern.
* });
*/
var userProvidedKeyEscaperLookup = {
'=': '=0',
'.': '=1',
':': '=2'
};
var userProvidedKeyEscapeRegex = /[=.:]/g;
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) {
if (component && 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 {*} key 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 {!number} indexSoFar Number of children encountered until this point.
* @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.
*/
var traverseAllChildrenImpl =
function(children, nameSoFar, indexSoFar, callback, traverseContext) {
var nextName, nextIndex;
var subtreeCount = 0; // Count of children found in the current subtree.
if (Array.isArray(children)) {
for (var i = 0; i < children.length; i++) {
var child = children[i];
nextName = (
nameSoFar +
(nameSoFar ? SUBSEPARATOR : SEPARATOR) +
getComponentKey(child, i)
);
nextIndex = indexSoFar + subtreeCount;
subtreeCount += traverseAllChildrenImpl(
child,
nextName,
nextIndex,
callback,
traverseContext
);
}
} else {
var type = typeof children;
var isOnlyChild = nameSoFar === '';
// 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
var storageName =
isOnlyChild ? SEPARATOR + getComponentKey(children, 0) : nameSoFar;
if (children == null || type === 'boolean') {
// All of the above are perceived as null.
callback(traverseContext, null, storageName, indexSoFar);
subtreeCount = 1;
} else if (type === 'string' || type === 'number' ||
ReactElement.isValidElement(children)) {
callback(traverseContext, children, storageName, indexSoFar);
subtreeCount = 1;
} else if (type === 'object') {
("production" !== "development" ? invariant(
!children || children.nodeType !== 1,
'traverseAllChildren(...): Encountered an invalid child; DOM ' +
'elements are not valid children of React components.'
) : invariant(!children || children.nodeType !== 1));
for (var key in children) {
if (children.hasOwnProperty(key)) {
nextName = (
nameSoFar + (nameSoFar ? SUBSEPARATOR : SEPARATOR) +
wrapUserProvidedKey(key) + SUBSEPARATOR +
getComponentKey(children[key], 0)
);
nextIndex = indexSoFar + subtreeCount;
subtreeCount += traverseAllChildrenImpl(
children[key],
nextName,
nextIndex,
callback,
traverseContext
);
}
}
}
}
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, '', 0, callback, traverseContext);
}
module.exports = traverseAllChildren;
},{"./ReactElement":58,"./ReactInstanceHandles":66,"./invariant":140}],159:[function(_dereq_,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 update
*/
"use strict";
var assign = _dereq_("./Object.assign");
var keyOf = _dereq_("./keyOf");
var invariant = _dereq_("./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" !== "development" ? 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" !== "development" ? 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" !== "development" ? 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" !== "development" ? 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" !== "development" ? invariant(
mergeObj && typeof mergeObj === 'object',
'update(): %s expects a spec of type \'object\'; got %s',
COMMAND_MERGE,
mergeObj
) : invariant(mergeObj && typeof mergeObj === 'object'));
("production" !== "development" ? 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" !== "development" ? invariant(
Array.isArray(value),
'Expected %s target to be an array; got %s',
COMMAND_SPLICE,
value
) : invariant(Array.isArray(value)));
("production" !== "development" ? 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" !== "development" ? 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" !== "development" ? 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;
},{"./Object.assign":29,"./invariant":140,"./keyOf":147}],160:[function(_dereq_,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 warning
*/
"use strict";
var emptyFunction = _dereq_("./emptyFunction");
/**
* 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 ("production" !== "development") {
warning = function(condition, format ) {var args=Array.prototype.slice.call(arguments,2);
if (format === undefined) {
throw new Error(
'`warning(condition, format, ...args)` requires a warning ' +
'message argument'
);
}
if (!condition) {
var argIndex = 0;
console.warn('Warning: ' + format.replace(/%s/g, function() {return args[argIndex++];}));
}
};
}
module.exports = warning;
},{"./emptyFunction":121}]},{},[1])(1)
}); |
ajax/libs/mobx-react/4.0.0-rc.4/custom.min.js | emmy41124/cdnjs | !function(e,t){"object"==typeof exports&&"object"==typeof module?module.exports=t(require("mobx"),require("react")):"function"==typeof define&&define.amd?define(["mobx","react"],t):"object"==typeof exports?exports.mobxReact=t(require("mobx"),require("react")):e.mobxReact=t(e.mobx,e.React)}(this,function(e,t){return function(e){function t(n){if(r[n])return r[n].exports;var o=r[n]={exports:{},id:n,loaded:!1};return e[n].call(o.exports,o,o.exports,t),o.loaded=!0,o.exports}var r={};return t.m=e,t.c=r,t.p="",t(0)}([function(e,t,r){"use strict";function n(e){if(e&&e.__esModule)return e;var t={};if(null!=e)for(var r in e)Object.prototype.hasOwnProperty.call(e,r)&&(t[r]=e[r]);return t.default=e,t}function o(e){return e&&e.__esModule?e:{default:e}}Object.defineProperty(t,"__esModule",{value:!0}),t.reactiveComponent=t.PropTypes=t.propTypes=t.inject=t.Provider=t.useStaticRendering=t.trackComponents=t.componentByNodeRegistery=t.renderReporter=t.Observer=t.observer=void 0;var i="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e},a=arguments,s=r(1);Object.defineProperty(t,"observer",{enumerable:!0,get:function(){return s.observer}}),Object.defineProperty(t,"Observer",{enumerable:!0,get:function(){return s.Observer}}),Object.defineProperty(t,"renderReporter",{enumerable:!0,get:function(){return s.renderReporter}}),Object.defineProperty(t,"componentByNodeRegistery",{enumerable:!0,get:function(){return s.componentByNodeRegistery}}),Object.defineProperty(t,"trackComponents",{enumerable:!0,get:function(){return s.trackComponents}}),Object.defineProperty(t,"useStaticRendering",{enumerable:!0,get:function(){return s.useStaticRendering}});var u=r(8);Object.defineProperty(t,"Provider",{enumerable:!0,get:function(){return o(u).default}});var c=r(6);Object.defineProperty(t,"inject",{enumerable:!0,get:function(){return o(c).default}});var f=r(2),l=o(f),p=r(3),d=o(p),b=(r(4),r(4),r(9)),y=n(b),m=void 0;if(m="mobx-react/custom",!l.default)throw new Error(m+" requires the MobX package");if(!d.default)throw new Error(m+" requires React to be available");t.propTypes=y,t.PropTypes=y,t.default=e.exports;t.reactiveComponent=function(){return console.warn("[mobx-react] `reactiveComponent` has been renamed to `observer` and will be removed in 1.1."),observer.apply(null,a)};"object"===("undefined"==typeof __MOBX_DEVTOOLS_GLOBAL_HOOK__?"undefined":i(__MOBX_DEVTOOLS_GLOBAL_HOOK__))&&__MOBX_DEVTOOLS_GLOBAL_HOOK__.injectMobxReact(e.exports,l.default)},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e){return v.default?v.default.findDOMNode(e):null}function i(e){var t=o(e);t&&P&&P.set(t,e),S.emit({event:"render",renderTime:e.__$mobRenderEnd-e.__$mobRenderStart,totalTime:Date.now()-e.__$mobRenderStart,component:e,node:t})}function a(){if("undefined"==typeof WeakMap)throw new Error("[mobx-react] tracking components is not supported in this browser.");x||(x=!0)}function s(e){_=e}function u(e,t){var r=e[t],n=M[t];r?e[t]=function(){r.apply(this,arguments),n.apply(this,arguments)}:e[t]=n}function c(e,t){if(null==e||null==t||"object"!==("undefined"==typeof e?"undefined":l(e))||"object"!==("undefined"==typeof t?"undefined":l(t)))return e!==t;var r=Object.keys(e);if(r.length!==Object.keys(t).length)return!0;for(var n=void 0,o=r.length-1;n=r[o];o--)if(t[n]!==e[n])return!0;return!1}function f(e,t){if("string"==typeof e)throw new Error("Store names should be provided as array");if(Array.isArray(e))return w||(w=!0,console.warn('Mobx observer: Using observer to inject stores is deprecated since 4.0. Use `@inject("store1", "store2") @observer ComponentClass` or `inject("store1", "store2")(observer(componentClass))` instead of `@observer(["store1", "store2"]) ComponentClass`')),t?j.default.apply(null,e)(f(t)):function(t){return f(e,t)};var r=e;if(r.isMobxInjector===!0&&console.warn("Mobx observer: You are trying to use 'observer' on a component that already has 'inject'. Please apply 'observer' before applying 'inject'"),!("function"!=typeof r||r.prototype&&r.prototype.render||r.isReactClass||y.default.Component.isPrototypeOf(r)))return f(y.default.createClass({displayName:r.displayName||r.name,propTypes:r.propTypes,contextTypes:r.contextTypes,getDefaultProps:function(){return r.defaultProps},render:function(){return r.call(this,this.props,this.context)}}));if(!r)throw new Error("Please pass a valid component to 'observer'");var n=r.prototype||r;return["componentWillMount","componentWillUnmount","componentDidMount","componentDidUpdate"].forEach(function(e){u(n,e)}),n.shouldComponentUpdate||(n.shouldComponentUpdate=M.shouldComponentUpdate),r.isMobXReactObserver=!0,r}Object.defineProperty(t,"__esModule",{value:!0}),t.Observer=t.renderReporter=t.componentByNodeRegistery=void 0;var l="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e};t.trackComponents=a,t.useStaticRendering=s,t.observer=f;var p=r(2),d=n(p),b=r(3),y=n(b),m=r(4),v=n(m),h=r(5),O=n(h),g=r(6),j=n(g),x=!1,_=!1,w=!1,P=t.componentByNodeRegistery="undefined"!=typeof WeakMap?new WeakMap:void 0,S=t.renderReporter=new O.default,M={componentWillMount:function(){function e(e){var t=this[e],r=new d.default.Atom("reactive "+e);Object.defineProperty(this,e,{configurable:!0,enumerable:!0,get:function(){return r.reportObserved(),t},set:function(e){!i&&c(t,e)?(t=e,o=!0,r.reportChanged(),o=!1):t=e}})}var t=this;if(_!==!0){var r=this.displayName||this.name||this.constructor&&(this.constructor.displayName||this.constructor.name)||"<component>",n=this._reactInternalInstance&&this._reactInternalInstance._rootNodeID,o=!1,i=!1;e.call(this,"props"),e.call(this,"state");var a=this.render.bind(this),s=null,u=!1,f=function(){return s=new d.default.Reaction(r+"#"+n+".render()",function(){if(!u&&(u=!0,"function"==typeof t.componentWillReact&&t.componentWillReact(),t.__$mobxIsUnmounted!==!0)){var e=!0;try{i=!0,o||y.default.Component.prototype.forceUpdate.call(t),e=!1}finally{i=!1,e&&s.dispose()}}}),l.$mobx=s,t.render=l,l()},l=function(){u=!1;var e=void 0;return s.track(function(){x&&(t.__$mobRenderStart=Date.now()),e=d.default.extras.allowStateChanges(!1,a),x&&(t.__$mobRenderEnd=Date.now())}),e};this.render=f}},componentWillUnmount:function(){if(_!==!0&&(this.render.$mobx&&this.render.$mobx.dispose(),this.__$mobxIsUnmounted=!0,x)){var e=o(this);e&&P&&P.delete(e),S.emit({event:"destroy",component:this,node:e})}},componentDidMount:function(){x&&i(this)},componentDidUpdate:function(){x&&i(this)},shouldComponentUpdate:function(e,t){return _&&console.warn("[mobx-react] It seems that a re-rendering of a React component is triggered while in static (server-side) mode. Please make sure components are rendered only once server-side."),this.state!==t||c(this.props,e)}},R=t.Observer=f(function(e){var t=e.children;return t()});R.propTypes={children:y.default.PropTypes.func.isRequired}},function(t,r){t.exports=e},function(e,r){e.exports=t},function(e,t){e.exports=null},function(e,t){"use strict";function r(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}Object.defineProperty(t,"__esModule",{value:!0});var n=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}}(),o=function(){function e(){r(this,e),this.listeners=[]}return n(e,[{key:"on",value:function(e){var t=this;return this.listeners.push(e),function(){var r=t.listeners.indexOf(e);r!==-1&&t.listeners.splice(r,1)}}},{key:"emit",value:function(e){this.listeners.forEach(function(t){return t(e)})}}]),e}();t.default=o},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t,r){var n="inject-"+(t.displayName||t.name||t.constructor&&t.constructor.name||"Unknown");r&&(n+="-with-"+r);var o=c.default.createClass({displayName:n,storeRef:function(e){this.wrappedInstance=e},render:function(){var r={};for(var n in this.props)this.props.hasOwnProperty(n)&&(r[n]=this.props[n]);var o=e(this.context.mobxStores||{},r,this.context)||{};for(var i in o)r[i]=o[i];return r.ref=this.storeRef,c.default.createElement(t,r)}});return(0,l.default)(o,t),o.wrappedComponent=t,Object.defineProperties(o,b),o}function i(e){return function(t,r){return e.forEach(function(e){if(!(e in r)){if(!(e in t))throw new Error("MobX observer: Store '"+e+"' is not available! Make sure it is provided by some Provider");r[e]=t[e]}}),r}}function a(){var e=arguments,t=void 0;if("function"==typeof arguments[0])return t=arguments[0],function(e){var r=o(t,e);return r.isMobxInjector=!1,r=(0,p.observer)(r),r.isMobxInjector=!0,r};var r=function(){for(var r=[],n=0;n<e.length;n++)r[n]=e[n];return t=i(r),{v:function(e){return o(t,e,r.join("-"))}}}();return"object"===("undefined"==typeof r?"undefined":s(r))?r.v:void 0}Object.defineProperty(t,"__esModule",{value:!0});var s="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e};t.default=a;var u=r(3),c=n(u),f=r(7),l=n(f),p=r(1),d={mobxStores:u.PropTypes.object};Object.seal(d);var b={contextTypes:{get:function(){return d},set:function(e){console.warn("Mobx Injector: you are trying to attach `contextTypes` on an component decorated with `inject` (or `observer`) HOC. Please specify the contextTypes on the wrapped component instead. It is accessible through the `wrappedComponent`")},configurable:!0,enumerable:!1},isMobxInjector:{value:!0,writable:!0,configurable:!0,enumerable:!0}}},function(e,t){"use strict";var r={childContextTypes:!0,contextTypes:!0,defaultProps:!0,displayName:!0,getDefaultProps:!0,mixins:!0,propTypes:!0,type:!0},n={name:!0,length:!0,prototype:!0,caller:!0,arguments:!0,arity:!0},o="function"==typeof Object.getOwnPropertySymbols;e.exports=function(e,t,i){if("string"!=typeof t){var a=Object.getOwnPropertyNames(t);o&&(a=a.concat(Object.getOwnPropertySymbols(t)));for(var s=0;s<a.length;++s)if(!(r[a[s]]||n[a[s]]||i&&i[a[s]]))try{e[a[s]]=t[a[s]]}catch(e){}}return e}},function(e,t,r){"use strict";function n(e){return e&&e.__esModule?e:{default:e}}function o(e,t){if(!(e instanceof t))throw new TypeError("Cannot call a class as a function")}function i(e,t){if(!e)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!t||"object"!=typeof t&&"function"!=typeof t?e:t}function a(e,t){if("function"!=typeof t&&null!==t)throw new TypeError("Super expression must either be null or a function, not "+typeof t);e.prototype=Object.create(t&&t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}),t&&(Object.setPrototypeOf?Object.setPrototypeOf(e,t):e.__proto__=t)}Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0;var s,u,c=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}}(),f=r(3),l=n(f),p={children:!0,key:!0,ref:!0},d=(u=s=function(e){function t(){return o(this,t),i(this,Object.getPrototypeOf(t).apply(this,arguments))}return a(t,e),c(t,[{key:"render",value:function(){return l.default.Children.only(this.props.children)}},{key:"getChildContext",value:function(){var e={},t=this.context.mobxStores;if(t)for(var r in t)e[r]=t[r];for(var n in this.props)p[n]||(e[n]=this.props[n]);return{mobxStores:e}}},{key:"componentWillReceiveProps",value:function(e){Object.keys(e).length!==Object.keys(this.props).length&&console.warn("MobX Provider: The set of provided stores has changed. Please avoid changing stores as the change might not propagate to all children");for(var t in e)p[t]||this.props[t]===e[t]||console.warn("MobX Provider: Provided store '"+t+"' has changed. Please avoid replacing stores as the change might not propagate to all children")}}]),t}(f.Component),s.contextTypes={mobxStores:f.PropTypes.object},s.childContextTypes={mobxStores:f.PropTypes.object.isRequired},u);t.default=d},function(e,t,r){"use strict";function n(e){function t(t,r,n,o,i,a){for(var s=arguments.length,u=Array(s>6?s-6:0),c=6;c<s;c++)u[c-6]=arguments[c];return(0,f.untracked)(function(){if(o=o||"<<anonymous>>",a=a||n,null==r[n]){if(t){var s=null===r[n]?"null":"undefined";return new Error("The "+i+" `"+a+"` is marked as required in `"+o+"`, but its value is `"+s+"`.")}return null}return e.apply(void 0,[r,n,o,i,a].concat(u))})}var r=t.bind(null,!1);return r.isRequired=t.bind(null,!0),r}function o(e,t){return"symbol"===e||("Symbol"===t["@@toStringTag"]||"function"==typeof Symbol&&t instanceof Symbol)}function i(e){var t="undefined"==typeof e?"undefined":c(e);return Array.isArray(e)?"array":e instanceof RegExp?"object":o(t,e)?"symbol":t}function a(e){var t=i(e);if("object"===t){if(e instanceof Date)return"date";if(e instanceof RegExp)return"regexp"}return t}function s(e,t){return n(function(r,n,o,s,u){return(0,f.untracked)(function(){if(e&&i(r[n])===t.toLowerCase())return null;var s=void 0;switch(t){case"Array":s=f.isObservableArray;break;case"Object":s=f.isObservableObject;break;case"Map":s=f.isObservableMap;break;default:throw new Error("Unexpected mobxType: "+t)}var c=r[n];if(!s(c)){var l=a(c),p=e?" or javascript `"+t.toLowerCase()+"`":"";return new Error("Invalid prop `"+u+"` of type `"+l+"` supplied to `"+o+"`, expected `mobx.Observable"+t+"`"+p+".")}return null})})}function u(e,t){return n(function(r,n,o,i,a){for(var u=arguments.length,c=Array(u>5?u-5:0),l=5;l<u;l++)c[l-5]=arguments[l];return(0,f.untracked)(function(){if("function"!=typeof t)return new Error("Property `"+a+"` of component `"+o+"` has invalid PropType notation.");var u=s(e,"Array")(r,n,o);if(u instanceof Error)return u;for(var f=r[n],l=0;l<f.length;l++)if(u=t.apply(void 0,[f,l,o,i,a+"["+l+"]"].concat(c)),u instanceof Error)return u;return null})})}Object.defineProperty(t,"__esModule",{value:!0}),t.objectOrObservableObject=t.arrayOrObservableArrayOf=t.arrayOrObservableArray=t.observableObject=t.observableMap=t.observableArrayOf=t.observableArray=void 0;var c="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(e){return typeof e}:function(e){return e&&"function"==typeof Symbol&&e.constructor===Symbol?"symbol":typeof e},f=r(2);t.observableArray=s(!1,"Array"),t.observableArrayOf=u.bind(null,!1),t.observableMap=s(!1,"Map"),t.observableObject=s(!1,"Object"),t.arrayOrObservableArray=s(!0,"Array"),t.arrayOrObservableArrayOf=u.bind(null,!0),t.objectOrObservableObject=s(!0,"Object")}])});
//# sourceMappingURL=custom.min.js.map |
Examples/UIExplorer/ProgressViewIOSExample.js | hzgnpu/react-native | /**
* The examples provided by Facebook are for non-commercial testing and
* evaluation purposes only.
*
* Facebook reserves all rights not expressly granted.
*
* 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 NON INFRINGEMENT. IN NO EVENT SHALL
* FACEBOOK 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.
*
* @flow
*/
'use strict';
var React = require('react-native');
var {
ProgressViewIOS,
StyleSheet,
View,
} = React;
var TimerMixin = require('react-timer-mixin');
var ProgressViewExample = React.createClass({
mixins: [TimerMixin],
getInitialState() {
return {
progress: 0,
};
},
componentDidMount() {
this.updateProgress();
},
updateProgress() {
var progress = this.state.progress + 0.01;
this.setState({ progress });
this.requestAnimationFrame(() => this.updateProgress());
},
getProgress(offset) {
var progress = this.state.progress + offset;
return Math.sin(progress % Math.PI) % 1;
},
render() {
return (
<View style={styles.container}>
<ProgressViewIOS style={styles.progressView} progress={this.getProgress(0)}/>
<ProgressViewIOS style={styles.progressView} progressTintColor="purple" progress={this.getProgress(0.2)}/>
<ProgressViewIOS style={styles.progressView} progressTintColor="red" progress={this.getProgress(0.4)}/>
<ProgressViewIOS style={styles.progressView} progressTintColor="orange" progress={this.getProgress(0.6)}/>
<ProgressViewIOS style={styles.progressView} progressTintColor="yellow" progress={this.getProgress(0.8)}/>
</View>
);
},
});
exports.displayName = (undefined: ?string);
exports.framework = 'React';
exports.title = 'ProgressViewIOS';
exports.description = 'ProgressViewIOS';
exports.examples = [{
title: 'ProgressViewIOS',
render() {
return (
<ProgressViewExample/>
);
}
}];
var styles = StyleSheet.create({
container: {
marginTop: -20,
backgroundColor: 'transparent',
},
progressView: {
marginTop: 20,
}
});
|
spring-boot-samples/spring-boot-sample-web-groovy-templates/src/main/resources/static/js/jquery-1.7.2.js | hehuabing/spring-boot | /*!
* jQuery JavaScript Library v1.7.2
* 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: Wed Mar 21 12:46:34 2012 -0700
*/
(function( window, undefined ) {
// Use the correct document accordingly with window argument (sandbox)
var document = window.document,
navigator = window.navigator,
location = window.location;
var jQuery = (function() {
// Define a local copy of jQuery
var jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// A central reference to the root jQuery(document)
rootjQuery,
// A simple way to check for HTML strings or ID strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,
// Check if a string has a non-whitespace character in it
rnotwhite = /\S/,
// Used for trimming whitespace
trimLeft = /^\s+/,
trimRight = /\s+$/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/,
// JSON RegExp
rvalidchars = /^[\],:{}\s]*$/,
rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,
rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
// Useragent RegExp
rwebkit = /(webkit)[ \/]([\w.]+)/,
ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/,
rmsie = /(msie) ([\w.]+)/,
rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/,
// Matches dashed string for camelizing
rdashAlpha = /-([a-z]|[0-9])/ig,
rmsPrefix = /^-ms-/,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return ( letter + "" ).toUpperCase();
},
// Keep a UserAgent string for use with jQuery.browser
userAgent = navigator.userAgent,
// For matching the engine and version of the browser
browserMatch,
// The deferred used on DOM ready
readyList,
// The ready event handler
DOMContentLoaded,
// Save a reference to some core methods
toString = Object.prototype.toString,
hasOwn = Object.prototype.hasOwnProperty,
push = Array.prototype.push,
slice = Array.prototype.slice,
trim = String.prototype.trim,
indexOf = Array.prototype.indexOf,
// [[Class]] -> type pairs
class2type = {};
jQuery.fn = jQuery.prototype = {
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem, ret, doc;
// Handle $(""), $(null), or $(undefined)
if ( !selector ) {
return this;
}
// Handle $(DOMElement)
if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
}
// The body element only exists once, optimize finding it
if ( selector === "body" && !context && document.body ) {
this.context = document;
this[0] = document.body;
this.selector = selector;
this.length = 1;
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
// Are we dealing with HTML string or an ID?
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = quickExpr.exec( selector );
}
// Verify a match, and that no context was specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
doc = ( context ? context.ownerDocument || context : document );
// If a single string is passed in and it's a single tag
// just do a createElement and skip the rest
ret = rsingleTag.exec( selector );
if ( ret ) {
if ( jQuery.isPlainObject( context ) ) {
selector = [ document.createElement( ret[1] ) ];
jQuery.fn.attr.call( selector, context, true );
} else {
selector = [ doc.createElement( ret[1] ) ];
}
} else {
ret = jQuery.buildFragment( [ match[1] ], [ doc ] );
selector = ( ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment ).childNodes;
}
return jQuery.merge( this, selector );
// HANDLE: $("#id")
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The current version of jQuery being used
jquery: "1.7.2",
// The default length of a jQuery object is 0
length: 0,
// The number of elements contained in the matched element set
size: function() {
return this.length;
},
toArray: function() {
return slice.call( this, 0 );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems, name, selector ) {
// Build a new jQuery matched element set
var ret = this.constructor();
if ( jQuery.isArray( elems ) ) {
push.apply( ret, elems );
} else {
jQuery.merge( ret, elems );
}
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
if ( name === "find" ) {
ret.selector = this.selector + ( this.selector ? " " : "" ) + selector;
} else if ( name ) {
ret.selector = this.selector + "." + name + "(" + selector + ")";
}
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Attach the listeners
jQuery.bindReady();
// Add the callback
readyList.add( fn );
return this;
},
eq: function( i ) {
i = +i;
return i === -1 ?
this.slice( i ) :
this.slice( i, i + 1 );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
slice: function() {
return this.pushStack( slice.apply( this, arguments ),
"slice", slice.call(arguments).join(",") );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Either a released hold or an DOMready/load event and not yet ready
if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) {
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready, 1 );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.fireWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger( "ready" ).off( "ready" );
}
}
},
bindReady: function() {
if ( readyList ) {
return;
}
readyList = jQuery.Callbacks( "once memory" );
// Catch cases where $(document).ready() is called after the
// browser event has already occurred.
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
return setTimeout( jQuery.ready, 1 );
}
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", jQuery.ready, false );
// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload,
// maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", DOMContentLoaded );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", jQuery.ready );
// If IE and not a frame
// continually check to see if the document is ready
var toplevel = false;
try {
toplevel = window.frameElement == null;
} catch(e) {}
if ( document.documentElement.doScroll && toplevel ) {
doScrollCheck();
}
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
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[ toString.call(obj) ] || "object";
},
isPlainObject: function( obj ) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!hasOwn.call(obj, "constructor") &&
!hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}
return key === undefined || hasOwn.call( obj, key );
},
isEmptyObject: function( obj ) {
for ( var name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw new Error( msg );
},
parseJSON: function( data ) {
if ( typeof data !== "string" || !data ) {
return null;
}
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return ( new Function( "return " + data ) )();
}
jQuery.error( "Invalid JSON: " + data );
},
// Cross-browser xml parsing
parseXML: function( data ) {
if ( typeof data !== "string" || !data ) {
return null;
}
var xml, tmp;
try {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
} catch( e ) {
xml = undefined;
}
if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && rnotwhite.test( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase();
},
// args is for internal usage only
each: function( object, callback, args ) {
var name, i = 0,
length = object.length,
isObj = length === undefined || jQuery.isFunction( object );
if ( args ) {
if ( isObj ) {
for ( name in object ) {
if ( callback.apply( object[ name ], args ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.apply( object[ i++ ], args ) === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isObj ) {
for ( name in object ) {
if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) {
break;
}
}
}
}
return object;
},
// Use native String.trim function wherever possible
trim: trim ?
function( text ) {
return text == null ?
"" :
trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
"" :
text.toString().replace( trimLeft, "" ).replace( trimRight, "" );
},
// results is for internal usage only
makeArray: function( array, results ) {
var ret = results || [];
if ( array != null ) {
// The window, strings (and functions) also have 'length'
// Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
var type = jQuery.type( array );
if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) {
push.call( ret, array );
} else {
jQuery.merge( ret, array );
}
}
return ret;
},
inArray: function( elem, array, i ) {
var len;
if ( array ) {
if ( indexOf ) {
return indexOf.call( array, elem, i );
}
len = array.length;
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
for ( ; i < len; i++ ) {
// Skip accessing in sparse arrays
if ( i in array && array[ i ] === elem ) {
return i;
}
}
}
return -1;
},
merge: function( first, second ) {
var i = first.length,
j = 0;
if ( typeof second.length === "number" ) {
for ( var l = second.length; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, inv ) {
var ret = [], retVal;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( var i = 0, length = elems.length; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value, key, ret = [],
i = 0,
length = elems.length,
// jquery objects are treated as arrays
isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ;
// Go through the array, translating each of the items to their
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
} else {
for ( key in elems ) {
value = callback( elems[ key ], key, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return ret.concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
if ( typeof context === "string" ) {
var tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
var args = slice.call( arguments, 2 ),
proxy = function() {
return fn.apply( context, args.concat( slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;
return proxy;
},
// Mutifunctional method to get and set values to a collection
// The value/s can optionally be executed if it's a function
access: function( elems, 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();
},
// Use of jQuery.browser is frowned upon.
// More details: http://docs.jquery.com/Utilities/jQuery.browser
uaMatch: function( ua ) {
ua = ua.toLowerCase();
var match = rwebkit.exec( ua ) ||
ropera.exec( ua ) ||
rmsie.exec( ua ) ||
ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) ||
[];
return { browser: match[1] || "", version: match[2] || "0" };
},
sub: function() {
function jQuerySub( selector, context ) {
return new jQuerySub.fn.init( selector, context );
}
jQuery.extend( true, jQuerySub, this );
jQuerySub.superclass = this;
jQuerySub.fn = jQuerySub.prototype = this();
jQuerySub.fn.constructor = jQuerySub;
jQuerySub.sub = this.sub;
jQuerySub.fn.init = function init( selector, context ) {
if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
context = jQuerySub( context );
}
return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
};
jQuerySub.fn.init.prototype = jQuerySub.fn;
var rootjQuerySub = jQuerySub(document);
return jQuerySub;
},
browser: {}
});
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
browserMatch = jQuery.uaMatch( userAgent );
if ( browserMatch.browser ) {
jQuery.browser[ browserMatch.browser ] = true;
jQuery.browser.version = browserMatch.version;
}
// Deprecated, use jQuery.browser.webkit instead
if ( jQuery.browser.webkit ) {
jQuery.browser.safari = true;
}
// IE doesn't match non-breaking spaces with \s
if ( rnotwhite.test( "\xA0" ) ) {
trimLeft = /^[\s\xA0]+/;
trimRight = /[\s\xA0]+$/;
}
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
// Cleanup functions for the document ready method
if ( document.addEventListener ) {
DOMContentLoaded = function() {
document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
jQuery.ready();
};
} else if ( document.attachEvent ) {
DOMContentLoaded = function() {
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( document.readyState === "complete" ) {
document.detachEvent( "onreadystatechange", DOMContentLoaded );
jQuery.ready();
}
};
}
// The DOM ready check for Internet Explorer
function doScrollCheck() {
if ( jQuery.isReady ) {
return;
}
try {
// If IE is used, use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
document.documentElement.doScroll("left");
} catch(e) {
setTimeout( doScrollCheck, 1 );
return;
}
// and execute any waiting functions
jQuery.ready();
}
return jQuery;
})();
// String to Object flags format cache
var flagsCache = {};
// Convert String-formatted flags into Object-formatted ones and store in cache
function createFlags( flags ) {
var object = flagsCache[ flags ] = {},
i, length;
flags = flags.split( /\s+/ );
for ( i = 0, length = flags.length; i < length; i++ ) {
object[ flags[i] ] = true;
}
return object;
}
/*
* Create a callback list using the following parameters:
*
* flags: an optional list of space-separated flags that will change how
* the callback list behaves
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible flags:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( flags ) {
// Convert flags from String-formatted to Object-formatted
// (we check in cache first)
flags = flags ? ( flagsCache[ flags ] || createFlags( flags ) ) : {};
var // Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = [],
// Last fire value (for non-forgettable lists)
memory,
// Flag to know if list 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,
// Add one or several callbacks to the list
add = function( args ) {
var i,
length,
elem,
type,
actual;
for ( i = 0, length = args.length; i < length; i++ ) {
elem = args[ i ];
type = jQuery.type( elem );
if ( type === "array" ) {
// Inspect recursively
add( elem );
} else if ( type === "function" ) {
// Add if not in unique mode and callback is not in
if ( !flags.unique || !self.has( elem ) ) {
list.push( elem );
}
}
}
},
// Fire callbacks
fire = function( context, args ) {
args = args || [];
memory = !flags.memory || [ context, args ];
fired = true;
firing = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( context, args ) === false && flags.stopOnFalse ) {
memory = true; // Mark as halted
break;
}
}
firing = false;
if ( list ) {
if ( !flags.once ) {
if ( stack && stack.length ) {
memory = stack.shift();
self.fireWith( memory[ 0 ], memory[ 1 ] );
}
} else if ( memory === true ) {
self.disable();
} else {
list = [];
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
var length = list.length;
add( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away, unless previous
// firing was halted (stopOnFalse)
} else if ( memory && memory !== true ) {
firingStart = length;
fire( memory[ 0 ], memory[ 1 ] );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
var args = arguments,
argIndex = 0,
argLength = args.length;
for ( ; argIndex < argLength ; argIndex++ ) {
for ( var i = 0; i < list.length; i++ ) {
if ( args[ argIndex ] === list[ i ] ) {
// Handle firingIndex and firingLength
if ( firing ) {
if ( i <= firingLength ) {
firingLength--;
if ( i <= firingIndex ) {
firingIndex--;
}
}
}
// Remove the element
list.splice( i--, 1 );
// If we have some unicity property then
// we only need to do this once
if ( flags.unique ) {
break;
}
}
}
}
}
return this;
},
// Control if a given callback is in the list
has: function( fn ) {
if ( list ) {
var i = 0,
length = list.length;
for ( ; i < length; i++ ) {
if ( fn === list[ i ] ) {
return true;
}
}
}
return false;
},
// Remove all callbacks from the list
empty: function() {
list = [];
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory || memory === true ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
if ( stack ) {
if ( firing ) {
if ( !flags.once ) {
stack.push( [ context, args ] );
}
} else if ( !( flags.once && memory ) ) {
fire( context, args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
var // Static reference to slice
sliceDeferred = [].slice;
jQuery.extend({
Deferred: function( func ) {
var doneList = jQuery.Callbacks( "once memory" ),
failList = jQuery.Callbacks( "once memory" ),
progressList = jQuery.Callbacks( "memory" ),
state = "pending",
lists = {
resolve: doneList,
reject: failList,
notify: progressList
},
promise = {
done: doneList.add,
fail: failList.add,
progress: progressList.add,
state: function() {
return state;
},
// Deprecated
isResolved: doneList.fired,
isRejected: failList.fired,
then: function( doneCallbacks, failCallbacks, progressCallbacks ) {
deferred.done( doneCallbacks ).fail( failCallbacks ).progress( progressCallbacks );
return this;
},
always: function() {
deferred.done.apply( deferred, arguments ).fail.apply( deferred, arguments );
return this;
},
pipe: function( fnDone, fnFail, fnProgress ) {
return jQuery.Deferred(function( newDefer ) {
jQuery.each( {
done: [ fnDone, "resolve" ],
fail: [ fnFail, "reject" ],
progress: [ fnProgress, "notify" ]
}, function( handler, data ) {
var fn = data[ 0 ],
action = data[ 1 ],
returned;
if ( jQuery.isFunction( fn ) ) {
deferred[ handler ](function() {
returned = fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise().then( newDefer.resolve, newDefer.reject, newDefer.notify );
} else {
newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] );
}
});
} else {
deferred[ handler ]( newDefer[ action ] );
}
});
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
if ( obj == null ) {
obj = promise;
} else {
for ( var key in promise ) {
obj[ key ] = promise[ key ];
}
}
return obj;
}
},
deferred = promise.promise({}),
key;
for ( key in lists ) {
deferred[ key ] = lists[ key ].fire;
deferred[ key + "With" ] = lists[ key ].fireWith;
}
// Handle state
deferred.done( function() {
state = "resolved";
}, failList.disable, progressList.lock ).fail( function() {
state = "rejected";
}, doneList.disable, progressList.lock );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( firstParam ) {
var args = sliceDeferred.call( arguments, 0 ),
i = 0,
length = args.length,
pValues = new Array( length ),
count = length,
pCount = length,
deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ?
firstParam :
jQuery.Deferred(),
promise = deferred.promise();
function resolveFunc( i ) {
return function( value ) {
args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value;
if ( !( --count ) ) {
deferred.resolveWith( deferred, args );
}
};
}
function progressFunc( i ) {
return function( value ) {
pValues[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value;
deferred.notifyWith( promise, pValues );
};
}
if ( length > 1 ) {
for ( ; i < length; i++ ) {
if ( args[ i ] && args[ i ].promise && jQuery.isFunction( args[ i ].promise ) ) {
args[ i ].promise().then( resolveFunc(i), deferred.reject, progressFunc(i) );
} else {
--count;
}
}
if ( !count ) {
deferred.resolveWith( deferred, args );
}
} else if ( deferred !== firstParam ) {
deferred.resolveWith( deferred, length ? [ firstParam ] : [] );
}
return promise;
}
});
jQuery.support = (function() {
var support,
all,
a,
select,
opt,
input,
fragment,
tds,
events,
eventName,
i,
isSupported,
div = document.createElement( "div" ),
documentElement = document.documentElement;
// Preliminary tests
div.setAttribute("className", "t");
div.innerHTML = " <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>";
all = div.getElementsByTagName( "*" );
a = div.getElementsByTagName( "a" )[ 0 ];
// Can't get basic test support
if ( !all || !all.length || !a ) {
return {};
}
// First batch of supports tests
select = document.createElement( "select" );
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName( "input" )[ 0 ];
support = {
// IE strips leading whitespace when .innerHTML is used
leadingWhitespace: ( div.firstChild.nodeType === 3 ),
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
tbody: !div.getElementsByTagName("tbody").length,
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
htmlSerialize: !!div.getElementsByTagName("link").length,
// Get the style information from getAttribute
// (IE uses .cssText instead)
style: /top/.test( a.getAttribute("style") ),
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
hrefNormalized: ( a.getAttribute("href") === "/a" ),
// Make sure that element opacity exists
// (IE uses filter instead)
// Use a regex to work around a WebKit issue. See #5145
opacity: /^0.55/.test( a.style.opacity ),
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
cssFloat: !!a.style.cssFloat,
// Make sure that if no value is specified for a checkbox
// that it defaults to "on".
// (WebKit defaults to "" instead)
checkOn: ( input.value === "on" ),
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
optSelected: opt.selected,
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
getSetAttribute: div.className !== "t",
// Tests for enctype support on a form(#6743)
enctype: !!document.createElement("form").enctype,
// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>",
// Will be defined later
submitBubbles: true,
changeBubbles: true,
focusinBubbles: false,
deleteExpando: true,
noCloneEvent: true,
inlineBlockNeedsLayout: false,
shrinkWrapBlocks: false,
reliableMarginRight: true,
pixelMargin: true
};
// jQuery.boxModel DEPRECATED in 1.3, use jQuery.support.boxModel instead
jQuery.boxModel = support.boxModel = (document.compatMode === "CSS1Compat");
// Make sure checked status is properly cloned
input.checked = true;
support.noCloneChecked = input.cloneNode( true ).checked;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Test to see if it's possible to delete an expando from an element
// Fails in Internet Explorer
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
if ( !div.addEventListener && div.attachEvent && div.fireEvent ) {
div.attachEvent( "onclick", function() {
// Cloning a node shouldn't copy over any
// bound event handlers (IE does this)
support.noCloneEvent = false;
});
div.cloneNode( true ).fireEvent( "onclick" );
}
// Check if a radio maintains its value
// after being appended to the DOM
input = document.createElement("input");
input.value = "t";
input.setAttribute("type", "radio");
support.radioValue = input.value === "t";
input.setAttribute("checked", "checked");
// #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: 1,
change: 1,
focusin: 1
}) {
eventName = "on" + i;
isSupported = ( eventName in div );
if ( !isSupported ) {
div.setAttribute( eventName, "return;" );
isSupported = ( typeof div[ eventName ] === "function" );
}
support[ i + "Bubbles" ] = isSupported;
}
}
fragment.removeChild( div );
// Null elements to avoid leaks in IE
fragment = select = opt = div = input = null;
// Run tests that need a body at doc ready
jQuery(function() {
var container, outer, inner, table, td, offsetSupport,
marginDiv, conMarginTop, style, html, positionTopLeftWidthHeight,
paddingMarginBorderVisibility, paddingMarginBorder,
body = document.getElementsByTagName("body")[0];
if ( !body ) {
// Return for frameset docs that don't have a body
return;
}
conMarginTop = 1;
paddingMarginBorder = "padding:0;margin:0;border:";
positionTopLeftWidthHeight = "position:absolute;top:0;left:0;width:1px;height:1px;";
paddingMarginBorderVisibility = paddingMarginBorder + "0;visibility:hidden;";
style = "style='" + positionTopLeftWidthHeight + paddingMarginBorder + "5px solid #000;";
html = "<div " + style + "display:block;'><div style='" + paddingMarginBorder + "0;display:block;overflow:hidden;'></div></div>" +
"<table " + style + "' cellpadding='0' cellspacing='0'>" +
"<tr><td></td></tr></table>";
container = document.createElement("div");
container.style.cssText = paddingMarginBorderVisibility + "width:0;height:0;position:static;top:0;margin-top:" + conMarginTop + "px";
body.insertBefore( container, body.firstChild );
// Construct the test element
div = document.createElement("div");
container.appendChild( div );
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
// (only IE 8 fails this test)
div.innerHTML = "<table><tr><td style='" + paddingMarginBorder + "0;display:none'></td><td>t</td></tr></table>";
tds = div.getElementsByTagName( "td" );
isSupported = ( tds[ 0 ].offsetHeight === 0 );
tds[ 0 ].style.display = "";
tds[ 1 ].style.display = "none";
// Check if empty table cells still have offsetWidth/Height
// (IE <= 8 fail this test)
support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. For more
// info see bug #3333
// Fails in WebKit before Feb 2011 nightlies
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
if ( window.getComputedStyle ) {
div.innerHTML = "";
marginDiv = document.createElement( "div" );
marginDiv.style.width = "0";
marginDiv.style.marginRight = "0";
div.style.width = "2px";
div.appendChild( marginDiv );
support.reliableMarginRight =
( parseInt( ( window.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0;
}
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.width = div.style.padding = "1px";
div.style.border = 0;
div.style.overflow = "hidden";
div.style.display = "inline";
div.style.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 style='width:5px;'></div>";
support.shrinkWrapBlocks = ( div.offsetWidth !== 3 );
}
div.style.cssText = positionTopLeftWidthHeight + paddingMarginBorderVisibility;
div.innerHTML = html;
outer = div.firstChild;
inner = outer.firstChild;
td = outer.nextSibling.firstChild.firstChild;
offsetSupport = {
doesNotAddBorder: ( inner.offsetTop !== 5 ),
doesAddBorderForTableAndCells: ( td.offsetTop === 5 )
};
inner.style.position = "fixed";
inner.style.top = "20px";
// safari subtracts parent border width here which is 5px
offsetSupport.fixedPosition = ( inner.offsetTop === 20 || inner.offsetTop === 15 );
inner.style.position = inner.style.top = "";
outer.style.overflow = "hidden";
outer.style.position = "relative";
offsetSupport.subtractsBorderForOverflowNotVisible = ( inner.offsetTop === -5 );
offsetSupport.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== conMarginTop );
if ( window.getComputedStyle ) {
div.style.marginTop = "1%";
support.pixelMargin = ( window.getComputedStyle( div, null ) || { marginTop: 0 } ).marginTop !== "1%";
}
if ( typeof container.style.zoom !== "undefined" ) {
container.style.zoom = 1;
}
body.removeChild( container );
marginDiv = div = container = null;
jQuery.extend( support, offsetSupport );
});
return support;
})();
var rbrace = /^(?:\{.*\}|\[.*\])$/,
rmultiDash = /([A-Z])/g;
jQuery.extend({
cache: {},
// Please use with caution
uuid: 0,
// Unique for each copy of jQuery on the page
// Non-digits removed to match rinlinejQuery
expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ),
// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
noData: {
"embed": true,
// Ban all objects except for Flash (which handle expandos)
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
"applet": true
},
hasData: function( elem ) {
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
},
data: function( elem, name, data, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var privateCache, thisCache, ret,
internalKey = jQuery.expando,
getByName = typeof name === "string",
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey,
isEvents = name === "events";
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ( (!id || !cache[id] || (!isEvents && !pvt && !cache[id].data)) && getByName && data === undefined ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
elem[ internalKey ] = id = ++jQuery.uuid;
} else {
id = internalKey;
}
}
if ( !cache[ id ] ) {
cache[ id ] = {};
// Avoids exposing jQuery metadata on plain JS objects when the object
// is serialized using JSON.stringify
if ( !isNode ) {
cache[ id ].toJSON = jQuery.noop;
}
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
if ( pvt ) {
cache[ id ] = jQuery.extend( cache[ id ], name );
} else {
cache[ id ].data = jQuery.extend( cache[ id ].data, name );
}
}
privateCache = thisCache = cache[ id ];
// jQuery data() is stored in a separate object inside the object's internal data
// cache in order to avoid key collisions between internal data and user-defined
// data.
if ( !pvt ) {
if ( !thisCache.data ) {
thisCache.data = {};
}
thisCache = thisCache.data;
}
if ( data !== undefined ) {
thisCache[ jQuery.camelCase( name ) ] = data;
}
// Users should not attempt to inspect the internal events object using jQuery.data,
// it is undocumented and subject to change. But does anyone listen? No.
if ( isEvents && !thisCache[ name ] ) {
return privateCache.events;
}
// Check for both converted-to-camel and non-converted data property names
// If a data property was specified
if ( getByName ) {
// First Try to find as-is property data
ret = thisCache[ name ];
// Test for null|undefined property data
if ( ret == null ) {
// Try to find the camelCased property
ret = thisCache[ jQuery.camelCase( name ) ];
}
} else {
ret = thisCache;
}
return ret;
},
removeData: function( elem, name, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, i, l,
// Reference to internal data cache key
internalKey = jQuery.expando,
isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
// See jQuery.data for more information
id = isNode ? elem[ internalKey ] : internalKey;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
thisCache = pvt ? cache[ id ] : cache[ id ].data;
if ( thisCache ) {
// Support array or space separated string names for data keys
if ( !jQuery.isArray( name ) ) {
// try the string as a key before any manipulation
if ( name in thisCache ) {
name = [ name ];
} else {
// split the camel cased version by spaces unless a key with the spaces exists
name = jQuery.camelCase( name );
if ( name in thisCache ) {
name = [ name ];
} else {
name = name.split( " " );
}
}
}
for ( i = 0, l = name.length; i < l; i++ ) {
delete thisCache[ name[i] ];
}
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) {
return;
}
}
}
// See jQuery.data for more information
if ( !pvt ) {
delete cache[ id ].data;
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject(cache[ id ]) ) {
return;
}
}
// Browsers that fail expando deletion also refuse to delete expandos on
// the window, but it will allow it on all other JS objects; other browsers
// don't care
// Ensure that `cache` is not a window object #10080
if ( jQuery.support.deleteExpando || !cache.setInterval ) {
delete cache[ id ];
} else {
cache[ id ] = null;
}
// We destroyed the cache and need to eliminate the expando on the node to avoid
// false lookups in the cache for entries that no longer exist
if ( isNode ) {
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if ( jQuery.support.deleteExpando ) {
delete elem[ internalKey ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( internalKey );
} else {
elem[ internalKey ] = null;
}
}
},
// For internal use only.
_data: function( elem, name, data ) {
return jQuery.data( elem, name, data, true );
},
// A method for determining if a DOM node can handle the data expando
acceptData: function( elem ) {
if ( elem.nodeName ) {
var match = jQuery.noData[ elem.nodeName.toLowerCase() ];
if ( match ) {
return !(match === true || elem.getAttribute("classid") !== match);
}
}
return true;
}
});
jQuery.fn.extend({
data: function( key, value ) {
var parts, 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-" ) === 0 ) {
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 :
jQuery.isNumeric( 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 ) {
for ( var name in obj ) {
// if the public data object is empty, the private is still empty
if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
continue;
}
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
function handleQueueMarkDefer( elem, type, src ) {
var deferDataKey = type + "defer",
queueDataKey = type + "queue",
markDataKey = type + "mark",
defer = jQuery._data( elem, deferDataKey );
if ( defer &&
( src === "queue" || !jQuery._data(elem, queueDataKey) ) &&
( src === "mark" || !jQuery._data(elem, markDataKey) ) ) {
// Give room for hard-coded callbacks to fire first
// and eventually mark/queue something else on the element
setTimeout( function() {
if ( !jQuery._data( elem, queueDataKey ) &&
!jQuery._data( elem, markDataKey ) ) {
jQuery.removeData( elem, deferDataKey, true );
defer.fire();
}
}, 0 );
}
}
jQuery.extend({
_mark: function( elem, type ) {
if ( elem ) {
type = ( type || "fx" ) + "mark";
jQuery._data( elem, type, (jQuery._data( elem, type ) || 0) + 1 );
}
},
_unmark: function( force, elem, type ) {
if ( force !== true ) {
type = elem;
elem = force;
force = false;
}
if ( elem ) {
type = type || "fx";
var key = type + "mark",
count = force ? 0 : ( (jQuery._data( elem, key ) || 1) - 1 );
if ( count ) {
jQuery._data( elem, key, count );
} else {
jQuery.removeData( elem, key, true );
handleQueueMarkDefer( elem, type, "mark" );
}
}
},
queue: function( elem, type, data ) {
var q;
if ( elem ) {
type = ( type || "fx" ) + "queue";
q = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !q || jQuery.isArray(data) ) {
q = jQuery._data( elem, type, jQuery.makeArray(data) );
} else {
q.push( data );
}
}
return q || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
fn = queue.shift(),
hooks = {};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
jQuery._data( elem, type + ".run", hooks );
fn.call( elem, function() {
jQuery.dequeue( elem, type );
}, hooks );
}
if ( !queue.length ) {
jQuery.removeData( elem, type + "queue " + type + ".run", true );
handleQueueMarkDefer( elem, type, "queue" );
}
}
});
jQuery.fn.extend({
queue: function( type, data ) {
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 );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
delay: function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, object ) {
if ( typeof type !== "string" ) {
object = type;
type = undefined;
}
type = type || "fx";
var defer = jQuery.Deferred(),
elements = this,
i = elements.length,
count = 1,
deferDataKey = type + "defer",
queueDataKey = type + "queue",
markDataKey = type + "mark",
tmp;
function resolve() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
}
while( i-- ) {
if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) ||
( jQuery.data( elements[ i ], queueDataKey, undefined, true ) ||
jQuery.data( elements[ i ], markDataKey, undefined, true ) ) &&
jQuery.data( elements[ i ], deferDataKey, jQuery.Callbacks( "once memory" ), true ) )) {
count++;
tmp.add( resolve );
}
}
resolve();
return defer.promise( object );
}
});
var rclass = /[\n\t\r]/g,
rspace = /\s+/,
rreturn = /\r/g,
rtype = /^(?:button|input)$/i,
rfocusable = /^(?:button|input|object|select|textarea)$/i,
rclickable = /^a(?:rea)?$/i,
rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,
getSetAttribute = jQuery.support.getSetAttribute,
nodeHook, boolHook, fixSpecified;
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, 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( rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 ) {
if ( !elem.className && classNames.length === 1 ) {
elem.className = value;
} else {
setClass = " " + elem.className + " ";
for ( c = 0, cl = classNames.length; c < cl; c++ ) {
if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) {
setClass += classNames[ c ] + " ";
}
}
elem.className = jQuery.trim( setClass );
}
}
}
}
return this;
},
removeClass: function( value ) {
var classNames, i, l, elem, className, c, cl;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call(this, j, this.className) );
});
}
if ( (value && typeof value === "string") || value === undefined ) {
classNames = ( value || "" ).split( rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 && elem.className ) {
if ( value ) {
className = (" " + elem.className + " ").replace( rclass, " " );
for ( c = 0, cl = classNames.length; c < cl; c++ ) {
className = className.replace(" " + classNames[ c ] + " ", " ");
}
elem.className = jQuery.trim( className );
} else {
elem.className = "";
}
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value,
isBool = typeof stateVal === "boolean";
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
state = stateVal,
classNames = value.split( rspace );
while ( (className = classNames[ i++ ]) ) {
// check each className given, space seperated list
state = isBool ? state : !self.hasClass( className );
self[ state ? "addClass" : "removeClass" ]( className );
}
} else if ( type === "undefined" || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery._data( this, "__className__", this.className );
}
// toggle whole className
this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) {
return true;
}
}
return false;
},
val: function( value ) {
var hooks, ret, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.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 self = jQuery(this), val;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, self.val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map(val, function ( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.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, i, max, option,
index = elem.selectedIndex,
values = [],
options = elem.options,
one = elem.type === "select-one";
// Nothing was selected
if ( index < 0 ) {
return null;
}
// Loop through all the selected options
i = one ? index : 0;
max = one ? index + 1 : options.length;
for ( ; i < max; i++ ) {
option = options[ i ];
// Don't return options that are disabled or in a disabled optgroup
if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) &&
(!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
// Fixes Bug #2551 -- select.val() broken in IE after form.reset()
if ( one && !values.length && options.length ) {
return jQuery( options[ index ] ).val();
}
return values;
},
set: function( elem, value ) {
var values = jQuery.makeArray( value );
jQuery(elem).find("option").each(function() {
this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
});
if ( !values.length ) {
elem.selectedIndex = -1;
}
return values;
}
}
},
attrFn: {
val: true,
css: true,
html: true,
text: true,
data: true,
width: true,
height: true,
offset: true
},
attr: function( elem, name, value, pass ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
if ( pass && name in jQuery.attrFn ) {
return jQuery( elem )[ name ]( value );
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === "undefined" ) {
return jQuery.prop( elem, name, value );
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( notxml ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
return;
} else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, "" + value );
return value;
}
} else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = elem.getAttribute( name );
// Non-existent attributes return null, we normalize to undefined
return ret === null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var propName, attrNames, name, l, isBool,
i = 0;
if ( value && elem.nodeType === 1 ) {
attrNames = value.toLowerCase().split( rspace );
l = attrNames.length;
for ( ; i < l; i++ ) {
name = attrNames[ i ];
if ( name ) {
propName = jQuery.propFix[ name ] || name;
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;
}
}
}
});
// Add the tabIndex propHook to attrHooks for back-compat (different case is intentional)
jQuery.attrHooks.tabindex = jQuery.propHooks.tabIndex;
// Hook for boolean attributes
boolHook = {
get: function( elem, name ) {
// Align boolean attributes with corresponding properties
// Fall back to attribute presence where some booleans are not supported
var attrNode,
property = jQuery.prop( elem, name );
return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ?
name.toLowerCase() :
undefined;
},
set: function( elem, value, name ) {
var propName;
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else {
// value is true since we know at this point it's type boolean and not false
// Set boolean attributes to the same name and set the DOM property
propName = jQuery.propFix[ name ] || name;
if ( propName in elem ) {
// Only set the IDL specifically if it already exists on the element
elem[ propName ] = true;
}
elem.setAttribute( name, name.toLowerCase() );
}
return name;
}
};
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {
fixSpecified = {
name: true,
id: true,
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.nodeValue !== "" : ret.specified ) ?
ret.nodeValue :
undefined;
},
set: function( elem, value, name ) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode( name );
if ( !ret ) {
ret = document.createAttribute( name );
elem.setAttributeNode( ret );
}
return ( ret.nodeValue = value + "" );
}
};
// Apply the nodeHook to tabindex
jQuery.attrHooks.tabindex.set = nodeHook.set;
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each([ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
});
});
// Set contenteditable to false on removals(#10429)
// Setting to empty string throws an error as an invalid value
jQuery.attrHooks.contenteditable = {
get: nodeHook.get,
set: function( elem, value, name ) {
if ( value === "" ) {
value = "false";
}
nodeHook.set( elem, value, name );
}
};
}
// Some attributes require a special call on IE
if ( !jQuery.support.hrefNormalized ) {
jQuery.each([ "href", "src", "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
get: function( elem ) {
var ret = elem.getAttribute( name, 2 );
return ret === null ? undefined : ret;
}
});
});
}
if ( !jQuery.support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Normalize to lowercase since IE uppercases css property names
return elem.style.cssText.toLowerCase() || undefined;
},
set: function( elem, value ) {
return ( elem.style.cssText = "" + value );
}
};
}
// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !jQuery.support.optSelected ) {
jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
return null;
}
});
}
// IE6/7 call enctype encoding
if ( !jQuery.support.enctype ) {
jQuery.propFix.enctype = "encoding";
}
// Radios and checkboxes getter/setter
if ( !jQuery.support.checkOn ) {
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
get: function( elem ) {
// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
}
};
});
}
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
});
});
var rformElems = /^(?:textarea|input|select)$/i,
rtypenamespace = /^([^\.]*)?(?:\.(.+))?$/,
rhoverHack = /(?:^|\s)hover(\.\S+)?\b/,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rquickIs = /^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,
quickParse = function( selector ) {
var quick = rquickIs.exec( selector );
if ( quick ) {
// 0 1 2 3
// [ _, tag, id, class ]
quick[1] = ( quick[1] || "" ).toLowerCase();
quick[3] = quick[3] && new RegExp( "(?:^|\\s)" + quick[3] + "(?:\\s|$)" );
}
return quick;
},
quickIs = function( elem, m ) {
var attrs = elem.attributes || {};
return (
(!m[1] || elem.nodeName.toLowerCase() === m[1]) &&
(!m[2] || (attrs.id || {}).value === m[2]) &&
(!m[3] || m[3].test( (attrs[ "class" ] || {}).value ))
);
},
hoverHack = function( events ) {
return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" );
};
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
add: function( elem, types, handler, data, selector ) {
var elemData, eventHandle, events,
t, tns, type, namespaces, handleObj,
handleObjIn, quick, handlers, special;
// Don't attach events to noData or text/comment nodes (allow plain objects tho)
if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
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,
quick: selector && quickParse( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
handlers = events[ type ];
if ( !handlers ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener/attachEvent if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
global: {},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var elemData = jQuery.hasData( elem ) && jQuery._data( elem ),
t, tns, type, origType, namespaces, origCount,
j, events, special, handle, eventType, handleObj;
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = jQuery.trim( hoverHack( types || "" ) ).split(" ");
for ( t = 0; t < types.length; t++ ) {
tns = rtypenamespace.exec( types[t] ) || [];
type = origType = tns[1];
namespaces = tns[2];
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector? special.delegateType : special.bindType ) || type;
eventType = events[ type ] || [];
origCount = eventType.length;
namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.)?") + "(\\.|$)") : null;
// Remove matching events
for ( j = 0; j < eventType.length; j++ ) {
handleObj = eventType[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !namespaces || namespaces.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
eventType.splice( j--, 1 );
if ( handleObj.selector ) {
eventType.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( eventType.length === 0 && origCount !== eventType.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
handle = elemData.handle;
if ( handle ) {
handle.elem = null;
}
// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
jQuery.removeData( elem, [ "events", "handle" ], true );
}
},
// Events that are safe to short-circuit if no handlers are attached.
// Native DOM events should not be added, they may have inline handlers.
customEvent: {
"getData": true,
"setData": true,
"changeData": true
},
trigger: function( event, data, elem, onlyHandlers ) {
// Don't do events on text and comment nodes
if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) {
return;
}
// Event object or event type
var type = event.type || event,
namespaces = [],
cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType;
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf( "!" ) >= 0 ) {
// Exclusive events trigger only for the exact event (no namespaces)
type = type.slice(0, -1);
exclusive = true;
}
if ( type.indexOf( "." ) >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) {
// No jQuery handlers for this event type, and it can't have inline handlers
return;
}
// Caller can pass in an Event, Object, or just an event type string
event = typeof event === "object" ?
// jQuery.Event object
event[ jQuery.expando ] ? event :
// Object literal
new jQuery.Event( type, event ) :
// Just the event type (string)
new jQuery.Event( type );
event.type = type;
event.isTrigger = true;
event.exclusive = exclusive;
event.namespace = namespaces.join( "." );
event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)") : null;
ontype = type.indexOf( ":" ) < 0 ? "on" + type : "";
// Handle a global trigger
if ( !elem ) {
// TODO: Stop taunting the data cache; remove global events and always attach to document
cache = jQuery.cache;
for ( i in cache ) {
if ( cache[ i ].events && cache[ i ].events[ type ] ) {
jQuery.event.trigger( event, data, cache[ i ].handle.elem, true );
}
}
return;
}
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data != null ? jQuery.makeArray( data ) : [];
data.unshift( event );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
eventPath = [[ elem, special.bindType || type ]];
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode;
old = null;
for ( ; cur; cur = cur.parentNode ) {
eventPath.push([ cur, bubbleType ]);
old = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( old && old === elem.ownerDocument ) {
eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]);
}
}
// Fire handlers on the event path
for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) {
cur = eventPath[i][0];
event.type = eventPath[i][1];
handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Note that this is a bare JS function and not a jQuery handler
handle = ontype && cur[ ontype ];
if ( handle && jQuery.acceptData( cur ) && handle.apply( cur, data ) === false ) {
event.preventDefault();
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) &&
!(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction() check here because IE6/7 fails that test.
// Don't do default actions on window, that's where global variables be (#6170)
// IE<9 dies on focus/blur to hidden element (#1486)
if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
old = elem[ ontype ];
if ( old ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
elem[ type ]();
jQuery.event.triggered = undefined;
if ( old ) {
elem[ ontype ] = old;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event || window.event );
var handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []),
delegateCount = handlers.delegateCount,
args = [].slice.call( arguments, 0 ),
run_all = !event.exclusive && !event.namespace,
special = jQuery.event.special[ event.type ] || {},
handlerQueue = [],
i, j, cur, jqcur, ret, selMatch, matched, matches, handleObj, sel, related;
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// 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") ) {
// Pregenerate a single jQuery object for reuse with .is()
jqcur = jQuery(this);
jqcur.context = this.ownerDocument || this;
for ( cur = event.target; cur != this; cur = cur.parentNode || this ) {
// Don't process events on disabled elements (#6911, #8165)
if ( cur.disabled !== true ) {
selMatch = {};
matches = [];
jqcur[0] = cur;
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
sel = handleObj.selector;
if ( selMatch[ sel ] === undefined ) {
selMatch[ sel ] = (
handleObj.quick ? quickIs( cur, handleObj.quick ) : jqcur.is( sel )
);
}
if ( selMatch[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, matches: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( handlers.length > delegateCount ) {
handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) });
}
// Run delegates first; they may want to stop propagation beneath us
for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) {
matched = handlerQueue[ i ];
event.currentTarget = matched.elem;
for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) {
handleObj = matched.matches[ j ];
// Triggered event must either 1) be non-exclusive and have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) {
event.data = handleObj.data;
event.handleObj = handleObj;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
event.result = ret;
if ( ret === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// 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; add metaKey if it's not there (#3368, IE6/7/8)
if ( event.metaKey === undefined ) {
event.metaKey = event.ctrlKey;
}
return fixHook.filter? fixHook.filter( event, originalEvent ) : event;
},
special: {
ready: {
// Make sure the ready event is setup
setup: jQuery.bindReady
},
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
delegateType: "focusin"
},
blur: {
delegateType: "focusout"
},
beforeunload: {
setup: function( data, namespaces, eventHandle ) {
// We only want to do this special case on windows
if ( jQuery.isWindow( this ) ) {
this.onbeforeunload = eventHandle;
}
},
teardown: function( namespaces, eventHandle ) {
if ( this.onbeforeunload === eventHandle ) {
this.onbeforeunload = null;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{ type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
// Some plugins are using, but it's undocumented/deprecated and will be removed.
// The 1.7 special event interface should provide all the hooks needed now.
jQuery.event.handle = jQuery.event.dispatch;
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
if ( elem.detachEvent ) {
elem.detachEvent( "on" + type, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false ||
src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
function returnFalse() {
return false;
}
function returnTrue() {
return true;
}
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
preventDefault: function() {
this.isDefaultPrevented = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if preventDefault exists run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// otherwise set the returnValue property of the original event to false (IE)
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
this.isPropagationStopped = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if stopPropagation exists run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// otherwise set the cancelBubble property of the original event to true (IE)
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
},
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse
};
// Create mouseenter/leave events using mouseover/out and event-time checks
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var target = this,
related = event.relatedTarget,
handleObj = event.handleObj,
selector = handleObj.selector,
ret;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// IE submit delegation
if ( !jQuery.support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Lazy-add a submit handler when a descendant form may potentially be submitted
jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
// Node name check avoids a VML-related crash in IE (#9807)
var elem = e.target,
form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
if ( form && !form._submit_attached ) {
jQuery.event.add( form, "submit._submit", function( event ) {
event._submit_bubble = true;
});
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;
jQuery.event.simulate( "change", this, event, true );
}
});
}
return false;
}
// Delegated event; lazy-add a change handler on descendant inputs
jQuery.event.add( this, "beforeactivate._change", function( e ) {
var elem = e.target;
if ( rformElems.test( elem.nodeName ) && !elem._change_attached ) {
jQuery.event.add( elem, "change._change", function( event ) {
if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
jQuery.event.simulate( "change", this.parentNode, event, true );
}
});
elem._change_attached = true;
}
});
},
handle: function( event ) {
var elem = event.target;
// Swallow native change events from checkbox/radio, we already triggered them above
if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
return event.handleObj.handler.apply( this, arguments );
}
},
teardown: function() {
jQuery.event.remove( this, "._change" );
return rformElems.test( this.nodeName );
}
};
}
// Create "bubbling" focus and blur events
if ( !jQuery.support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler while someone wants focusin/focusout
var attaches = 0,
handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
if ( attaches++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
if ( --attaches === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var origFn, type;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) { // && 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 ) {
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
var 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 ( var type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
live: function( types, data, fn ) {
jQuery( this.context ).on( types, this.selector, data, fn );
return this;
},
die: function( types, fn ) {
jQuery( this.context ).off( types, this.selector || "**", fn );
return this;
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length == 1? this.off( selector, "**" ) : this.off( types, selector, fn );
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
if ( this[0] ) {
return jQuery.event.trigger( type, data, this[0], true );
}
},
toggle: function( fn ) {
// Save reference to arguments for access in closure
var args = arguments,
guid = fn.guid || jQuery.guid++,
i = 0,
toggler = function( event ) {
// Figure out which function to execute
var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i;
jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 );
// Make sure that clicks stop
event.preventDefault();
// and execute the function
return args[ lastToggle ].apply( this, arguments ) || false;
};
// link all the functions, so any of them can unbind this click handler
toggler.guid = guid;
while ( i < args.length ) {
args[ i++ ].guid = guid;
}
return this.click( toggler );
},
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
}
});
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
if ( jQuery.attrFn ) {
jQuery.attrFn[ name ] = true;
}
if ( rkeyEvent.test( name ) ) {
jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks;
}
if ( rmouseEvent.test( name ) ) {
jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks;
}
});
/*!
* Sizzle CSS Selector Engine
* Copyright 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,
expando = "sizcache" + (Math.random() + '').replace('.', ''),
done = 0,
toString = Object.prototype.toString,
hasDuplicate = false,
baseHasDuplicate = true,
rBackslash = /\\/g,
rReturn = /\r\n/g,
rNonWord = /\W/;
// Here we check if the JavaScript engine is using some sort of
// optimization where it does not always call our comparision
// function. If that is the case, discard the hasDuplicate value.
// Thus far that includes Google Chrome.
[0, 0].sort(function() {
baseHasDuplicate = false;
return 0;
});
var Sizzle = function( selector, context, results, seed ) {
results = results || [];
context = context || document;
var origContext = context;
if ( context.nodeType !== 1 && context.nodeType !== 9 ) {
return [];
}
if ( !selector || typeof selector !== "string" ) {
return results;
}
var m, set, checkSet, extra, ret, cur, pop, i,
prune = true,
contextXML = Sizzle.isXML( context ),
parts = [],
soFar = selector;
// Reset the position of the chunker regexp (start from head)
do {
chunker.exec( "" );
m = chunker.exec( soFar );
if ( m ) {
soFar = m[3];
parts.push( m[1] );
if ( m[2] ) {
extra = m[3];
break;
}
}
} while ( m );
if ( parts.length > 1 && origPOS.exec( selector ) ) {
if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
set = posProcess( parts[0] + parts[1], context, seed );
} else {
set = Expr.relative[ parts[0] ] ?
[ context ] :
Sizzle( parts.shift(), context );
while ( parts.length ) {
selector = parts.shift();
if ( Expr.relative[ selector ] ) {
selector += parts.shift();
}
set = posProcess( selector, set, seed );
}
}
} else {
// Take a shortcut and set the context if the root selector is an ID
// (but not if it'll be faster if the inner selector is an ID)
if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML &&
Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) {
ret = Sizzle.find( parts.shift(), context, contextXML );
context = ret.expr ?
Sizzle.filter( ret.expr, ret.set )[0] :
ret.set[0];
}
if ( context ) {
ret = seed ?
{ expr: parts.pop(), set: makeArray(seed) } :
Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML );
set = ret.expr ?
Sizzle.filter( ret.expr, ret.set ) :
ret.set;
if ( parts.length > 0 ) {
checkSet = makeArray( set );
} else {
prune = false;
}
while ( parts.length ) {
cur = parts.pop();
pop = cur;
if ( !Expr.relative[ cur ] ) {
cur = "";
} else {
pop = parts.pop();
}
if ( pop == null ) {
pop = context;
}
Expr.relative[ cur ]( checkSet, pop, contextXML );
}
} else {
checkSet = parts = [];
}
}
if ( !checkSet ) {
checkSet = set;
}
if ( !checkSet ) {
Sizzle.error( cur || selector );
}
if ( toString.call(checkSet) === "[object Array]" ) {
if ( !prune ) {
results.push.apply( results, checkSet );
} else if ( context && context.nodeType === 1 ) {
for ( i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) {
results.push( set[i] );
}
}
} else {
for ( i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && checkSet[i].nodeType === 1 ) {
results.push( set[i] );
}
}
}
} else {
makeArray( checkSet, results );
}
if ( extra ) {
Sizzle( extra, origContext, results, seed );
Sizzle.uniqueSort( results );
}
return results;
};
Sizzle.uniqueSort = function( results ) {
if ( sortOrder ) {
hasDuplicate = baseHasDuplicate;
results.sort( sortOrder );
if ( hasDuplicate ) {
for ( var i = 1; i < results.length; i++ ) {
if ( results[i] === results[ i - 1 ] ) {
results.splice( i--, 1 );
}
}
}
}
return results;
};
Sizzle.matches = function( expr, set ) {
return Sizzle( expr, null, null, set );
};
Sizzle.matchesSelector = function( node, expr ) {
return Sizzle( expr, null, null, [node] ).length > 0;
};
Sizzle.find = function( expr, context, isXML ) {
var set, i, len, match, type, left;
if ( !expr ) {
return [];
}
for ( i = 0, len = Expr.order.length; i < len; i++ ) {
type = Expr.order[i];
if ( (match = Expr.leftMatch[ type ].exec( expr )) ) {
left = match[1];
match.splice( 1, 1 );
if ( left.substr( left.length - 1 ) !== "\\" ) {
match[1] = (match[1] || "").replace( rBackslash, "" );
set = Expr.find[ type ]( match, context, isXML );
if ( set != null ) {
expr = expr.replace( Expr.match[ type ], "" );
break;
}
}
}
}
if ( !set ) {
set = typeof context.getElementsByTagName !== "undefined" ?
context.getElementsByTagName( "*" ) :
[];
}
return { set: set, expr: expr };
};
Sizzle.filter = function( expr, set, inplace, not ) {
var match, anyFound,
type, found, item, filter, left,
i, pass,
old = expr,
result = [],
curLoop = set,
isXMLFilter = set && set[0] && Sizzle.isXML( set[0] );
while ( expr && set.length ) {
for ( type in Expr.filter ) {
if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) {
filter = Expr.filter[ type ];
left = match[1];
anyFound = false;
match.splice(1,1);
if ( left.substr( left.length - 1 ) === "\\" ) {
continue;
}
if ( curLoop === result ) {
result = [];
}
if ( Expr.preFilter[ type ] ) {
match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );
if ( !match ) {
anyFound = found = true;
} else if ( match === true ) {
continue;
}
}
if ( match ) {
for ( i = 0; (item = curLoop[i]) != null; i++ ) {
if ( item ) {
found = filter( item, match, i, curLoop );
pass = not ^ found;
if ( inplace && found != null ) {
if ( pass ) {
anyFound = true;
} else {
curLoop[i] = false;
}
} else if ( pass ) {
result.push( item );
anyFound = true;
}
}
}
}
if ( found !== undefined ) {
if ( !inplace ) {
curLoop = result;
}
expr = expr.replace( Expr.match[ type ], "" );
if ( !anyFound ) {
return [];
}
break;
}
}
}
// Improper expression
if ( expr === old ) {
if ( anyFound == null ) {
Sizzle.error( expr );
} else {
break;
}
}
old = expr;
}
return curLoop;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
/**
* Utility function for retreiving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
var getText = Sizzle.getText = function( elem ) {
var i, node,
nodeType = elem.nodeType,
ret = "";
if ( nodeType ) {
if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent || innerText for elements
if ( typeof elem.textContent === 'string' ) {
return elem.textContent;
} else if ( typeof elem.innerText === 'string' ) {
// Replace IE's carriage returns
return elem.innerText.replace( rReturn, '' );
} else {
// Traverse it's children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
} else {
// If no nodeType, this is expected to be an array
for ( i = 0; (node = elem[i]); i++ ) {
// Do not traverse comment nodes
if ( node.nodeType !== 8 ) {
ret += getText( node );
}
}
}
return ret;
};
var Expr = Sizzle.selectors = {
order: [ "ID", "NAME", "TAG" ],
match: {
ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,
ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,
TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,
CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,
POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,
PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/
},
leftMatch: {},
attrMap: {
"class": "className",
"for": "htmlFor"
},
attrHandle: {
href: function( elem ) {
return elem.getAttribute( "href" );
},
type: function( elem ) {
return elem.getAttribute( "type" );
}
},
relative: {
"+": function(checkSet, part){
var isPartStr = typeof part === "string",
isTag = isPartStr && !rNonWord.test( part ),
isPartStrNotTag = isPartStr && !isTag;
if ( isTag ) {
part = part.toLowerCase();
}
for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {
if ( (elem = checkSet[i]) ) {
while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}
checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ?
elem || false :
elem === part;
}
}
if ( isPartStrNotTag ) {
Sizzle.filter( part, checkSet, true );
}
},
">": function( checkSet, part ) {
var elem,
isPartStr = typeof part === "string",
i = 0,
l = checkSet.length;
if ( isPartStr && !rNonWord.test( part ) ) {
part = part.toLowerCase();
for ( ; i < l; i++ ) {
elem = checkSet[i];
if ( elem ) {
var parent = elem.parentNode;
checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false;
}
}
} else {
for ( ; i < l; i++ ) {
elem = checkSet[i];
if ( elem ) {
checkSet[i] = isPartStr ?
elem.parentNode :
elem.parentNode === part;
}
}
if ( isPartStr ) {
Sizzle.filter( part, checkSet, true );
}
}
},
"": function(checkSet, part, isXML){
var nodeCheck,
doneName = done++,
checkFn = dirCheck;
if ( typeof part === "string" && !rNonWord.test( part ) ) {
part = part.toLowerCase();
nodeCheck = part;
checkFn = dirNodeCheck;
}
checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML );
},
"~": function( checkSet, part, isXML ) {
var nodeCheck,
doneName = done++,
checkFn = dirCheck;
if ( typeof part === "string" && !rNonWord.test( part ) ) {
part = part.toLowerCase();
nodeCheck = part;
checkFn = dirNodeCheck;
}
checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML );
}
},
find: {
ID: function( match, context, isXML ) {
if ( typeof context.getElementById !== "undefined" && !isXML ) {
var m = context.getElementById(match[1]);
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
},
NAME: function( match, context ) {
if ( typeof context.getElementsByName !== "undefined" ) {
var ret = [],
results = context.getElementsByName( match[1] );
for ( var i = 0, l = results.length; i < l; i++ ) {
if ( results[i].getAttribute("name") === match[1] ) {
ret.push( results[i] );
}
}
return ret.length === 0 ? null : ret;
}
},
TAG: function( match, context ) {
if ( typeof context.getElementsByTagName !== "undefined" ) {
return context.getElementsByTagName( match[1] );
}
}
},
preFilter: {
CLASS: function( match, curLoop, inplace, result, not, isXML ) {
match = " " + match[1].replace( rBackslash, "" ) + " ";
if ( isXML ) {
return match;
}
for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
if ( elem ) {
if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) {
if ( !inplace ) {
result.push( elem );
}
} else if ( inplace ) {
curLoop[i] = false;
}
}
}
return false;
},
ID: function( match ) {
return match[1].replace( rBackslash, "" );
},
TAG: function( match, curLoop ) {
return match[1].replace( rBackslash, "" ).toLowerCase();
},
CHILD: function( match ) {
if ( match[1] === "nth" ) {
if ( !match[2] ) {
Sizzle.error( match[0] );
}
match[2] = match[2].replace(/^\+|\s*/g, '');
// parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec(
match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" ||
!/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);
// calculate the numbers (first)n+(last) including if they are negative
match[2] = (test[1] + (test[2] || 1)) - 0;
match[3] = test[3] - 0;
}
else if ( match[2] ) {
Sizzle.error( match[0] );
}
// TODO: Move to normal caching system
match[0] = done++;
return match;
},
ATTR: function( match, curLoop, inplace, result, not, isXML ) {
var name = match[1] = match[1].replace( rBackslash, "" );
if ( !isXML && Expr.attrMap[name] ) {
match[1] = Expr.attrMap[name];
}
// Handle if an un-quoted value was used
match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" );
if ( match[2] === "~=" ) {
match[4] = " " + match[4] + " ";
}
return match;
},
PSEUDO: function( match, curLoop, inplace, result, not ) {
if ( match[1] === "not" ) {
// If we're dealing with a complex expression, or a simple one
if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) {
match[3] = Sizzle(match[3], null, null, curLoop);
} else {
var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);
if ( !inplace ) {
result.push.apply( result, ret );
}
return false;
}
} else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {
return true;
}
return match;
},
POS: function( match ) {
match.unshift( true );
return match;
}
},
filters: {
enabled: function( elem ) {
return elem.disabled === false && elem.type !== "hidden";
},
disabled: function( elem ) {
return elem.disabled === true;
},
checked: function( elem ) {
return elem.checked === true;
},
selected: function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
parent: function( elem ) {
return !!elem.firstChild;
},
empty: function( elem ) {
return !elem.firstChild;
},
has: function( elem, i, match ) {
return !!Sizzle( match[3], elem ).length;
},
header: function( elem ) {
return (/h\d/i).test( elem.nodeName );
},
text: function( elem ) {
var attr = elem.getAttribute( "type" ), type = elem.type;
// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
// use getAttribute instead to test this case
return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null );
},
radio: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type;
},
checkbox: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type;
},
file: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "file" === elem.type;
},
password: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "password" === elem.type;
},
submit: function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && "submit" === elem.type;
},
image: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "image" === elem.type;
},
reset: function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && "reset" === elem.type;
},
button: function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && "button" === elem.type || name === "button";
},
input: function( elem ) {
return (/input|select|textarea|button/i).test( elem.nodeName );
},
focus: function( elem ) {
return elem === elem.ownerDocument.activeElement;
}
},
setFilters: {
first: function( elem, i ) {
return i === 0;
},
last: function( elem, i, match, array ) {
return i === array.length - 1;
},
even: function( elem, i ) {
return i % 2 === 0;
},
odd: function( elem, i ) {
return i % 2 === 1;
},
lt: function( elem, i, match ) {
return i < match[3] - 0;
},
gt: function( elem, i, match ) {
return i > match[3] - 0;
},
nth: function( elem, i, match ) {
return match[3] - 0 === i;
},
eq: function( elem, i, match ) {
return match[3] - 0 === i;
}
},
filter: {
PSEUDO: function( elem, match, i, array ) {
var name = match[1],
filter = Expr.filters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
} else if ( name === "contains" ) {
return (elem.textContent || elem.innerText || getText([ elem ]) || "").indexOf(match[3]) >= 0;
} else if ( name === "not" ) {
var not = match[3];
for ( var j = 0, l = not.length; j < l; j++ ) {
if ( not[j] === elem ) {
return false;
}
}
return true;
} else {
Sizzle.error( name );
}
},
CHILD: function( elem, match ) {
var first, last,
doneName, parent, cache,
count, diff,
type = match[1],
node = elem;
switch ( type ) {
case "only":
case "first":
while ( (node = node.previousSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
if ( type === "first" ) {
return true;
}
node = elem;
/* falls through */
case "last":
while ( (node = node.nextSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
return true;
case "nth":
first = match[2];
last = match[3];
if ( first === 1 && last === 0 ) {
return true;
}
doneName = match[0];
parent = elem.parentNode;
if ( parent && (parent[ expando ] !== doneName || !elem.nodeIndex) ) {
count = 0;
for ( node = parent.firstChild; node; node = node.nextSibling ) {
if ( node.nodeType === 1 ) {
node.nodeIndex = ++count;
}
}
parent[ expando ] = doneName;
}
diff = elem.nodeIndex - last;
if ( first === 0 ) {
return diff === 0;
} else {
return ( diff % first === 0 && diff / first >= 0 );
}
}
},
ID: function( elem, match ) {
return elem.nodeType === 1 && elem.getAttribute("id") === match;
},
TAG: function( elem, match ) {
return (match === "*" && elem.nodeType === 1) || !!elem.nodeName && elem.nodeName.toLowerCase() === match;
},
CLASS: function( elem, match ) {
return (" " + (elem.className || elem.getAttribute("class")) + " ")
.indexOf( match ) > -1;
},
ATTR: function( elem, match ) {
var name = match[1],
result = Sizzle.attr ?
Sizzle.attr( elem, name ) :
Expr.attrHandle[ name ] ?
Expr.attrHandle[ name ]( elem ) :
elem[ name ] != null ?
elem[ name ] :
elem.getAttribute( name ),
value = result + "",
type = match[2],
check = match[4];
return result == null ?
type === "!=" :
!type && Sizzle.attr ?
result != null :
type === "=" ?
value === check :
type === "*=" ?
value.indexOf(check) >= 0 :
type === "~=" ?
(" " + value + " ").indexOf(check) >= 0 :
!check ?
value && result !== false :
type === "!=" ?
value !== check :
type === "^=" ?
value.indexOf(check) === 0 :
type === "$=" ?
value.substr(value.length - check.length) === check :
type === "|=" ?
value === check || value.substr(0, check.length + 1) === check + "-" :
false;
},
POS: function( elem, match, i, array ) {
var name = match[2],
filter = Expr.setFilters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
}
}
}
};
var origPOS = Expr.match.POS,
fescape = function(all, num){
return "\\" + (num - 0 + 1);
};
for ( var type in Expr.match ) {
Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) );
Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) );
}
// Expose origPOS
// "global" as in regardless of relation to brackets/parens
Expr.match.globalPOS = origPOS;
var makeArray = function( array, results ) {
array = Array.prototype.slice.call( array, 0 );
if ( results ) {
results.push.apply( results, array );
return results;
}
return array;
};
// Perform a simple check to determine if the browser is capable of
// converting a NodeList to an array using builtin methods.
// Also verifies that the returned array holds DOM nodes
// (which is not the case in the Blackberry browser)
try {
Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType;
// Provide a fallback method if it does not work
} catch( e ) {
makeArray = function( array, results ) {
var i = 0,
ret = results || [];
if ( toString.call(array) === "[object Array]" ) {
Array.prototype.push.apply( ret, array );
} else {
if ( typeof array.length === "number" ) {
for ( var l = array.length; i < l; i++ ) {
ret.push( array[i] );
}
} else {
for ( ; array[i]; i++ ) {
ret.push( array[i] );
}
}
}
return ret;
};
}
var sortOrder, siblingCheck;
if ( document.documentElement.compareDocumentPosition ) {
sortOrder = function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
return 0;
}
if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) {
return a.compareDocumentPosition ? -1 : 1;
}
return a.compareDocumentPosition(b) & 4 ? -1 : 1;
};
} else {
sortOrder = function( a, b ) {
// The nodes are identical, we can exit early
if ( a === b ) {
hasDuplicate = true;
return 0;
// Fallback to using sourceIndex (in IE) if it's available on both nodes
} else if ( a.sourceIndex && b.sourceIndex ) {
return a.sourceIndex - b.sourceIndex;
}
var al, bl,
ap = [],
bp = [],
aup = a.parentNode,
bup = b.parentNode,
cur = aup;
// If the nodes are siblings (or identical) we can do a quick check
if ( aup === bup ) {
return siblingCheck( a, b );
// If no parents were found then the nodes are disconnected
} else if ( !aup ) {
return -1;
} else if ( !bup ) {
return 1;
}
// Otherwise they're somewhere else in the tree so we need
// to build up a full list of the parentNodes for comparison
while ( cur ) {
ap.unshift( cur );
cur = cur.parentNode;
}
cur = bup;
while ( cur ) {
bp.unshift( cur );
cur = cur.parentNode;
}
al = ap.length;
bl = bp.length;
// Start walking down the tree looking for a discrepancy
for ( var i = 0; i < al && i < bl; i++ ) {
if ( ap[i] !== bp[i] ) {
return siblingCheck( ap[i], bp[i] );
}
}
// We ended someplace up the tree so do a sibling check
return i === al ?
siblingCheck( a, bp[i], -1 ) :
siblingCheck( ap[i], b, 1 );
};
siblingCheck = function( a, b, ret ) {
if ( a === b ) {
return ret;
}
var cur = a.nextSibling;
while ( cur ) {
if ( cur === b ) {
return -1;
}
cur = cur.nextSibling;
}
return 1;
};
}
// Check to see if the browser returns elements by name when
// querying by getElementById (and provide a workaround)
(function(){
// We're going to inject a fake input element with a specified name
var form = document.createElement("div"),
id = "script" + (new Date()).getTime(),
root = document.documentElement;
form.innerHTML = "<a name='" + id + "'/>";
// Inject it into the root element, check its status, and remove it quickly
root.insertBefore( form, root.firstChild );
// The workaround has to do additional checks after a getElementById
// Which slows things down for other browsers (hence the branching)
if ( document.getElementById( id ) ) {
Expr.find.ID = function( match, context, isXML ) {
if ( typeof context.getElementById !== "undefined" && !isXML ) {
var m = context.getElementById(match[1]);
return m ?
m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ?
[m] :
undefined :
[];
}
};
Expr.filter.ID = function( elem, match ) {
var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
return elem.nodeType === 1 && node && node.nodeValue === match;
};
}
root.removeChild( form );
// release memory in IE
root = form = null;
})();
(function(){
// Check to see if the browser returns only elements
// when doing getElementsByTagName("*")
// Create a fake element
var div = document.createElement("div");
div.appendChild( document.createComment("") );
// Make sure no comments are found
if ( div.getElementsByTagName("*").length > 0 ) {
Expr.find.TAG = function( match, context ) {
var results = context.getElementsByTagName( match[1] );
// Filter out possible comments
if ( match[1] === "*" ) {
var tmp = [];
for ( var i = 0; results[i]; i++ ) {
if ( results[i].nodeType === 1 ) {
tmp.push( results[i] );
}
}
results = tmp;
}
return results;
};
}
// Check to see if an attribute returns normalized href attributes
div.innerHTML = "<a href='#'></a>";
if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" &&
div.firstChild.getAttribute("href") !== "#" ) {
Expr.attrHandle.href = function( elem ) {
return elem.getAttribute( "href", 2 );
};
}
// release memory in IE
div = null;
})();
if ( document.querySelectorAll ) {
(function(){
var oldSizzle = Sizzle,
div = document.createElement("div"),
id = "__sizzle__";
div.innerHTML = "<p class='TEST'></p>";
// Safari can't handle uppercase or unicode characters when
// in quirks mode.
if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
return;
}
Sizzle = function( query, context, extra, seed ) {
context = context || document;
// Only use querySelectorAll on non-XML documents
// (ID selectors don't work in non-HTML documents)
if ( !seed && !Sizzle.isXML(context) ) {
// See if we find a selector to speed up
var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query );
if ( match && (context.nodeType === 1 || context.nodeType === 9) ) {
// Speed-up: Sizzle("TAG")
if ( match[1] ) {
return makeArray( context.getElementsByTagName( query ), extra );
// Speed-up: Sizzle(".CLASS")
} else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) {
return makeArray( context.getElementsByClassName( match[2] ), extra );
}
}
if ( context.nodeType === 9 ) {
// Speed-up: Sizzle("body")
// The body element only exists once, optimize finding it
if ( query === "body" && context.body ) {
return makeArray( [ context.body ], extra );
// Speed-up: Sizzle("#ID")
} else if ( match && match[3] ) {
var elem = context.getElementById( match[3] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id === match[3] ) {
return makeArray( [ elem ], extra );
}
} else {
return makeArray( [], extra );
}
}
try {
return makeArray( context.querySelectorAll(query), extra );
} catch(qsaError) {}
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
} else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
var oldContext = context,
old = context.getAttribute( "id" ),
nid = old || id,
hasParent = context.parentNode,
relativeHierarchySelector = /^\s*[+~]/.test( query );
if ( !old ) {
context.setAttribute( "id", nid );
} else {
nid = nid.replace( /'/g, "\\$&" );
}
if ( relativeHierarchySelector && hasParent ) {
context = context.parentNode;
}
try {
if ( !relativeHierarchySelector || hasParent ) {
return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra );
}
} catch(pseudoError) {
} finally {
if ( !old ) {
oldContext.removeAttribute( "id" );
}
}
}
}
return oldSizzle(query, context, extra, seed);
};
for ( var prop in oldSizzle ) {
Sizzle[ prop ] = oldSizzle[ prop ];
}
// release memory in IE
div = null;
})();
}
(function(){
var html = document.documentElement,
matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector;
if ( matches ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9 fails this)
var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ),
pseudoWorks = false;
try {
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( document.documentElement, "[test!='']:sizzle" );
} catch( pseudoError ) {
pseudoWorks = true;
}
Sizzle.matchesSelector = function( node, expr ) {
// Make sure that attribute selectors are quoted
expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']");
if ( !Sizzle.isXML( node ) ) {
try {
if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) {
var ret = matches.call( node, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || !disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9, so check for that
node.document && node.document.nodeType !== 11 ) {
return ret;
}
}
} catch(e) {}
}
return Sizzle(expr, null, null, [node]).length > 0;
};
}
})();
(function(){
var div = document.createElement("div");
div.innerHTML = "<div class='test e'></div><div class='test'></div>";
// Opera can't find a second classname (in 9.6)
// Also, make sure that getElementsByClassName actually exists
if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) {
return;
}
// Safari caches class attributes, doesn't catch changes (in 3.2)
div.lastChild.className = "e";
if ( div.getElementsByClassName("e").length === 1 ) {
return;
}
Expr.order.splice(1, 0, "CLASS");
Expr.find.CLASS = function( match, context, isXML ) {
if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) {
return context.getElementsByClassName(match[1]);
}
};
// release memory in IE
div = null;
})();
function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
var match = false;
elem = elem[dir];
while ( elem ) {
if ( elem[ expando ] === doneName ) {
match = checkSet[elem.sizset];
break;
}
if ( elem.nodeType === 1 && !isXML ){
elem[ expando ] = doneName;
elem.sizset = i;
}
if ( elem.nodeName.toLowerCase() === cur ) {
match = elem;
break;
}
elem = elem[dir];
}
checkSet[i] = match;
}
}
}
function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
var match = false;
elem = elem[dir];
while ( elem ) {
if ( elem[ expando ] === doneName ) {
match = checkSet[elem.sizset];
break;
}
if ( elem.nodeType === 1 ) {
if ( !isXML ) {
elem[ expando ] = doneName;
elem.sizset = i;
}
if ( typeof cur !== "string" ) {
if ( elem === cur ) {
match = true;
break;
}
} else if ( Sizzle.filter( cur, [elem] ).length > 0 ) {
match = elem;
break;
}
}
elem = elem[dir];
}
checkSet[i] = match;
}
}
}
if ( document.documentElement.contains ) {
Sizzle.contains = function( a, b ) {
return a !== b && (a.contains ? a.contains(b) : true);
};
} else if ( document.documentElement.compareDocumentPosition ) {
Sizzle.contains = function( a, b ) {
return !!(a.compareDocumentPosition(b) & 16);
};
} else {
Sizzle.contains = function() {
return false;
};
}
Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
var posProcess = function( selector, context, seed ) {
var match,
tmpSet = [],
later = "",
root = context.nodeType ? [context] : context;
// Position selectors must be done after the filter
// And so must :not(positional) so we move all PSEUDOs to the end
while ( (match = Expr.match.PSEUDO.exec( selector )) ) {
later += match[0];
selector = selector.replace( Expr.match.PSEUDO, "" );
}
selector = Expr.relative[selector] ? selector + "*" : selector;
for ( var i = 0, l = root.length; i < l; i++ ) {
Sizzle( selector, root[i], tmpSet, seed );
}
return Sizzle.filter( later, tmpSet );
};
// EXPOSE
// Override sizzle attribute retrieval
Sizzle.attr = jQuery.attr;
Sizzle.selectors.attrMap = {};
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.filters;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
})();
var runtil = /Until$/,
rparentsprev = /^(?:parents|prevUntil|prevAll)/,
// Note: This RegExp should be improved, or likely pulled from Sizzle
rmultiselector = /,/,
isSimple = /^.[^:#\[\.,]*$/,
slice = Array.prototype.slice,
POS = jQuery.expr.match.globalPOS,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend({
find: function( selector ) {
var self = this,
i, l;
if ( typeof selector !== "string" ) {
return jQuery( selector ).filter(function() {
for ( i = 0, l = self.length; i < l; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
});
}
var ret = this.pushStack( "", "find", selector ),
length, n, r;
for ( i = 0, l = this.length; i < l; i++ ) {
length = ret.length;
jQuery.find( selector, this[i], ret );
if ( i > 0 ) {
// Make sure that the results are unique
for ( n = length; n < ret.length; n++ ) {
for ( r = 0; r < length; r++ ) {
if ( ret[r] === ret[n] ) {
ret.splice(n--, 1);
break;
}
}
}
}
}
return ret;
},
has: function( target ) {
var targets = jQuery( target );
return this.filter(function() {
for ( var i = 0, l = targets.length; i < l; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
not: function( selector ) {
return this.pushStack( winnow(this, selector, false), "not", selector);
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector, true), "filter", selector );
},
is: function( selector ) {
return !!selector && (
typeof selector === "string" ?
// If this is a positional selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
POS.test( selector ) ?
jQuery( selector, this.context ).index( this[0] ) >= 0 :
jQuery.filter( selector, this ).length > 0 :
this.filter( selector ).length > 0 );
},
closest: function( selectors, context ) {
var ret = [], i, l, cur = this[0];
// Array (deprecated as of jQuery 1.7)
if ( jQuery.isArray( selectors ) ) {
var level = 1;
while ( cur && cur.ownerDocument && cur !== context ) {
for ( i = 0; i < selectors.length; i++ ) {
if ( jQuery( cur ).is( selectors[ i ] ) ) {
ret.push({ selector: selectors[ i ], elem: cur, level: level });
}
}
cur = cur.parentNode;
level++;
}
return ret;
}
// String
var pos = POS.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( i = 0, l = this.length; i < l; i++ ) {
cur = this[i];
while ( cur ) {
if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
ret.push( cur );
break;
} else {
cur = cur.parentNode;
if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) {
break;
}
}
}
}
ret = ret.length > 1 ? jQuery.unique( ret ) : ret;
return this.pushStack( ret, "closest", selectors );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return jQuery.inArray( this[0], jQuery( elem ) );
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem, this );
},
add: function( selector, context ) {
var set = typeof selector === "string" ?
jQuery( selector, context ) :
jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
all = jQuery.merge( this.get(), set );
return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ?
all :
jQuery.unique( all ) );
},
andSelf: function() {
return this.add( this.prevObject );
}
});
// A painfully simple check to see if an element is disconnected
// from a document (should be improved, where feasible).
function isDisconnected( node ) {
return !node || !node.parentNode || node.parentNode.nodeType === 11;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return jQuery.nth( elem, 2, "nextSibling" );
},
prev: function( elem ) {
return jQuery.nth( elem, 2, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.makeArray( elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until );
if ( !runtil.test( name ) ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret, name, slice.call( arguments ).join(",") );
};
});
jQuery.extend({
filter: function( expr, elems, not ) {
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 ?
jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
jQuery.find.matches(expr, elems);
},
dir: function( elem, dir, until ) {
var matched = [],
cur = elem[ dir ];
while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
if ( cur.nodeType === 1 ) {
matched.push( cur );
}
cur = cur[dir];
}
return matched;
},
nth: function( cur, result, dir, elem ) {
result = result || 1;
var num = 0;
for ( ; cur; cur = cur[dir] ) {
if ( cur.nodeType === 1 && ++num === result ) {
break;
}
}
return cur;
},
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
});
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, keep ) {
// Can't pass null or undefined to indexOf in Firefox 4
// Set to 0 to skip string check
qualifier = qualifier || 0;
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep(elements, function( elem, i ) {
var retVal = !!qualifier.call( elem, i, elem );
return retVal === keep;
});
} else if ( qualifier.nodeType ) {
return jQuery.grep(elements, function( elem, i ) {
return ( elem === qualifier ) === keep;
});
} else if ( typeof qualifier === "string" ) {
var filtered = jQuery.grep(elements, function( elem ) {
return elem.nodeType === 1;
});
if ( isSimple.test( qualifier ) ) {
return jQuery.filter(qualifier, filtered, !keep);
} else {
qualifier = jQuery.filter( qualifier, filtered );
}
}
return jQuery.grep(elements, function( elem, i ) {
return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep;
});
}
function createSafeFragment( document ) {
var list = nodeNames.split( "|" ),
safeFrag = document.createDocumentFragment();
if ( safeFrag.createElement ) {
while ( list.length ) {
safeFrag.createElement(
list.pop()
);
}
}
return safeFrag;
}
var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g,
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style)/i,
rnocache = /<(?:script|object|embed|option|style)/i,
rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /\/(java|ecma)script/i,
rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)/,
wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
area: [ 1, "<map>", "</map>" ],
_default: [ 0, "", "" ]
},
safeFragment = createSafeFragment( document );
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
// IE can't serialize <link> and <script> tags normally
if ( !jQuery.support.htmlSerialize ) {
wrapMap._default = [ 1, "div<div>", "</div>" ];
}
jQuery.fn.extend({
text: function( 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.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 ) {
this.insertBefore( elem, this.firstChild );
}
});
},
before: function() {
if ( this[0] && this[0].parentNode ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this );
});
} else if ( arguments.length ) {
var set = jQuery.clean( arguments );
set.push.apply( set, this.toArray() );
return this.pushStack( set, "before", arguments );
}
},
after: function() {
if ( this[0] && this[0].parentNode ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this.nextSibling );
});
} else if ( arguments.length ) {
var set = this.pushStack( this, "after", arguments );
set.push.apply( set, jQuery.clean(arguments) );
return set;
}
},
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
jQuery.cleanData( [ elem ] );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
}
}
return this;
},
empty: function() {
for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function () {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
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, "" ) :
null;
}
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
!wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for (; 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 ( this[0] && this[0].parentNode ) {
// Make sure that the elements are removed from the DOM before they are inserted
// this can help fix replacing a parent with child elements
if ( jQuery.isFunction( value ) ) {
return this.each(function(i) {
var self = jQuery(this), old = self.html();
self.replaceWith( value.call( this, i, old ) );
});
}
if ( typeof value !== "string" ) {
value = jQuery( value ).detach();
}
return this.each(function() {
var next = this.nextSibling,
parent = this.parentNode;
jQuery( this ).remove();
if ( next ) {
jQuery(next).before( value );
} else {
jQuery(parent).append( value );
}
});
} else {
return this.length ?
this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) :
this;
}
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, table, callback ) {
var results, first, fragment, parent,
value = args[0],
scripts = [];
// We can't cloneNode fragments that contain checked, in WebKit
if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) {
return this.each(function() {
jQuery(this).domManip( args, table, callback, true );
});
}
if ( jQuery.isFunction(value) ) {
return this.each(function(i) {
var self = jQuery(this);
args[0] = value.call(this, i, table ? self.html() : undefined);
self.domManip( args, table, callback );
});
}
if ( this[0] ) {
parent = value && value.parentNode;
// If we're in a fragment, just use that instead of building a new one
if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) {
results = { fragment: parent };
} else {
results = jQuery.buildFragment( args, this, scripts );
}
fragment = results.fragment;
if ( fragment.childNodes.length === 1 ) {
first = fragment = fragment.firstChild;
} else {
first = fragment.firstChild;
}
if ( first ) {
table = table && jQuery.nodeName( first, "tr" );
for ( var i = 0, l = this.length, lastIndex = l - 1; i < l; i++ ) {
callback.call(
table ?
root(this[i], first) :
this[i],
// Make sure that we do not leak memory by inadvertently discarding
// the original fragment (which might have attached data) instead of
// using it; in addition, use the original fragment object for the last
// item instead of first because it can end up being emptied incorrectly
// in certain situations (Bug #8070).
// Fragments from the fragment cache must always be cloned and never used
// in place.
results.cacheable || ( l > 1 && i < lastIndex ) ?
jQuery.clone( fragment, true, true ) :
fragment
);
}
}
if ( scripts.length ) {
jQuery.each( scripts, function( i, elem ) {
if ( elem.src ) {
jQuery.ajax({
type: "GET",
global: false,
url: elem.src,
async: false,
dataType: "script"
});
} else {
jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "/*$0*/" ) );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
});
}
}
return this;
}
});
function root( elem, cur ) {
return jQuery.nodeName(elem, "table") ?
(elem.getElementsByTagName("tbody")[0] ||
elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
elem;
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
var type, i, l,
oldData = jQuery._data( src ),
curData = jQuery._data( dest, oldData ),
events = oldData.events;
if ( events ) {
delete curData.handle;
curData.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
// make the cloned public data object a copy from the original
if ( curData.data ) {
curData.data = jQuery.extend( {}, curData.data );
}
}
function cloneFixAttributes( src, dest ) {
var nodeName;
// We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) {
return;
}
// clearAttributes removes the attributes, which we don't want,
// but also removes the attachEvent events, which we *do* want
if ( dest.clearAttributes ) {
dest.clearAttributes();
}
// mergeAttributes, in contrast, only merges back on the
// original attributes, not the events
if ( dest.mergeAttributes ) {
dest.mergeAttributes( src );
}
nodeName = dest.nodeName.toLowerCase();
// IE6-8 fail to clone children inside object elements that use
// the proprietary classid attribute value (rather than the type
// attribute) to identify the type of content to display
if ( nodeName === "object" ) {
dest.outerHTML = src.outerHTML;
} else if ( nodeName === "input" && (src.type === "checkbox" || src.type === "radio") ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
if ( src.checked ) {
dest.defaultChecked = dest.checked = src.checked;
}
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if ( nodeName === "option" ) {
dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
// 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 );
// Clear flags for bubbling special change/submit events, they must
// be reattached when the newly cloned events are first activated
dest.removeAttribute( "_submit_attached" );
dest.removeAttribute( "_change_attached" );
}
jQuery.buildFragment = function( args, nodes, scripts ) {
var fragment, cacheable, cacheresults, doc,
first = args[ 0 ];
// nodes may contain either an explicit document object,
// a jQuery collection or context object.
// If nodes[0] contains a valid object to assign to doc
if ( nodes && nodes[0] ) {
doc = nodes[0].ownerDocument || nodes[0];
}
// Ensure that an attr object doesn't incorrectly stand in as a document object
// Chrome and Firefox seem to allow this to occur and will throw exception
// Fixes #8950
if ( !doc.createDocumentFragment ) {
doc = document;
}
// Only cache "small" (1/2 KB) HTML strings that are associated with the main document
// Cloning options loses the selected state, so don't cache them
// IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
// Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
// Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501
if ( args.length === 1 && typeof first === "string" && first.length < 512 && doc === document &&
first.charAt(0) === "<" && !rnocache.test( first ) &&
(jQuery.support.checkClone || !rchecked.test( first )) &&
(jQuery.support.html5Clone || !rnoshimcache.test( first )) ) {
cacheable = true;
cacheresults = jQuery.fragments[ first ];
if ( cacheresults && cacheresults !== 1 ) {
fragment = cacheresults;
}
}
if ( !fragment ) {
fragment = doc.createDocumentFragment();
jQuery.clean( args, doc, fragment, scripts );
}
if ( cacheable ) {
jQuery.fragments[ first ] = cacheresults ? fragment : 1;
}
return { fragment: fragment, cacheable: cacheable };
};
jQuery.fragments = {};
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var ret = [],
insert = jQuery( selector ),
parent = this.length === 1 && this[0].parentNode;
if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) {
insert[ original ]( this[0] );
return this;
} else {
for ( var i = 0, l = insert.length; i < l; i++ ) {
var elems = ( i > 0 ? this.clone(true) : this ).get();
jQuery( insert[i] )[ original ]( elems );
ret = ret.concat( elems );
}
return this.pushStack( ret, name, insert.selector );
}
};
});
function getAll( elem ) {
if ( typeof elem.getElementsByTagName !== "undefined" ) {
return elem.getElementsByTagName( "*" );
} else if ( typeof elem.querySelectorAll !== "undefined" ) {
return elem.querySelectorAll( "*" );
} else {
return [];
}
}
// Used in clean, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( elem.type === "checkbox" || elem.type === "radio" ) {
elem.defaultChecked = elem.checked;
}
}
// Finds all inputs and passes them to fixDefaultChecked
function findInputs( elem ) {
var nodeName = ( elem.nodeName || "" ).toLowerCase();
if ( nodeName === "input" ) {
fixDefaultChecked( elem );
// Skip scripts, get other children
} else if ( nodeName !== "script" && typeof elem.getElementsByTagName !== "undefined" ) {
jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked );
}
}
// Derived From: http://www.iecss.com/shimprove/javascript/shimprove.1-0-1.js
function shimCloneNode( elem ) {
var div = document.createElement( "div" );
safeFragment.appendChild( div );
div.innerHTML = elem.outerHTML;
return div.firstChild;
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var srcElements,
destElements,
i,
// IE<=8 does not properly clone detached, unknown element nodes
clone = jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ?
elem.cloneNode( true ) :
shimCloneNode( elem );
if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
// IE copies events bound via attachEvent when using cloneNode.
// Calling detachEvent on the clone will also remove the events
// from the original. In order to get around this, we use some
// proprietary methods to clear the events. Thanks to MooTools
// guys for this hotness.
cloneFixAttributes( elem, clone );
// Using Sizzle here is crazy slow, so we use getElementsByTagName instead
srcElements = getAll( elem );
destElements = getAll( clone );
// Weird iteration because IE will replace the length property
// with an element if you are cloning the body and one of the
// elements on the page has a name or id of "length"
for ( i = 0; srcElements[i]; ++i ) {
// Ensure that the destination node is not null; Fixes #9587
if ( destElements[i] ) {
cloneFixAttributes( srcElements[i], destElements[i] );
}
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
cloneCopyEvent( elem, clone );
if ( deepDataAndEvents ) {
srcElements = getAll( elem );
destElements = getAll( clone );
for ( i = 0; srcElements[i]; ++i ) {
cloneCopyEvent( srcElements[i], destElements[i] );
}
}
}
srcElements = destElements = null;
// Return the cloned set
return clone;
},
clean: function( elems, context, fragment, scripts ) {
var checkScriptType, script, j,
ret = [];
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;
}
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
if ( typeof elem === "number" ) {
elem += "";
}
if ( !elem ) {
continue;
}
// Convert html string into DOM nodes
if ( typeof elem === "string" ) {
if ( !rhtml.test( elem ) ) {
elem = context.createTextNode( elem );
} else {
// Fix "XHTML"-style tags in all browsers
elem = elem.replace(rxhtmlTag, "<$1></$2>");
// Trim whitespace, otherwise indexOf won't work as expected
var tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(),
wrap = wrapMap[ tag ] || wrapMap._default,
depth = wrap[0],
div = context.createElement("div"),
safeChildNodes = safeFragment.childNodes,
remove;
// Append wrapper element to unknown element safe doc fragment
if ( context === document ) {
// Use the fragment we've already created for this document
safeFragment.appendChild( div );
} else {
// Use a fragment created with the owner document
createSafeFragment( context ).appendChild( div );
}
// Go to html and back, then peel off extra wrappers
div.innerHTML = wrap[1] + elem + wrap[2];
// Move to the right depth
while ( depth-- ) {
div = div.lastChild;
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !jQuery.support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
var hasBody = rtbody.test(elem),
tbody = tag === "table" && !hasBody ?
div.firstChild && div.firstChild.childNodes :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !hasBody ?
div.childNodes :
[];
for ( j = tbody.length - 1; j >= 0 ; --j ) {
if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
tbody[ j ].parentNode.removeChild( tbody[ j ] );
}
}
}
// IE completely kills leading whitespace when innerHTML is used
if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
}
elem = div.childNodes;
// Clear elements from DocumentFragment (safeFragment or otherwise)
// to avoid hoarding elements. Fixes #11356
if ( div ) {
div.parentNode.removeChild( div );
// Guard against -1 index exceptions in FF3.6
if ( safeChildNodes.length > 0 ) {
remove = safeChildNodes[ safeChildNodes.length - 1 ];
if ( remove && remove.parentNode ) {
remove.parentNode.removeChild( remove );
}
}
}
}
}
// Resets defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
var len;
if ( !jQuery.support.appendChecked ) {
if ( elem[0] && typeof (len = elem.length) === "number" ) {
for ( j = 0; j < len; j++ ) {
findInputs( elem[j] );
}
} else {
findInputs( elem );
}
}
if ( elem.nodeType ) {
ret.push( elem );
} else {
ret = jQuery.merge( ret, elem );
}
}
if ( fragment ) {
checkScriptType = function( elem ) {
return !elem.type || rscriptType.test( elem.type );
};
for ( i = 0; ret[i]; i++ ) {
script = ret[i];
if ( scripts && jQuery.nodeName( script, "script" ) && (!script.type || rscriptType.test( script.type )) ) {
scripts.push( script.parentNode ? script.parentNode.removeChild( script ) : script );
} else {
if ( script.nodeType === 1 ) {
var jsTags = jQuery.grep( script.getElementsByTagName( "script" ), checkScriptType );
ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) );
}
fragment.appendChild( script );
}
}
}
return ret;
},
cleanData: function( elems ) {
var data, id,
cache = jQuery.cache,
special = jQuery.event.special,
deleteExpando = jQuery.support.deleteExpando;
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) {
continue;
}
id = elem[ jQuery.expando ];
if ( id ) {
data = cache[ id ];
if ( data && data.events ) {
for ( var type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
// Null the DOM reference to avoid IE6/7/8 leak (#7054)
if ( data.handle ) {
data.handle.elem = null;
}
}
if ( deleteExpando ) {
delete elem[ jQuery.expando ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( jQuery.expando );
}
delete cache[ id ];
}
}
}
});
var ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity=([^)]*)/,
// fixed for IE9, see #8346
rupper = /([A-Z]|^ms)/g,
rnum = /^[\-+]?(?:\d*\.)?\d+$/i,
rnumnonpx = /^-?(?:\d*\.)?\d+(?!px)[^\d\s]+$/i,
rrelNum = /^([\-+])=([\-+.\de]+)/,
rmargin = /^margin/,
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
// order is important!
cssExpand = [ "Top", "Right", "Bottom", "Left" ],
curCSS,
getComputedStyle,
currentStyle;
jQuery.fn.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 );
};
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;
} else {
return elem.style.opacity;
}
}
}
},
// Exclude the following css properties to add px
cssNumber: {
"fillOpacity": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, origName = jQuery.camelCase( name ),
style = elem.style, hooks = jQuery.cssHooks[ origName ];
name = jQuery.cssProps[ origName ] || origName;
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( +( ret[1] + 1) * +ret[2] ) + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that NaN and null values aren't set. See: #7116
if ( value == null || type === "number" && isNaN( value ) ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value )) !== undefined ) {
// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
// Fixes bug #5509
try {
style[ name ] = value;
} catch(e) {}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, extra ) {
var ret, hooks;
// Make sure that we're working with the right name
name = jQuery.camelCase( name );
hooks = jQuery.cssHooks[ name ];
name = jQuery.cssProps[ name ] || name;
// cssFloat needs a special treatment
if ( name === "cssFloat" ) {
name = "float";
}
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) {
return ret;
// Otherwise, if a way to get the computed value exists, use that
} else if ( curCSS ) {
return curCSS( elem, name );
}
},
// A method for quickly swapping in/out CSS properties to get correct calculations
swap: function( elem, options, callback ) {
var old = {},
ret, name;
// 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;
}
});
// DEPRECATED in 1.3, Use jQuery.css() instead
jQuery.curCSS = jQuery.css;
if ( document.defaultView && document.defaultView.getComputedStyle ) {
getComputedStyle = function( elem, name ) {
var ret, defaultView, computedStyle, width,
style = elem.style;
name = name.replace( rupper, "-$1" ).toLowerCase();
if ( (defaultView = elem.ownerDocument.defaultView) &&
(computedStyle = defaultView.getComputedStyle( elem, null )) ) {
ret = computedStyle.getPropertyValue( name );
if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) {
ret = jQuery.style( elem, name );
}
}
// A tribute to the "awesome hack by Dean Edwards"
// WebKit uses "computed value (percentage if specified)" instead of "used value" for margins
// which is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if ( !jQuery.support.pixelMargin && computedStyle && rmargin.test( name ) && rnumnonpx.test( ret ) ) {
width = style.width;
style.width = ret;
ret = computedStyle.width;
style.width = width;
}
return ret;
};
}
if ( document.documentElement.currentStyle ) {
currentStyle = function( elem, name ) {
var left, rsLeft, uncomputed,
ret = elem.currentStyle && elem.currentStyle[ name ],
style = elem.style;
// Avoid setting ret to empty string here
// so we don't default to auto
if ( ret == null && style && (uncomputed = style[ name ]) ) {
ret = uncomputed;
}
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
if ( rnumnonpx.test( ret ) ) {
// Remember the original values
left = style.left;
rsLeft = elem.runtimeStyle && elem.runtimeStyle.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
elem.runtimeStyle.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : ret;
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 getWidthOrHeight( elem, name, extra ) {
// Start with offset property
var val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
i = name === "width" ? 1 : 0,
len = 4;
if ( val > 0 ) {
if ( extra !== "border" ) {
for ( ; i < len; i += 2 ) {
if ( !extra ) {
val -= parseFloat( jQuery.css( elem, "padding" + cssExpand[ i ] ) ) || 0;
}
if ( extra === "margin" ) {
val += parseFloat( jQuery.css( elem, extra + cssExpand[ i ] ) ) || 0;
} else {
val -= parseFloat( jQuery.css( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0;
}
}
}
return val + "px";
}
// 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;
}
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
// Add padding, border, margin
if ( extra ) {
for ( ; i < len; i += 2 ) {
val += parseFloat( jQuery.css( elem, "padding" + cssExpand[ i ] ) ) || 0;
if ( extra !== "padding" ) {
val += parseFloat( jQuery.css( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0;
}
if ( extra === "margin" ) {
val += parseFloat( jQuery.css( elem, extra + cssExpand[ i ]) ) || 0;
}
}
}
return val + "px";
}
jQuery.each([ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
if ( elem.offsetWidth !== 0 ) {
return getWidthOrHeight( elem, name, extra );
} else {
return jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
});
}
}
},
set: function( elem, value ) {
return rnum.test( value ) ?
value + "px" :
value;
}
};
});
if ( !jQuery.support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
( parseFloat( RegExp.$1 ) / 100 ) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style,
currentStyle = elem.currentStyle,
opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
filter = currentStyle && currentStyle.filter || style.filter || "";
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" ) {
// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
// if "filter:" is present at all, clearType is disabled, we want to avoid this
// style.removeAttribute is IE Only, but so apparently is this code path...
style.removeAttribute( "filter" );
// if there there is no filter style applied in a css rule, we are done
if ( currentStyle && !currentStyle.filter ) {
return;
}
}
// otherwise, set new filter values
style.filter = ralpha.test( filter ) ?
filter.replace( ralpha, opacity ) :
filter + " " + opacity;
}
};
}
jQuery(function() {
// This hook cannot be added until DOM ready because the support test
// for it is not run until after DOM ready
if ( !jQuery.support.reliableMarginRight ) {
jQuery.cssHooks.marginRight = {
get: function( elem, computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
return jQuery.swap( elem, { "display": "inline-block" }, function() {
if ( computed ) {
return curCSS( elem, "margin-right" );
} else {
return elem.style.marginRight;
}
});
}
};
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.hidden = function( elem ) {
var width = elem.offsetWidth,
height = elem.offsetHeight;
return ( width === 0 && height === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
}
// 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;
}
};
});
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rhash = /#.*$/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rquery = /\?/,
rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
rselectTextarea = /^(?:select|textarea)/i,
rspacesAjax = /\s+/,
rts = /([?&])_=[^&]*/,
rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,
// Keep a copy of the old load method
_load = jQuery.fn.load,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Document location
ajaxLocation,
// Document location segments
ajaxLocParts,
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = ["*/"] + ["*"];
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
if ( jQuery.isFunction( func ) ) {
var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ),
i = 0,
length = dataTypes.length,
dataType,
list,
placeBefore;
// For each dataType in the dataTypeExpression
for ( ; i < length; i++ ) {
dataType = dataTypes[ i ];
// We control if we're asked to add before
// any existing element
placeBefore = /^\+/.test( dataType );
if ( placeBefore ) {
dataType = dataType.substr( 1 ) || "*";
}
list = structure[ dataType ] = structure[ dataType ] || [];
// then we add to the structure accordingly
list[ placeBefore ? "unshift" : "push" ]( func );
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR,
dataType /* internal */, inspected /* internal */ ) {
dataType = dataType || options.dataTypes[ 0 ];
inspected = inspected || {};
inspected[ dataType ] = true;
var list = structure[ dataType ],
i = 0,
length = list ? list.length : 0,
executeOnly = ( structure === prefilters ),
selection;
for ( ; i < length && ( executeOnly || !selection ); i++ ) {
selection = list[ i ]( options, originalOptions, jqXHR );
// If we got redirected to another dataType
// we try there if executing only and not done already
if ( typeof selection === "string" ) {
if ( !executeOnly || inspected[ selection ] ) {
selection = undefined;
} else {
options.dataTypes.unshift( selection );
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, selection, inspected );
}
}
}
// If we're only executing or nothing was selected
// we try the catchall dataType if not done already
if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) {
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, "*", inspected );
}
// unnecessary when only executing (prefilters)
// but it'll be ignored by the caller in that case
return selection;
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var key, deep,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
}
jQuery.fn.extend({
load: function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
// Don't do a request if no elements are being requested
} else if ( !this.length ) {
return this;
}
var off = url.indexOf( " " );
if ( off >= 0 ) {
var selector = url.slice( off, url.length );
url = url.slice( 0, off );
}
// Default to a GET request
var type = "GET";
// If the second parameter was provided
if ( params ) {
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( typeof params === "object" ) {
params = jQuery.param( params, jQuery.ajaxSettings.traditional );
type = "POST";
}
}
var self = this;
// Request the remote document
jQuery.ajax({
url: url,
type: type,
dataType: "html",
data: params,
// Complete callback (responseText is used internally)
complete: function( jqXHR, status, responseText ) {
// Store the response as specified by the jqXHR object
responseText = jqXHR.responseText;
// If successful, inject the HTML into all the matched elements
if ( jqXHR.isResolved() ) {
// #4825: Get the actual response in case
// a dataFilter is present in ajaxSettings
jqXHR.done(function( r ) {
responseText = r;
});
// See if a selector was specified
self.html( selector ?
// Create a dummy div to hold the results
jQuery("<div>")
// inject the contents of the document in, removing the scripts
// to avoid any 'Permission Denied' errors in IE
.append(responseText.replace(rscript, ""))
// Locate the specified elements
.find(selector) :
// If not, just inject the full result
responseText );
}
if ( callback ) {
self.each( callback, [ responseText, status, jqXHR ] );
}
}
});
return this;
},
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function(){
return this.elements ? jQuery.makeArray( this.elements ) : this;
})
.filter(function(){
return this.name && !this.disabled &&
( this.checked || rselectTextarea.test( this.nodeName ) ||
rinput.test( this.type ) );
})
.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val, i ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
// Attach a bunch of functions for handling common AJAX events
jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){
jQuery.fn[ o ] = function( f ){
return this.on( o, f );
};
});
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
type: method,
url: url,
data: data,
success: callback,
dataType: type
});
};
});
jQuery.extend({
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
if ( settings ) {
// Building a settings object
ajaxExtend( target, jQuery.ajaxSettings );
} else {
// Extending ajaxSettings
settings = target;
target = jQuery.ajaxSettings;
}
ajaxExtend( target, settings );
return target;
},
ajaxSettings: {
url: ajaxLocation,
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
type: "GET",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
processData: true,
async: true,
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
traditional: false,
headers: {},
*/
accepts: {
xml: "application/xml, text/xml",
html: "text/html",
text: "text/plain",
json: "application/json, text/javascript",
"*": allTypes
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText"
},
// List of data converters
// 1) key format is "source_type destination_type" (a single space in-between)
// 2) the catchall symbol "*" can be used for source_type
converters: {
// Convert anything to text
"* text": window.String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
context: true,
url: true
}
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var // Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events
// It's the callbackContext if one was provided in the options
// and if it's a DOM node or a jQuery collection
globalEventContext = callbackContext !== s &&
( callbackContext.nodeType || callbackContext instanceof jQuery ) ?
jQuery( callbackContext ) : jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks( "once memory" ),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// ifModified key
ifModifiedKey,
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// Response headers
responseHeadersString,
responseHeaders,
// transport
transport,
// timeout handle
timeoutTimer,
// Cross-domain detection vars
parts,
// The jqXHR state
state = 0,
// To know if global events are to be dispatched
fireGlobals,
// Loop variable
i,
// Fake xhr
jqXHR = {
readyState: 0,
// Caches the header
setRequestHeader: function( name, value ) {
if ( !state ) {
var lname = name.toLowerCase();
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
if ( !responseHeaders ) {
responseHeaders = {};
while( ( match = rheaders.exec( responseHeadersString ) ) ) {
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match === undefined ? null : match;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Cancel the request
abort: function( statusText ) {
statusText = statusText || "abort";
if ( transport ) {
transport.abort( statusText );
}
done( 0, statusText );
return this;
}
};
// Callback for when everything is done
// It is defined here because jslint complains if it is declared
// at the end of the function (which would be more logical and readable)
function done( status, nativeStatusText, responses, headers ) {
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
var isSuccess,
success,
error,
statusText = nativeStatusText,
response = responses ? ajaxHandleResponses( s, jqXHR, responses ) : undefined,
lastModified,
etag;
// If successful, handle type chaining
if ( status >= 200 && status < 300 || status === 304 ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) {
jQuery.lastModified[ ifModifiedKey ] = lastModified;
}
if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) {
jQuery.etag[ ifModifiedKey ] = etag;
}
}
// If not modified
if ( status === 304 ) {
statusText = "notmodified";
isSuccess = true;
// If we have data
} else {
try {
success = ajaxConvert( s, response );
statusText = "success";
isSuccess = true;
} catch(e) {
// We have a parsererror
statusText = "parsererror";
error = e;
}
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if ( !statusText || status ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = "" + ( nativeStatusText || statusText );
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger( "ajaxStop" );
}
}
}
// Attach deferreds
deferred.promise( jqXHR );
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
jqXHR.complete = completeDeferred.add;
// Status-dependent callbacks
jqXHR.statusCode = function( map ) {
if ( map ) {
var tmp;
if ( state < 2 ) {
for ( tmp in map ) {
statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
}
} else {
tmp = map[ jqXHR.status ];
jqXHR.then( tmp, tmp );
}
}
return this;
};
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// We also use the url parameter if available
s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax );
// Determine if a cross-domain request is in order
if ( s.crossDomain == null ) {
parts = rurl.exec( s.url.toLowerCase() );
s.crossDomain = !!( parts &&
( parts[ 1 ] != ajaxLocParts[ 1 ] || parts[ 2 ] != ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) )
);
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefilter, stop there
if ( state === 2 ) {
return false;
}
// We can fire global events as of now if asked to
fireGlobals = s.global;
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger( "ajaxStart" );
}
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Get ifModifiedKey before adding the anti-cache parameter
ifModifiedKey = s.url;
// Add anti-cache in url if needed
if ( s.cache === false ) {
var ts = jQuery.now(),
// try replacing _= if it is there
ret = s.url.replace( rts, "$1_=" + ts );
// if nothing was replaced, add timestamp to the end
s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
ifModifiedKey = ifModifiedKey || s.url;
if ( jQuery.lastModified[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] );
}
if ( jQuery.etag[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] );
}
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
// Abort if not done already
jqXHR.abort();
return false;
}
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout( function(){
jqXHR.abort( "timeout" );
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch (e) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw e;
}
}
}
return jqXHR;
},
// Serialize an array of form elements or a set of
// key/values into a query string
param: function( a, traditional ) {
var s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : value;
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( var prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
}
});
function buildParams( prefix, obj, traditional, add ) {
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// If array item is non-scalar (array or object), encode its
// numeric index to resolve deserialization ambiguity issues.
// Note that rack (as of 1.0.0) can't currently deserialize
// nested arrays properly, and attempting to do so may cause
// a server error. Possible fixes are to modify rack's
// deserialization algorithm or to provide an option or flag
// to force array serialization to be shallow.
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( var name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
// This is still on the jQuery object... for now
// Want to move this to jQuery.ajax some day
jQuery.extend({
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {}
});
/* Handles responses to an ajax request:
* - sets all responseXXX fields accordingly
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var contents = s.contents,
dataTypes = s.dataTypes,
responseFields = s.responseFields,
ct,
type,
finalDataType,
firstDataType;
// Fill responseXXX fields
for ( type in responseFields ) {
if ( type in responses ) {
jqXHR[ responseFields[type] ] = responses[ type ];
}
}
// Remove auto dataType and get content-type in the process
while( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader( "content-type" );
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
// Chain conversions given the request and the original response
function ajaxConvert( s, response ) {
// Apply the dataFilter if provided
if ( s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
var dataTypes = s.dataTypes,
converters = {},
i,
key,
length = dataTypes.length,
tmp,
// Current and previous dataTypes
current = dataTypes[ 0 ],
prev,
// Conversion expression
conversion,
// Conversion function
conv,
// Conversion functions (transitive conversion)
conv1,
conv2;
// For each dataType in the chain
for ( i = 1; i < length; i++ ) {
// Create converters map
// with lowercased keys
if ( i === 1 ) {
for ( key in s.converters ) {
if ( typeof key === "string" ) {
converters[ key.toLowerCase() ] = s.converters[ key ];
}
}
}
// Get the dataTypes
prev = current;
current = dataTypes[ i ];
// If current is auto dataType, update it to prev
if ( current === "*" ) {
current = prev;
// If no auto and dataTypes are actually different
} else if ( prev !== "*" && prev !== current ) {
// Get the converter
conversion = prev + " " + current;
conv = converters[ conversion ] || converters[ "* " + current ];
// If there is no direct converter, search transitively
if ( !conv ) {
conv2 = undefined;
for ( conv1 in converters ) {
tmp = conv1.split( " " );
if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) {
conv2 = converters[ tmp[1] + " " + current ];
if ( conv2 ) {
conv1 = converters[ conv1 ];
if ( conv1 === true ) {
conv = conv2;
} else if ( conv2 === true ) {
conv = conv1;
}
break;
}
}
}
}
// If we found no converter, dispatch an error
if ( !( conv || conv2 ) ) {
jQuery.error( "No conversion from " + conversion.replace(" "," to ") );
}
// If found converter is not an equivalence
if ( conv !== true ) {
// Convert with 1 or 2 converters accordingly
response = conv ? conv( response ) : conv2( conv1(response) );
}
}
}
return response;
}
var jsc = jQuery.now(),
jsre = /(\=)\?(&|$)|\?\?/i;
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
return jQuery.expando + "_" + ( jsc++ );
}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var inspectData = ( typeof s.data === "string" ) && /^application\/x\-www\-form\-urlencoded/.test( s.contentType );
if ( s.dataTypes[ 0 ] === "jsonp" ||
s.jsonp !== false && ( jsre.test( s.url ) ||
inspectData && jsre.test( s.data ) ) ) {
var responseContainer,
jsonpCallback = s.jsonpCallback =
jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback,
previous = window[ jsonpCallback ],
url = s.url,
data = s.data,
replace = "$1" + jsonpCallback + "$2";
if ( s.jsonp !== false ) {
url = url.replace( jsre, replace );
if ( s.url === url ) {
if ( inspectData ) {
data = data.replace( jsre, replace );
}
if ( s.data === data ) {
// Add callback manually
url += (/\?/.test( url ) ? "&" : "?") + s.jsonp + "=" + jsonpCallback;
}
}
}
s.url = url;
s.data = data;
// Install callback
window[ jsonpCallback ] = function( response ) {
responseContainer = [ response ];
};
// Clean-up function
jqXHR.always(function() {
// Set callback back to previous value
window[ jsonpCallback ] = previous;
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( previous ) ) {
window[ jsonpCallback ]( responseContainer[ 0 ] );
}
});
// Use data converter to retrieve json after script execution
s.converters["script json"] = function() {
if ( !responseContainer ) {
jQuery.error( jsonpCallback + " was not called" );
}
return responseContainer[ 0 ];
};
// force json dataType
s.dataTypes[ 0 ] = "json";
// Delegate to script
return "script";
}
});
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /javascript|ecmascript/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
s.global = false;
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script,
head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement;
return {
send: function( _, callback ) {
script = document.createElement( "script" );
script.async = "async";
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( head && script.parentNode ) {
head.removeChild( script );
}
// Dereference the script
script = undefined;
// Callback if not abort
if ( !isAbort ) {
callback( 200, "success" );
}
}
};
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
// This arises when a base node is used (#2709 and #4378).
head.insertBefore( script, head.firstChild );
},
abort: function() {
if ( script ) {
script.onload( 0, 1 );
}
}
};
}
});
var // #5280: Internet Explorer will keep connections alive if we don't abort on unload
xhrOnUnloadAbort = window.ActiveXObject ? function() {
// Abort all pending requests
for ( var key in xhrCallbacks ) {
xhrCallbacks[ key ]( 0, 1 );
}
} : false,
xhrId = 0,
xhrCallbacks;
// Functions to create xhrs
function createStandardXHR() {
try {
return new window.XMLHttpRequest();
} catch( e ) {}
}
function createActiveXHR() {
try {
return new window.ActiveXObject( "Microsoft.XMLHTTP" );
} catch( e ) {}
}
// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject ?
/* Microsoft failed to properly
* implement the XMLHttpRequest in IE7 (can't request local files),
* so we use the ActiveXObject when it is available
* Additionally XMLHttpRequest can be disabled in IE7/IE8 so
* we need a fallback.
*/
function() {
return !this.isLocal && createStandardXHR() || createActiveXHR();
} :
// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;
// Determine support properties
(function( xhr ) {
jQuery.extend( jQuery.support, {
ajax: !!xhr,
cors: !!xhr && ( "withCredentials" in xhr )
});
})( jQuery.ajaxSettings.xhr() );
// Create transport if the browser can provide an xhr
if ( jQuery.support.ajax ) {
jQuery.ajaxTransport(function( s ) {
// Cross domain only allowed if supported through XMLHttpRequest
if ( !s.crossDomain || jQuery.support.cors ) {
var callback;
return {
send: function( headers, complete ) {
// Get a new xhr
var xhr = s.xhr(),
handle,
i;
// Open the socket
// Passing null username, generates a login popup on Opera (#2865)
if ( s.username ) {
xhr.open( s.type, s.url, s.async, s.username, s.password );
} else {
xhr.open( s.type, s.url, s.async );
}
// Apply custom fields if provided
if ( s.xhrFields ) {
for ( i in s.xhrFields ) {
xhr[ i ] = s.xhrFields[ i ];
}
}
// Override mime type if needed
if ( s.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( s.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !s.crossDomain && !headers["X-Requested-With"] ) {
headers[ "X-Requested-With" ] = "XMLHttpRequest";
}
// Need an extra try/catch for cross domain requests in Firefox 3
try {
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
} catch( _ ) {}
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( ( s.hasContent && s.data ) || null );
// Listener
callback = function( _, isAbort ) {
var status,
statusText,
responseHeaders,
responses,
xml;
// Firefox throws exceptions when accessing properties
// of an xhr when a network error occured
// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
try {
// Was never called and is aborted or complete
if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
// Only called once
callback = undefined;
// Do not keep as active anymore
if ( handle ) {
xhr.onreadystatechange = jQuery.noop;
if ( xhrOnUnloadAbort ) {
delete xhrCallbacks[ handle ];
}
}
// If it's an abort
if ( isAbort ) {
// Abort it manually if needed
if ( xhr.readyState !== 4 ) {
xhr.abort();
}
} else {
status = xhr.status;
responseHeaders = xhr.getAllResponseHeaders();
responses = {};
xml = xhr.responseXML;
// Construct response list
if ( xml && xml.documentElement /* #4958 */ ) {
responses.xml = xml;
}
// When requesting binary data, IE6-9 will throw an exception
// on any attempt to access responseText (#11426)
try {
responses.text = xhr.responseText;
} catch( _ ) {
}
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
statusText = xhr.statusText;
} catch( e ) {
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if ( !status && s.isLocal && !s.crossDomain ) {
status = responses.text ? 200 : 404;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if ( status === 1223 ) {
status = 204;
}
}
}
} catch( firefoxAccessException ) {
if ( !isAbort ) {
complete( -1, firefoxAccessException );
}
}
// Call complete if needed
if ( responses ) {
complete( status, statusText, responses, responseHeaders );
}
};
// if we're in sync mode or it's in cache
// and has been retrieved directly (IE6 & IE7)
// we need to manually fire the callback
if ( !s.async || xhr.readyState === 4 ) {
callback();
} else {
handle = ++xhrId;
if ( xhrOnUnloadAbort ) {
// Create the active xhrs callbacks list if needed
// and attach the unload handler
if ( !xhrCallbacks ) {
xhrCallbacks = {};
jQuery( window ).unload( xhrOnUnloadAbort );
}
// Add to list of active xhrs callbacks
xhrCallbacks[ handle ] = callback;
}
xhr.onreadystatechange = callback;
}
},
abort: function() {
if ( callback ) {
callback(0,1);
}
}
};
}
});
}
var elemdisplay = {},
iframe, iframeDoc,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,
timerId,
fxAttrs = [
// height animations
[ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ],
// width animations
[ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ],
// opacity animations
[ "opacity" ]
],
fxNow;
jQuery.fn.extend({
show: function( speed, easing, callback ) {
var elem, display;
if ( speed || speed === 0 ) {
return this.animate( genFx("show", 3), speed, easing, callback );
} else {
for ( var i = 0, j = this.length; i < j; i++ ) {
elem = this[ i ];
if ( elem.style ) {
display = elem.style.display;
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !jQuery._data(elem, "olddisplay") && display === "none" ) {
display = elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( (display === "" && jQuery.css(elem, "display") === "none") ||
!jQuery.contains( elem.ownerDocument.documentElement, elem ) ) {
jQuery._data( elem, "olddisplay", defaultDisplay(elem.nodeName) );
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( i = 0; i < j; i++ ) {
elem = this[ i ];
if ( elem.style ) {
display = elem.style.display;
if ( display === "" || display === "none" ) {
elem.style.display = jQuery._data( elem, "olddisplay" ) || "";
}
}
}
return this;
}
},
hide: function( speed, easing, callback ) {
if ( speed || speed === 0 ) {
return this.animate( genFx("hide", 3), speed, easing, callback);
} else {
var elem, display,
i = 0,
j = this.length;
for ( ; i < j; i++ ) {
elem = this[i];
if ( elem.style ) {
display = jQuery.css( elem, "display" );
if ( display !== "none" && !jQuery._data( elem, "olddisplay" ) ) {
jQuery._data( elem, "olddisplay", display );
}
}
}
// Set the display of the elements in a second loop
// to avoid the constant reflow
for ( i = 0; i < j; i++ ) {
if ( this[i].style ) {
this[i].style.display = "none";
}
}
return this;
}
},
// Save the old toggle function
_toggle: jQuery.fn.toggle,
toggle: function( fn, fn2, callback ) {
var bool = typeof fn === "boolean";
if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) {
this._toggle.apply( this, arguments );
} else if ( fn == null || bool ) {
this.each(function() {
var state = bool ? fn : jQuery(this).is(":hidden");
jQuery(this)[ state ? "show" : "hide" ]();
});
} else {
this.animate(genFx("toggle", 3), fn, fn2, callback);
}
return this;
},
fadeTo: function( speed, to, easing, callback ) {
return this.filter(":hidden").css("opacity", 0).show().end()
.animate({opacity: to}, speed, easing, callback);
},
animate: function( prop, speed, easing, callback ) {
var optall = jQuery.speed( speed, easing, callback );
if ( jQuery.isEmptyObject( prop ) ) {
return this.each( optall.complete, [ false ] );
}
// Do not change referenced properties as per-property easing will be lost
prop = jQuery.extend( {}, prop );
function doAnimation() {
// XXX 'this' does not always have a nodeName when running the
// test suite
if ( optall.queue === false ) {
jQuery._mark( this );
}
var opt = jQuery.extend( {}, optall ),
isElement = this.nodeType === 1,
hidden = isElement && jQuery(this).is(":hidden"),
name, val, p, e, hooks, replace,
parts, start, end, unit,
method;
// will store per property easing and be used to determine when an animation is complete
opt.animatedProperties = {};
// first pass over propertys to expand / normalize
for ( p in prop ) {
name = jQuery.camelCase( p );
if ( p !== name ) {
prop[ name ] = prop[ p ];
delete prop[ p ];
}
if ( ( hooks = jQuery.cssHooks[ name ] ) && "expand" in hooks ) {
replace = hooks.expand( prop[ name ] );
delete prop[ name ];
// not quite $.extend, this wont overwrite keys already present.
// also - reusing 'p' from above because we have the correct "name"
for ( p in replace ) {
if ( ! ( p in prop ) ) {
prop[ p ] = replace[ p ];
}
}
}
}
for ( name in prop ) {
val = prop[ name ];
// easing resolution: per property > opt.specialEasing > opt.easing > 'swing' (default)
if ( jQuery.isArray( val ) ) {
opt.animatedProperties[ name ] = val[ 1 ];
val = prop[ name ] = val[ 0 ];
} else {
opt.animatedProperties[ name ] = opt.specialEasing && opt.specialEasing[ name ] || opt.easing || 'swing';
}
if ( val === "hide" && hidden || val === "show" && !hidden ) {
return opt.complete.call( this );
}
if ( isElement && ( name === "height" || name === "width" ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opt.overflow = [ this.style.overflow, this.style.overflowX, this.style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height animated
if ( jQuery.css( this, "display" ) === "inline" &&
jQuery.css( this, "float" ) === "none" ) {
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( !jQuery.support.inlineBlockNeedsLayout || defaultDisplay( this.nodeName ) === "inline" ) {
this.style.display = "inline-block";
} else {
this.style.zoom = 1;
}
}
}
}
if ( opt.overflow != null ) {
this.style.overflow = "hidden";
}
for ( p in prop ) {
e = new jQuery.fx( this, opt, p );
val = prop[ p ];
if ( rfxtypes.test( val ) ) {
// Tracks whether to show or hide based on private
// data attached to the element
method = jQuery._data( this, "toggle" + p ) || ( val === "toggle" ? hidden ? "show" : "hide" : 0 );
if ( method ) {
jQuery._data( this, "toggle" + p, method === "show" ? "hide" : "show" );
e[ method ]();
} else {
e[ val ]();
}
} else {
parts = rfxnum.exec( val );
start = e.cur();
if ( parts ) {
end = parseFloat( parts[2] );
unit = parts[3] || ( jQuery.cssNumber[ p ] ? "" : "px" );
// We need to compute starting value
if ( unit !== "px" ) {
jQuery.style( this, p, (end || 1) + unit);
start = ( (end || 1) / e.cur() ) * start;
jQuery.style( this, p, start + unit);
}
// If a +=/-= token was provided, we're doing a relative animation
if ( parts[1] ) {
end = ( (parts[ 1 ] === "-=" ? -1 : 1) * end ) + start;
}
e.custom( start, end, unit );
} else {
e.custom( start, val, "" );
}
}
}
// For JS strict compliance
return true;
}
return optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
if ( typeof type !== "string" ) {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if ( clearQueue && type !== false ) {
this.queue( type || "fx", [] );
}
return this.each(function() {
var index,
hadTimers = false,
timers = jQuery.timers,
data = jQuery._data( this );
// clear marker counters if we know they won't be
if ( !gotoEnd ) {
jQuery._unmark( true, this );
}
function stopQueue( elem, data, index ) {
var hooks = data[ index ];
jQuery.removeData( elem, index, true );
hooks.stop( gotoEnd );
}
if ( type == null ) {
for ( index in data ) {
if ( data[ index ] && data[ index ].stop && index.indexOf(".run") === index.length - 4 ) {
stopQueue( this, data, index );
}
}
} else if ( data[ index = type + ".run" ] && data[ index ].stop ){
stopQueue( this, data, index );
}
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
if ( gotoEnd ) {
// force the next step to be the last
timers[ index ]( true );
} else {
timers[ index ].saveState();
}
hadTimers = true;
timers.splice( index, 1 );
}
}
// start the next in the queue if the last step wasn't forced
// timers currently will call their complete callbacks, which will dequeue
// but only if they were gotoEnd
if ( !( gotoEnd && hadTimers ) ) {
jQuery.dequeue( this, type );
}
});
}
});
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout( clearFxNow, 0 );
return ( fxNow = jQuery.now() );
}
function clearFxNow() {
fxNow = undefined;
}
// Generate parameters to create a standard animation
function genFx( type, num ) {
var obj = {};
jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice( 0, num )), function() {
obj[ this ] = type;
});
return obj;
}
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx( "show", 1 ),
slideUp: genFx( "hide", 1 ),
slideToggle: genFx( "toggle", 1 ),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
});
jQuery.extend({
speed: function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
// normalize opt.queue - true/undefined/null -> "fx"
if ( opt.queue == null || opt.queue === true ) {
opt.queue = "fx";
}
// Queueing
opt.old = opt.complete;
opt.complete = function( noUnmark ) {
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
if ( opt.queue ) {
jQuery.dequeue( this, opt.queue );
} else if ( noUnmark !== false ) {
jQuery._unmark( this );
}
};
return opt;
},
easing: {
linear: function( p ) {
return p;
},
swing: function( p ) {
return ( -Math.cos( p*Math.PI ) / 2 ) + 0.5;
}
},
timers: [],
fx: function( elem, options, prop ) {
this.options = options;
this.elem = elem;
this.prop = prop;
options.orig = options.orig || {};
}
});
jQuery.fx.prototype = {
// Simple function for setting a style value
update: function() {
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
( jQuery.fx.step[ this.prop ] || jQuery.fx.step._default )( this );
},
// Get the current size
cur: function() {
if ( this.elem[ this.prop ] != null && (!this.elem.style || this.elem.style[ this.prop ] == null) ) {
return this.elem[ this.prop ];
}
var parsed,
r = jQuery.css( this.elem, this.prop );
// Empty strings, null, undefined and "auto" are converted to 0,
// complex values such as "rotate(1rad)" are returned as is,
// simple values such as "10px" are parsed to Float.
return isNaN( parsed = parseFloat( r ) ) ? !r || r === "auto" ? 0 : r : parsed;
},
// Start an animation from one number to another
custom: function( from, to, unit ) {
var self = this,
fx = jQuery.fx;
this.startTime = fxNow || createFxNow();
this.end = to;
this.now = this.start = from;
this.pos = this.state = 0;
this.unit = unit || this.unit || ( jQuery.cssNumber[ this.prop ] ? "" : "px" );
function t( gotoEnd ) {
return self.step( gotoEnd );
}
t.queue = this.options.queue;
t.elem = this.elem;
t.saveState = function() {
if ( jQuery._data( self.elem, "fxshow" + self.prop ) === undefined ) {
if ( self.options.hide ) {
jQuery._data( self.elem, "fxshow" + self.prop, self.start );
} else if ( self.options.show ) {
jQuery._data( self.elem, "fxshow" + self.prop, self.end );
}
}
};
if ( t() && jQuery.timers.push(t) && !timerId ) {
timerId = setInterval( fx.tick, fx.interval );
}
},
// Simple 'show' function
show: function() {
var dataShow = jQuery._data( this.elem, "fxshow" + this.prop );
// Remember where we started, so that we can go back to it later
this.options.orig[ this.prop ] = dataShow || jQuery.style( this.elem, this.prop );
this.options.show = true;
// Begin the animation
// Make sure that we start at a small width/height to avoid any flash of content
if ( dataShow !== undefined ) {
// This show is picking up where a previous hide or show left off
this.custom( this.cur(), dataShow );
} else {
this.custom( this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur() );
}
// Start by showing the element
jQuery( this.elem ).show();
},
// Simple 'hide' function
hide: function() {
// Remember where we started, so that we can go back to it later
this.options.orig[ this.prop ] = jQuery._data( this.elem, "fxshow" + this.prop ) || jQuery.style( this.elem, this.prop );
this.options.hide = true;
// Begin the animation
this.custom( this.cur(), 0 );
},
// Each step of an animation
step: function( gotoEnd ) {
var p, n, complete,
t = fxNow || createFxNow(),
done = true,
elem = this.elem,
options = this.options;
if ( gotoEnd || t >= options.duration + this.startTime ) {
this.now = this.end;
this.pos = this.state = 1;
this.update();
options.animatedProperties[ this.prop ] = true;
for ( p in options.animatedProperties ) {
if ( options.animatedProperties[ p ] !== true ) {
done = false;
}
}
if ( done ) {
// Reset the overflow
if ( options.overflow != null && !jQuery.support.shrinkWrapBlocks ) {
jQuery.each( [ "", "X", "Y" ], function( index, value ) {
elem.style[ "overflow" + value ] = options.overflow[ index ];
});
}
// Hide the element if the "hide" operation was done
if ( options.hide ) {
jQuery( elem ).hide();
}
// Reset the properties, if the item has been hidden or shown
if ( options.hide || options.show ) {
for ( p in options.animatedProperties ) {
jQuery.style( elem, p, options.orig[ p ] );
jQuery.removeData( elem, "fxshow" + p, true );
// Toggle data is no longer needed
jQuery.removeData( elem, "toggle" + p, true );
}
}
// Execute the complete function
// in the event that the complete function throws an exception
// we must ensure it won't be called twice. #5684
complete = options.complete;
if ( complete ) {
options.complete = false;
complete.call( elem );
}
}
return false;
} else {
// classical easing cannot be used with an Infinity duration
if ( options.duration == Infinity ) {
this.now = t;
} else {
n = t - this.startTime;
this.state = n / options.duration;
// Perform the easing function, defaults to swing
this.pos = jQuery.easing[ options.animatedProperties[this.prop] ]( this.state, n, 0, 1, options.duration );
this.now = this.start + ( (this.end - this.start) * this.pos );
}
// Perform the next step of the animation
this.update();
}
return true;
}
};
jQuery.extend( jQuery.fx, {
tick: function() {
var timer,
timers = jQuery.timers,
i = 0;
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// Checks the timer has not already been removed
if ( !timer() && timers[ i ] === timer ) {
timers.splice( i--, 1 );
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
},
interval: 13,
stop: function() {
clearInterval( timerId );
timerId = null;
},
speeds: {
slow: 600,
fast: 200,
// Default speed
_default: 400
},
step: {
opacity: function( fx ) {
jQuery.style( fx.elem, "opacity", fx.now );
},
_default: function( fx ) {
if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) {
fx.elem.style[ fx.prop ] = fx.now + fx.unit;
} else {
fx.elem[ fx.prop ] = fx.now;
}
}
}
});
// Ensure props that can't be negative don't go there on undershoot easing
jQuery.each( fxAttrs.concat.apply( [], fxAttrs ), function( i, prop ) {
// exclude marginTop, marginLeft, marginBottom and marginRight from this list
if ( prop.indexOf( "margin" ) ) {
jQuery.fx.step[ prop ] = function( fx ) {
jQuery.style( fx.elem, prop, Math.max(0, fx.now) + fx.unit );
};
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
}
// Try to restore the default display value of an element
function defaultDisplay( nodeName ) {
if ( !elemdisplay[ nodeName ] ) {
var body = document.body,
elem = jQuery( "<" + nodeName + ">" ).appendTo( body ),
display = elem.css( "display" );
elem.remove();
// If the simple way fails,
// get element's real default display by attaching it to a temp iframe
if ( display === "none" || display === "" ) {
// No iframe to use yet, so create it
if ( !iframe ) {
iframe = document.createElement( "iframe" );
iframe.frameBorder = iframe.width = iframe.height = 0;
}
body.appendChild( iframe );
// Create a cacheable copy of the iframe document on first call.
// IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML
// document to it; WebKit & Firefox won't allow reusing the iframe document.
if ( !iframeDoc || !iframe.createElement ) {
iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document;
iframeDoc.write( ( jQuery.support.boxModel ? "<!doctype html>" : "" ) + "<html><body>" );
iframeDoc.close();
}
elem = iframeDoc.createElement( nodeName );
iframeDoc.body.appendChild( elem );
display = jQuery.css( elem, "display" );
body.removeChild( iframe );
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return elemdisplay[ nodeName ];
}
var getOffset,
rtable = /^t(?:able|d|h)$/i,
rroot = /^(?:body|html)$/i;
if ( "getBoundingClientRect" in document.documentElement ) {
getOffset = function( elem, doc, docElem, box ) {
try {
box = elem.getBoundingClientRect();
} catch(e) {}
// 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 {
getOffset = function( elem, doc, docElem ) {
var computedStyle,
offsetParent = elem.offsetParent,
prevOffsetParent = elem,
body = doc.body,
defaultView = doc.defaultView,
prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle,
top = elem.offsetTop,
left = elem.offsetLeft;
while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) {
if ( jQuery.support.fixedPosition && prevComputedStyle.position === "fixed" ) {
break;
}
computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle;
top -= elem.scrollTop;
left -= elem.scrollLeft;
if ( elem === offsetParent ) {
top += elem.offsetTop;
left += elem.offsetLeft;
if ( jQuery.support.doesNotAddBorder && !(jQuery.support.doesAddBorderForTableAndCells && rtable.test(elem.nodeName)) ) {
top += parseFloat( computedStyle.borderTopWidth ) || 0;
left += parseFloat( computedStyle.borderLeftWidth ) || 0;
}
prevOffsetParent = offsetParent;
offsetParent = elem.offsetParent;
}
if ( jQuery.support.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) {
top += parseFloat( computedStyle.borderTopWidth ) || 0;
left += parseFloat( computedStyle.borderLeftWidth ) || 0;
}
prevComputedStyle = computedStyle;
}
if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) {
top += body.offsetTop;
left += body.offsetLeft;
}
if ( jQuery.support.fixedPosition && prevComputedStyle.position === "fixed" ) {
top += Math.max( docElem.scrollTop, body.scrollTop );
left += Math.max( docElem.scrollLeft, body.scrollLeft );
}
return { top: top, left: left };
};
}
jQuery.fn.offset = function( options ) {
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var elem = this[0],
doc = elem && elem.ownerDocument;
if ( !doc ) {
return null;
}
if ( elem === doc.body ) {
return jQuery.offset.bodyOffset( elem );
}
return getOffset( elem, doc, doc.documentElement );
};
jQuery.offset = {
bodyOffset: function( body ) {
var top = body.offsetTop,
left = body.offsetLeft;
if ( jQuery.support.doesNotIncludeMarginInBodyOffset ) {
top += parseFloat( jQuery.css(body, "marginTop") ) || 0;
left += parseFloat( jQuery.css(body, "marginLeft") ) || 0;
}
return { top: top, left: left };
},
setOffset: function( elem, options, i ) {
var position = jQuery.css( elem, "position" );
// set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
var curElem = jQuery( elem ),
curOffset = curElem.offset(),
curCSSTop = jQuery.css( elem, "top" ),
curCSSLeft = jQuery.css( elem, "left" ),
calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1,
props = {}, curPosition = {}, curTop, curLeft;
// need to be able to calculate position if either top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
position: function() {
if ( !this[0] ) {
return null;
}
var elem = this[0],
// Get *real* offsetParent
offsetParent = this.offsetParent(),
// Get correct offsets
offset = this.offset(),
parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset();
// Subtract element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0;
offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0;
// Add offsetParent borders
parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0;
parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0;
// Subtract the two offsets
return {
top: offset.top - parentOffset.top,
left: offset.left - parentOffset.left
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || document.body;
while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( {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 ] :
jQuery.support.boxModel && win.document.documentElement[ method ] ||
win.document.body[ 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 width, height, innerHeight, innerWidth, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
var clientProp = "client" + name,
scrollProp = "scroll" + name,
offsetProp = "offset" + name;
// innerHeight and innerWidth
jQuery.fn[ "inner" + name ] = function() {
var elem = this[0];
return elem ?
elem.style ?
parseFloat( jQuery.css( elem, type, "padding" ) ) :
this[ type ]() :
null;
};
// outerHeight and outerWidth
jQuery.fn[ "outer" + name ] = function( margin ) {
var elem = this[0];
return elem ?
elem.style ?
parseFloat( jQuery.css( elem, type, margin ? "margin" : "border" ) ) :
this[ type ]() :
null;
};
jQuery.fn[ type ] = function( value ) {
return jQuery.access( this, function( elem, type, value ) {
var doc, docElemProp, orig, ret;
if ( jQuery.isWindow( elem ) ) {
// 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat
doc = elem.document;
docElemProp = doc.documentElement[ clientProp ];
return jQuery.support.boxModel && docElemProp ||
doc.body && doc.body[ clientProp ] || docElemProp;
}
// Get document width or height
if ( elem.nodeType === 9 ) {
// Either scroll[Width/Height] or offset[Width/Height], whichever is greater
doc = elem.documentElement;
// when a window > document, IE6 reports a offset[Width/Height] > client[Width/Height]
// so we can't use max, as it'll choose the incorrect offset[Width/Height]
// instead we use the correct client[Width/Height]
// support:IE6
if ( doc[ clientProp ] >= doc[ scrollProp ] ) {
return doc[ clientProp ];
}
return Math.max(
elem.body[ scrollProp ], doc[ scrollProp ],
elem.body[ offsetProp ], doc[ offsetProp ]
);
}
// Get width or height on the element
if ( value === undefined ) {
orig = jQuery.css( elem, type );
ret = parseFloat( orig );
return jQuery.isNumeric( ret ) ? ret : orig;
}
// Set the width or height on the element
jQuery( elem ).css( type, value );
}, type, value, arguments.length, 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 ); |
packages/material-ui-icons/src/CheckCircleOutlineSharp.js | allanalexandre/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm0 18c-4.41 0-8-3.59-8-8s3.59-8 8-8 8 3.59 8 8-3.59 8-8 8z" /><path d="M16.59 7.58L10 14.17l-2.59-2.58L6 13l4 4 8-8z" /></g></React.Fragment>
, 'CheckCircleOutlineSharp');
|
src/components/Contact/index.js | ndlib/usurper | import React from 'react'
import PropTypes from 'prop-types'
import * as helper from 'constants/HelperFunctions'
const Contact = (props) => {
let name
if (props.name) {
name = <p itemProp='name' className='name'>{props.name.trim()}</p>
}
let title
if (props.title) {
title = (<p itemProp='jobTitle' className='title'>{props.title.trim()}</p>)
}
let phone
if (props.phone) {
phone = (
<span>
<a
href={helper.formatPhoneLink(props.phone)}
itemProp='telephone'
>
{props.phone.trim()}
</a><br />
</span>
)
}
let email
if (props.email) {
email = (
<span>
<a
href={'mailto:' + props.email}
itemProp='email'
>
{props.email.trim()}
</a><br />
</span>
)
}
let addr1
if (props.addr1) {
addr1 = <span itemProp='streetAddress'>{props.addr1.trim()}<br /></span>
}
let addr2
if (props.addr2) {
addr2 = <span>{props.addr2.trim()}</span>
}
let address
if (addr1 || addr2) {
address = (
<div itemScope itemType='http://schema.org/PostalAddress' itemProp='address'>
{addr1}
{addr2}
</div>
)
}
return (
<address className='contact' aria-label={props.name.trim()} itemScope itemType='http://schema.org/Person'>
{name}
{title}
{phone}
{email}
{address}
</address>
)
}
Contact.propTypes = {
name: PropTypes.string,
title: PropTypes.string,
phone: PropTypes.string,
email: PropTypes.string,
addr1: PropTypes.string,
addr2: PropTypes.string,
}
export default Contact
|
src/StyleContext.js | kriasoft/isomorphic-style-loader | /**
* Isomorphic CSS style loader for Webpack
*
* Copyright © 2015-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'
const StyleContext = React.createContext({
insertCss: null,
})
export default StyleContext
|
packages/components/src/ResourceList/ResourceList.stories.js | Talend/ui | import React from 'react';
import PropTypes from 'prop-types';
import { useTranslation } from 'react-i18next';
import { action } from '@storybook/addon-actions';
import ResourceList from './ResourceList.component';
import Icon from '../Icon';
const collection = [
{
id: 0,
name: 'Title with few actions',
modified: '2016-09-22',
icon: 'talend-file-xls-o',
author: 'First Author',
flags: ['CERTIFIED', 'FAVORITE'],
},
{
id: 1,
name: 'Title with lot of actions',
modified: '2016-09-22',
icon: 'talend-file-xls-o',
author: 'Second Author',
},
{
id: 2,
name: 'Title with persistant actions',
modified: '2016-09-22',
author: 'Jean-Pierre DUPONT',
icon: 'talend-file-xls-o',
flags: ['FAVORITE'],
},
{
id: 3,
name: 'Title with icon',
modified: '2016-09-22',
author: 'Third Author',
icon: 'talend-file-xls-o',
flags: ['CERTIFIED'],
},
{
id: 4,
name: 'Title in input mode',
modified: '2016-09-22',
author: 'Jean-Pierre DUPONT',
icon: 'talend-file-xls-o',
},
{
id: 5,
name: 'Title with long long long long long long long long long long long text',
modified: '2016-09-22',
author: 'Jean-Pierre DUPONT with super super super long text',
icon: 'talend-file-xls-o',
flags: ['CERTIFIED', 'FAVORITE'],
},
{
id: 5,
name: 'Without author',
icon: 'talend-file-xls-o',
flags: ['CERTIFIED', 'FAVORITE'],
},
];
const simpleCollection = [
{
icon: 'talend-file-xls-o',
id: 0,
name: 'Title with few actions',
subtitle:
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. In tempor felis ultricies felis molestie placerat quis sit amet felis.',
},
{
icon: 'talend-file-xls-o',
id: 1,
name: 'Title with lot of actions',
subtitle:
'Duis eros erat, ultricies sit amet tincidunt at, placerat quis ipsum. Cras nisi felis, condimentum sodales odio aliquet, accumsan molestie velit.',
},
{
icon: 'talend-file-xls-o',
id: 2,
name: 'Title with persistant actions',
subtitle:
'Duis eros erat, ultricies sit amet tincidunt at, placerat quis ipsum. Cras nisi felis, condimentum sodales odio aliquet, accumsan molestie velit.',
},
{
icon: 'talend-file-xls-o',
id: 3,
name: 'Title with icon',
subtitle:
'Curabitur ac nulla ut augue vulputate aliquet vitae at est. Curabitur massa lacus, sagittis eu cursus vel, consectetur ultricies nibh.',
},
{
icon: 'talend-file-xls-o',
id: 4,
name: 'Title in input mode',
subtitle:
'Curabitur ac porttitor nunc. Quisque molestie sollicitudin nisi sed tincidunt. Nam facilisis enim nec urna pretium, vel porttitor nisl venenatis.',
},
{
icon: 'talend-file-xls-o',
id: 5,
subtitle:
'Cras enim ligula, ornare at lorem sed, hendrerit tempor magna. Integer ac sapien sapien. Nam scelerisque tellus at ligula pharetra vulputate.',
},
{
icon: 'talend-file-xls-o',
id: 6,
name: 'Without author',
subtitle: 'Vestibulum felis nulla, commodo sed sem ac, maximus sollicitudin libero.',
},
];
export const preparations = [
{
id: 0,
name: 'Chief Marketing Officer',
createdBy: 'Karson Cartwright',
path: 'Group/Program/Solution',
},
{
id: 1,
name: 'Chief Web Technician',
createdBy: 'Rogers Gutkowski',
path: 'M/Program/Solution',
},
{
id: 3,
name: 'Customer Identity Developer',
createdBy: 'Zoey Jones',
path: '../Operations/Research/Directives',
},
{
id: 4,
name: 'Dynamic Response Consultant',
createdBy: 'Santiago Schmitt Jr.',
path: 'Quality/Security',
},
];
export const pipelines = [
{
id: 0,
name: 'Central Factors Facilitator',
createdBy:
'Darlene Koch Darlene Koch Darlene Koch Darlene Koch Darlene Koch Darlene Koch Darlene Koch Darlene Koch Darlene Koch',
usedAs: ['source', 'destination'],
},
{
id: 1,
name: 'Dynamic Solutions Strategist',
createdBy: 'Earnestine Rath',
usedAs: ['source'],
},
{
id: 2,
name: 'International Brand Engineer',
createdBy: 'Deonte Blick',
usedAs: ['source', 'destination'],
},
{
id: 3,
name: 'National Data Planner',
createdBy: 'Jaron Murray',
usedAs: ['destination'],
},
{
id: 4,
name: 'Regional Marketing Liaison',
createdBy: 'Earnestine Rath',
usedAs: ['source', 'destination'],
},
];
const commonProps = {
onRowClick: action('onRowClick'),
};
export function Preparation({ name, createdBy, path }) {
const { t } = useTranslation();
return (
<div className="preparation">
<h3>{name}</h3>
<dl>
<div>
<dt>
<Icon name="talend-user-circle" />
{t('CREATED_BY', { defaultValue: 'Created by' })}
</dt>
<dd>{createdBy}</dd>
</div>
<div>
<dt className="icon-only">
<Icon name="talend-folder-closed" />
<span className="sr-only">{t('Path', { defaultValue: 'Path' })}</span>
</dt>
<dd>{path}</dd>
</div>
</dl>
</div>
);
}
Preparation.propTypes = {
name: PropTypes.string,
createdBy: PropTypes.string,
path: PropTypes.string,
};
export function Pipeline({ name, createdBy, usedAs }) {
const { t } = useTranslation();
const joinedItemsMessage = t('JOIN_ITEMS', {
defaultValue: '{{item1}} and {{item2}}',
item1: usedAs[0],
item2: usedAs[1],
});
return (
<div className="pipeline">
<h3>{name}</h3>
<dl>
<div>
<dt>
<Icon name="talend-user-circle" />
{t('CREATED_BY', { defaultValue: 'Created by' })}
</dt>
<dd>{createdBy}</dd>
</div>
<div>
<dt>
<Icon name={usedAs.length > 1 ? 'talend-flow-source-target' : 'talend-flow-source-o'} />
{t('USED_AS', { defaultValue: 'Used as' })}
</dt>
<dd>{usedAs.length === 2 ? joinedItemsMessage : usedAs[0]}</dd>
</div>
</dl>
</div>
);
}
Pipeline.propTypes = {
name: PropTypes.string,
createdBy: PropTypes.string,
usedAs: PropTypes.array,
};
export function FilteredResourceList(props) {
const { t } = useTranslation();
const [filter, setFilter] = React.useState();
const filteredCollection = React.useMemo(
() =>
filter
? props.collection.filter(item => item.name.toLowerCase().includes(filter.toLowerCase()))
: props.collection,
[filter],
);
return (
<ResourceList
{...commonProps}
toolbar={{
name: {
label: t('FILTER', {
defaultValue: 'Find a {{type, lowercase}}',
type: props?.renderAs?.name,
}),
value: filter,
onChange: event => setFilter(event.target.value),
},
}}
{...props}
collection={filteredCollection}
/>
);
}
export default {
title: 'Data/List/ResourceList',
excludeStories: ['preparations', 'pipelines', 'Preparation', 'Pipeline', 'FilteredResourceList'],
};
export const Default = () => <ResourceList {...commonProps} collection={collection} />;
export const Simple = () => <ResourceList {...commonProps} collection={simpleCollection} />;
export const Preparations = () => (
<ResourceList {...commonProps} collection={preparations} renderAs={Preparation} />
);
export const WithRowProps = () => (
<ResourceList
{...commonProps}
collection={preparations}
renderAs={Preparation}
rowProps={{ style: { color: 'red' }, 'data-feature': 'my.data.feature' }}
/>
);
export const FilteredPipelines = () => (
<FilteredResourceList collection={pipelines} renderAs={Pipeline} />
);
|
node_modules/lite-server/node_modules/browser-sync/node_modules/bs-recipes/recipes/webpack.react-hot-loader/app/js/main.js | bobangajicsm/fut-scores | import React from 'react';
// It's important to not define HelloWorld component right in this file
// because in that case it will do full page reload on change
import HelloWorld from './HelloWorld.jsx';
React.render(<HelloWorld />, document.getElementById('react-root'));
|
src/containers/app/CreateAppType.js | kryptnostic/gallery | import React from 'react';
import PropTypes from 'prop-types';
import Immutable from 'immutable';
import Select from 'react-select';
import { Models } from 'lattice';
import { FormControl, FormGroup, ControlLabel, Button, Alert } from 'react-bootstrap';
import { connect } from 'react-redux';
import { bindActionCreators } from 'redux';
import { fetchAllEntityTypesRequest } from '../edm/EdmActionFactory';
import AsyncContent from '../../components/asynccontent/AsyncContent';
import { createAppTypeRequest } from './AppActionFactory';
const {
AppTypeBuilder
} = Models;
class CreateAppType extends React.Component {
static propTypes = {
actions: PropTypes.shape({
createAppTypeRequest: PropTypes.func.isRequired,
fetchAllEntityTypesRequest: PropTypes.func.isRequired
}).isRequired,
createAppTypeAsyncState: PropTypes.instanceOf(Immutable.Map).isRequired,
entityTypes: PropTypes.instanceOf(Immutable.Map).isRequired
}
constructor(props) {
super(props);
this.state = {
description: '',
entityTypeId: null,
isError: false,
name: '',
namespace: '',
title: ''
};
}
componentDidMount() {
this.props.actions.fetchAllEntityTypesRequest();
}
getEntityTypeOptions() {
const options = [];
this.props.entityTypes.forEach((entityType) => {
if (!entityType.isEmpty()) {
options.push({
value: entityType.get('id'),
label: entityType.get('title')
});
}
});
return options;
}
onTitleChange = (event) => {
this.setState({
title: event.target.value.trim()
});
};
onNameChange = (event) => {
this.setState({
name: event.target.value.trim()
});
};
onNamespaceChange = (event) => {
this.setState({
namespace: event.target.value.trim()
});
};
onDescriptionChange = (event) => {
this.setState({
description: event.target.value.trim()
});
};
onEntityTypeIdChange = (option) => {
const entityTypeId = (option) ? option.value : null;
this.setState({ entityTypeId });
}
onSubmit = () => {
const { title, description, name, namespace, entityTypeId } = this.state;
try {
const appType = (new AppTypeBuilder())
.setDescription(description)
.setEntityTypeId(entityTypeId)
.setTitle(title)
.setType({ namespace, name })
.build();
this.props.actions.createAppTypeRequest(appType);
}
catch (e) {
this.setState({ isError: true });
// Requires return statement still? Not tested yet becuase backend down.
// return;
}
}
renderPending = () => {
const { isError } = this.state;
return (
<form onSubmit={this.onSubmit}>
<FormGroup>
<ControlLabel>Namespace</ControlLabel>
<FormControl type="text" onChange={this.onNamespaceChange} />
</FormGroup>
<FormGroup>
<ControlLabel>Name</ControlLabel>
<FormControl type="text" onChange={this.onNameChange} />
</FormGroup>
<FormGroup>
<ControlLabel>Title</ControlLabel>
<FormControl type="text" onChange={this.onTitleChange} />
</FormGroup>
<FormGroup>
<ControlLabel>Description</ControlLabel>
<FormControl componentClass="textarea" onChange={this.onDescriptionChange} />
</FormGroup>
<FormGroup>
<ControlLabel>Entity Type Id</ControlLabel>
<Select
value={this.state.entityTypeId}
options={this.getEntityTypeOptions()}
onChange={this.onEntityTypeIdChange} />
</FormGroup>
<br />
<Button type="submit" bsStyle="primary">Create App Type</Button>
{ isError ? (<div style={{ color: 'red' }} >
<br />
Please check your inputs
</div>) : null}
</form>
);
};
renderSuccess = () => {
return (
<Alert bsStyle="success">
Successfully saved App Type
</Alert>
);
};
render() {
return (
<AsyncContent
content={this.renderSuccess}
errorMessage={this.props.createAppTypeAsyncState.get('errorMessage')}
pendingContent={this.renderPending()}
status={this.props.createAppTypeAsyncState.get('status')} />
);
}
}
function mapStateToProps(state) {
const createAppTypeAsyncState = state.getIn(['app', 'createAppTypeAsyncState']);
const entityTypes = state.getIn(['edm', 'entityTypes'], Immutable.Map());
return {
createAppTypeAsyncState,
entityTypes
};
}
function mapDispatchToProps(dispatch) {
const actions = {
createAppTypeRequest,
fetchAllEntityTypesRequest
};
return {
actions: bindActionCreators(actions, dispatch)
};
}
export default connect(mapStateToProps, mapDispatchToProps)(CreateAppType);
|
node_modules/react-dom/lib/ReactChildReconciler.js | bengimbel/Solstice-React-Contacts-Project | /**
* 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.
*
*/
'use strict';
var ReactReconciler = require('./ReactReconciler');
var instantiateReactComponent = require('./instantiateReactComponent');
var KeyEscapeUtils = require('./KeyEscapeUtils');
var shouldUpdateReactComponent = require('./shouldUpdateReactComponent');
var traverseAllChildren = require('./traverseAllChildren');
var warning = require('fbjs/lib/warning');
var ReactComponentTreeHook;
if (typeof process !== 'undefined' && process.env && process.env.NODE_ENV === 'test') {
// Temporary hack.
// Inline requires don't work well with Jest:
// https://github.com/facebook/react/issues/7240
// Remove the inline requires when we don't need them anymore:
// https://github.com/facebook/react/pull/7178
ReactComponentTreeHook = require('react/lib/ReactComponentTreeHook');
}
function instantiateChild(childInstances, child, name, selfDebugID) {
// We found a component instance.
var keyUnique = childInstances[name] === undefined;
if (process.env.NODE_ENV !== 'production') {
if (!ReactComponentTreeHook) {
ReactComponentTreeHook = require('react/lib/ReactComponentTreeHook');
}
if (!keyUnique) {
process.env.NODE_ENV !== 'production' ? warning(false, '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.%s', KeyEscapeUtils.unescape(name), ReactComponentTreeHook.getStackAddendumByID(selfDebugID)) : void 0;
}
}
if (child != null && keyUnique) {
childInstances[name] = instantiateReactComponent(child, true);
}
}
/**
* 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, selfDebugID) // 0 in production and for roots
{
if (nestedChildNodes == null) {
return null;
}
var childInstances = {};
if (process.env.NODE_ENV !== 'production') {
traverseAllChildren(nestedChildNodes, function (childInsts, child, name) {
return instantiateChild(childInsts, child, name, selfDebugID);
}, childInstances);
} else {
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, mountImages, removedNodes, transaction, hostParent, hostContainerInfo, context, selfDebugID) // 0 in production and for roots
{
// 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.getHostNode(prevChild);
ReactReconciler.unmountComponent(prevChild, false);
}
// The child must be instantiated before it's mounted.
var nextChildInstance = instantiateReactComponent(nextElement, true);
nextChildren[name] = nextChildInstance;
// Creating mount image now ensures refs are resolved in right order
// (see https://github.com/facebook/react/pull/7101 for explanation).
var nextChildMountImage = ReactReconciler.mountComponent(nextChildInstance, transaction, hostParent, hostContainerInfo, context, selfDebugID);
mountImages.push(nextChildMountImage);
}
}
// 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.getHostNode(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; |
assets/jquery Validation/lib/jquery-1.7.2.js | nasirkhan/dghs-hrm | /*!
* jQuery JavaScript Library v1.7.2
* 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: Wed Mar 21 12:46:34 2012 -0700
*/
(function( window, undefined ) {
// Use the correct document accordingly with window argument (sandbox)
var document = window.document,
navigator = window.navigator,
location = window.location;
var jQuery = (function() {
// Define a local copy of jQuery
var jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context, rootjQuery );
},
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// A central reference to the root jQuery(document)
rootjQuery,
// A simple way to check for HTML strings or ID strings
// Prioritize #id over <tag> to avoid XSS via location.hash (#9521)
quickExpr = /^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,
// Check if a string has a non-whitespace character in it
rnotwhite = /\S/,
// Used for trimming whitespace
trimLeft = /^\s+/,
trimRight = /\s+$/,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/,
// JSON RegExp
rvalidchars = /^[\],:{}\s]*$/,
rvalidescape = /\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,
rvalidtokens = /"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,
rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g,
// Useragent RegExp
rwebkit = /(webkit)[ \/]([\w.]+)/,
ropera = /(opera)(?:.*version)?[ \/]([\w.]+)/,
rmsie = /(msie) ([\w.]+)/,
rmozilla = /(mozilla)(?:.*? rv:([\w.]+))?/,
// Matches dashed string for camelizing
rdashAlpha = /-([a-z]|[0-9])/ig,
rmsPrefix = /^-ms-/,
// Used by jQuery.camelCase as callback to replace()
fcamelCase = function( all, letter ) {
return ( letter + "" ).toUpperCase();
},
// Keep a UserAgent string for use with jQuery.browser
userAgent = navigator.userAgent,
// For matching the engine and version of the browser
browserMatch,
// The deferred used on DOM ready
readyList,
// The ready event handler
DOMContentLoaded,
// Save a reference to some core methods
toString = Object.prototype.toString,
hasOwn = Object.prototype.hasOwnProperty,
push = Array.prototype.push,
slice = Array.prototype.slice,
trim = String.prototype.trim,
indexOf = Array.prototype.indexOf,
// [[Class]] -> type pairs
class2type = {};
jQuery.fn = jQuery.prototype = {
constructor: jQuery,
init: function( selector, context, rootjQuery ) {
var match, elem, ret, doc;
// Handle $(""), $(null), or $(undefined)
if ( !selector ) {
return this;
}
// Handle $(DOMElement)
if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
}
// The body element only exists once, optimize finding it
if ( selector === "body" && !context && document.body ) {
this.context = document;
this[0] = document.body;
this.selector = selector;
this.length = 1;
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
// Are we dealing with HTML string or an ID?
if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) {
// Assume that strings that start and end with <> are HTML and skip the regex check
match = [ null, selector, null ];
} else {
match = quickExpr.exec( selector );
}
// Verify a match, and that no context was specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
context = context instanceof jQuery ? context[0] : context;
doc = ( context ? context.ownerDocument || context : document );
// If a single string is passed in and it's a single tag
// just do a createElement and skip the rest
ret = rsingleTag.exec( selector );
if ( ret ) {
if ( jQuery.isPlainObject( context ) ) {
selector = [ document.createElement( ret[1] ) ];
jQuery.fn.attr.call( selector, context, true );
} else {
selector = [ doc.createElement( ret[1] ) ];
}
} else {
ret = jQuery.buildFragment( [ match[1] ], [ doc ] );
selector = ( ret.cacheable ? jQuery.clone(ret.fragment) : ret.fragment ).childNodes;
}
return jQuery.merge( this, selector );
// HANDLE: $("#id")
} else {
elem = document.getElementById( match[2] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return ( context || rootjQuery ).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return this.constructor( context ).find( selector );
}
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if ( selector.selector !== undefined ) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The current version of jQuery being used
jquery: "1.7.2",
// The default length of a jQuery object is 0
length: 0,
// The number of elements contained in the matched element set
size: function() {
return this.length;
},
toArray: function() {
return slice.call( this, 0 );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this[ this.length + num ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems, name, selector ) {
// Build a new jQuery matched element set
var ret = this.constructor();
if ( jQuery.isArray( elems ) ) {
push.apply( ret, elems );
} else {
jQuery.merge( ret, elems );
}
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
if ( name === "find" ) {
ret.selector = this.selector + ( this.selector ? " " : "" ) + selector;
} else if ( name ) {
ret.selector = this.selector + "." + name + "(" + selector + ")";
}
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Attach the listeners
jQuery.bindReady();
// Add the callback
readyList.add( fn );
return this;
},
eq: function( i ) {
i = +i;
return i === -1 ?
this.slice( i ) :
this.slice( i, i + 1 );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
slice: function() {
return this.pushStack( slice.apply( this, arguments ),
"slice", slice.call(arguments).join(",") );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || this.constructor(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
var options, name, src, copy, copyIsArray, clone,
target = arguments[0] || {},
i = 1,
length = arguments.length,
deep = false;
// Handle a deep copy situation
if ( typeof target === "boolean" ) {
deep = target;
target = arguments[1] || {};
// skip the boolean and the target
i = 2;
}
// Handle case when target is a string or something (possible in deep copy)
if ( typeof target !== "object" && !jQuery.isFunction(target) ) {
target = {};
}
// extend jQuery itself if only one argument is passed
if ( length === i ) {
target = this;
--i;
}
for ( ; i < length; i++ ) {
// Only deal with non-null/undefined values
if ( (options = arguments[ i ]) != null ) {
// Extend the base object
for ( name in options ) {
src = target[ name ];
copy = options[ name ];
// Prevent never-ending loop
if ( target === copy ) {
continue;
}
// Recurse if we're merging plain objects or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) {
if ( copyIsArray ) {
copyIsArray = false;
clone = src && jQuery.isArray(src) ? src : [];
} else {
clone = src && jQuery.isPlainObject(src) ? src : {};
}
// Never move original objects, clone them
target[ name ] = jQuery.extend( deep, clone, copy );
// Don't bring in undefined values
} else if ( copy !== undefined ) {
target[ name ] = copy;
}
}
}
}
// Return the modified object
return target;
};
jQuery.extend({
noConflict: function( deep ) {
if ( window.$ === jQuery ) {
window.$ = _$;
}
if ( deep && window.jQuery === jQuery ) {
window.jQuery = _jQuery;
}
return jQuery;
},
// Is the DOM ready to be used? Set to true once it occurs.
isReady: false,
// A counter to track how many items to wait for before
// the ready event fires. See #6781
readyWait: 1,
// Hold (or release) the ready event
holdReady: function( hold ) {
if ( hold ) {
jQuery.readyWait++;
} else {
jQuery.ready( true );
}
},
// Handle when the DOM is ready
ready: function( wait ) {
// Either a released hold or an DOMready/load event and not yet ready
if ( (wait === true && !--jQuery.readyWait) || (wait !== true && !jQuery.isReady) ) {
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready, 1 );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If a normal DOM Ready event fired, decrement, and wait if need be
if ( wait !== true && --jQuery.readyWait > 0 ) {
return;
}
// If there are functions bound, to execute
readyList.fireWith( document, [ jQuery ] );
// Trigger any bound ready events
if ( jQuery.fn.trigger ) {
jQuery( document ).trigger( "ready" ).off( "ready" );
}
}
},
bindReady: function() {
if ( readyList ) {
return;
}
readyList = jQuery.Callbacks( "once memory" );
// Catch cases where $(document).ready() is called after the
// browser event has already occurred.
if ( document.readyState === "complete" ) {
// Handle it asynchronously to allow scripts the opportunity to delay ready
return setTimeout( jQuery.ready, 1 );
}
// Mozilla, Opera and webkit nightlies currently support this event
if ( document.addEventListener ) {
// Use the handy event callback
document.addEventListener( "DOMContentLoaded", DOMContentLoaded, false );
// A fallback to window.onload, that will always work
window.addEventListener( "load", jQuery.ready, false );
// If IE event model is used
} else if ( document.attachEvent ) {
// ensure firing before onload,
// maybe late but safe also for iframes
document.attachEvent( "onreadystatechange", DOMContentLoaded );
// A fallback to window.onload, that will always work
window.attachEvent( "onload", jQuery.ready );
// If IE and not a frame
// continually check to see if the document is ready
var toplevel = false;
try {
toplevel = window.frameElement == null;
} catch(e) {}
if ( document.documentElement.doScroll && toplevel ) {
doScrollCheck();
}
}
},
// See test/unit/core.js for details concerning isFunction.
// Since version 1.3, DOM methods and functions like alert
// aren't supported. They return false on IE (#2968).
isFunction: function( obj ) {
return jQuery.type(obj) === "function";
},
isArray: Array.isArray || function( obj ) {
return jQuery.type(obj) === "array";
},
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[ toString.call(obj) ] || "object";
},
isPlainObject: function( obj ) {
// Must be an Object.
// Because of IE, we also have to check the presence of the constructor property.
// Make sure that DOM nodes and window objects don't pass through, as well
if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) {
return false;
}
try {
// Not own constructor property must be Object
if ( obj.constructor &&
!hasOwn.call(obj, "constructor") &&
!hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) {
return false;
}
} catch ( e ) {
// IE8,9 Will throw exceptions on certain host objects #9897
return false;
}
// Own properties are enumerated firstly, so to speed up,
// if last one is own, then all properties are own.
var key;
for ( key in obj ) {}
return key === undefined || hasOwn.call( obj, key );
},
isEmptyObject: function( obj ) {
for ( var name in obj ) {
return false;
}
return true;
},
error: function( msg ) {
throw new Error( msg );
},
parseJSON: function( data ) {
if ( typeof data !== "string" || !data ) {
return null;
}
// Make sure leading/trailing whitespace is removed (IE can't handle it)
data = jQuery.trim( data );
// Attempt to parse using the native JSON parser first
if ( window.JSON && window.JSON.parse ) {
return window.JSON.parse( data );
}
// Make sure the incoming data is actual JSON
// Logic borrowed from http://json.org/json2.js
if ( rvalidchars.test( data.replace( rvalidescape, "@" )
.replace( rvalidtokens, "]" )
.replace( rvalidbraces, "")) ) {
return ( new Function( "return " + data ) )();
}
jQuery.error( "Invalid JSON: " + data );
},
// Cross-browser xml parsing
parseXML: function( data ) {
if ( typeof data !== "string" || !data ) {
return null;
}
var xml, tmp;
try {
if ( window.DOMParser ) { // Standard
tmp = new DOMParser();
xml = tmp.parseFromString( data , "text/xml" );
} else { // IE
xml = new ActiveXObject( "Microsoft.XMLDOM" );
xml.async = "false";
xml.loadXML( data );
}
} catch( e ) {
xml = undefined;
}
if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) {
jQuery.error( "Invalid XML: " + data );
}
return xml;
},
noop: function() {},
// Evaluates a script in a global context
// Workarounds based on findings by Jim Driscoll
// http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context
globalEval: function( data ) {
if ( data && rnotwhite.test( data ) ) {
// We use execScript on Internet Explorer
// We use an anonymous function so that context is window
// rather than jQuery in Firefox
( window.execScript || function( data ) {
window[ "eval" ].call( window, data );
} )( data );
}
},
// Convert dashed to camelCase; used by the css and data modules
// Microsoft forgot to hump their vendor prefix (#9572)
camelCase: function( string ) {
return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase );
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase();
},
// args is for internal usage only
each: function( object, callback, args ) {
var name, i = 0,
length = object.length,
isObj = length === undefined || jQuery.isFunction( object );
if ( args ) {
if ( isObj ) {
for ( name in object ) {
if ( callback.apply( object[ name ], args ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.apply( object[ i++ ], args ) === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isObj ) {
for ( name in object ) {
if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.call( object[ i ], i, object[ i++ ] ) === false ) {
break;
}
}
}
}
return object;
},
// Use native String.trim function wherever possible
trim: trim ?
function( text ) {
return text == null ?
"" :
trim.call( text );
} :
// Otherwise use our own trimming functionality
function( text ) {
return text == null ?
"" :
text.toString().replace( trimLeft, "" ).replace( trimRight, "" );
},
// results is for internal usage only
makeArray: function( array, results ) {
var ret = results || [];
if ( array != null ) {
// The window, strings (and functions) also have 'length'
// Tweaked logic slightly to handle Blackberry 4.7 RegExp issues #6930
var type = jQuery.type( array );
if ( array.length == null || type === "string" || type === "function" || type === "regexp" || jQuery.isWindow( array ) ) {
push.call( ret, array );
} else {
jQuery.merge( ret, array );
}
}
return ret;
},
inArray: function( elem, array, i ) {
var len;
if ( array ) {
if ( indexOf ) {
return indexOf.call( array, elem, i );
}
len = array.length;
i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0;
for ( ; i < len; i++ ) {
// Skip accessing in sparse arrays
if ( i in array && array[ i ] === elem ) {
return i;
}
}
}
return -1;
},
merge: function( first, second ) {
var i = first.length,
j = 0;
if ( typeof second.length === "number" ) {
for ( var l = second.length; j < l; j++ ) {
first[ i++ ] = second[ j ];
}
} else {
while ( second[j] !== undefined ) {
first[ i++ ] = second[ j++ ];
}
}
first.length = i;
return first;
},
grep: function( elems, callback, inv ) {
var ret = [], retVal;
inv = !!inv;
// Go through the array, only saving the items
// that pass the validator function
for ( var i = 0, length = elems.length; i < length; i++ ) {
retVal = !!callback( elems[ i ], i );
if ( inv !== retVal ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var value, key, ret = [],
i = 0,
length = elems.length,
// jquery objects are treated as arrays
isArray = elems instanceof jQuery || length !== undefined && typeof length === "number" && ( ( length > 0 && elems[ 0 ] && elems[ length -1 ] ) || length === 0 || jQuery.isArray( elems ) ) ;
// Go through the array, translating each of the items to their
if ( isArray ) {
for ( ; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
// Go through every key on the object,
} else {
for ( key in elems ) {
value = callback( elems[ key ], key, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
}
// Flatten any nested arrays
return ret.concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
// Bind a function to a context, optionally partially applying any
// arguments.
proxy: function( fn, context ) {
if ( typeof context === "string" ) {
var tmp = fn[ context ];
context = fn;
fn = tmp;
}
// Quick check to determine if target is callable, in the spec
// this throws a TypeError, but we will just return undefined.
if ( !jQuery.isFunction( fn ) ) {
return undefined;
}
// Simulated bind
var args = slice.call( arguments, 2 ),
proxy = function() {
return fn.apply( context, args.concat( slice.call( arguments ) ) );
};
// Set the guid of unique handler to the same of original handler, so it can be removed
proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;
return proxy;
},
// Mutifunctional method to get and set values to a collection
// The value/s can optionally be executed if it's a function
access: function( elems, 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();
},
// Use of jQuery.browser is frowned upon.
// More details: http://docs.jquery.com/Utilities/jQuery.browser
uaMatch: function( ua ) {
ua = ua.toLowerCase();
var match = rwebkit.exec( ua ) ||
ropera.exec( ua ) ||
rmsie.exec( ua ) ||
ua.indexOf("compatible") < 0 && rmozilla.exec( ua ) ||
[];
return { browser: match[1] || "", version: match[2] || "0" };
},
sub: function() {
function jQuerySub( selector, context ) {
return new jQuerySub.fn.init( selector, context );
}
jQuery.extend( true, jQuerySub, this );
jQuerySub.superclass = this;
jQuerySub.fn = jQuerySub.prototype = this();
jQuerySub.fn.constructor = jQuerySub;
jQuerySub.sub = this.sub;
jQuerySub.fn.init = function init( selector, context ) {
if ( context && context instanceof jQuery && !(context instanceof jQuerySub) ) {
context = jQuerySub( context );
}
return jQuery.fn.init.call( this, selector, context, rootjQuerySub );
};
jQuerySub.fn.init.prototype = jQuerySub.fn;
var rootjQuerySub = jQuerySub(document);
return jQuerySub;
},
browser: {}
});
// Populate the class2type map
jQuery.each("Boolean Number String Function Array Date RegExp Object".split(" "), function(i, name) {
class2type[ "[object " + name + "]" ] = name.toLowerCase();
});
browserMatch = jQuery.uaMatch( userAgent );
if ( browserMatch.browser ) {
jQuery.browser[ browserMatch.browser ] = true;
jQuery.browser.version = browserMatch.version;
}
// Deprecated, use jQuery.browser.webkit instead
if ( jQuery.browser.webkit ) {
jQuery.browser.safari = true;
}
// IE doesn't match non-breaking spaces with \s
if ( rnotwhite.test( "\xA0" ) ) {
trimLeft = /^[\s\xA0]+/;
trimRight = /[\s\xA0]+$/;
}
// All jQuery objects should point back to these
rootjQuery = jQuery(document);
// Cleanup functions for the document ready method
if ( document.addEventListener ) {
DOMContentLoaded = function() {
document.removeEventListener( "DOMContentLoaded", DOMContentLoaded, false );
jQuery.ready();
};
} else if ( document.attachEvent ) {
DOMContentLoaded = function() {
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( document.readyState === "complete" ) {
document.detachEvent( "onreadystatechange", DOMContentLoaded );
jQuery.ready();
}
};
}
// The DOM ready check for Internet Explorer
function doScrollCheck() {
if ( jQuery.isReady ) {
return;
}
try {
// If IE is used, use the trick by Diego Perini
// http://javascript.nwbox.com/IEContentLoaded/
document.documentElement.doScroll("left");
} catch(e) {
setTimeout( doScrollCheck, 1 );
return;
}
// and execute any waiting functions
jQuery.ready();
}
return jQuery;
})();
// String to Object flags format cache
var flagsCache = {};
// Convert String-formatted flags into Object-formatted ones and store in cache
function createFlags( flags ) {
var object = flagsCache[ flags ] = {},
i, length;
flags = flags.split( /\s+/ );
for ( i = 0, length = flags.length; i < length; i++ ) {
object[ flags[i] ] = true;
}
return object;
}
/*
* Create a callback list using the following parameters:
*
* flags: an optional list of space-separated flags that will change how
* the callback list behaves
*
* By default a callback list will act like an event callback list and can be
* "fired" multiple times.
*
* Possible flags:
*
* once: will ensure the callback list can only be fired once (like a Deferred)
*
* memory: will keep track of previous values and will call any callback added
* after the list has been fired right away with the latest "memorized"
* values (like a Deferred)
*
* unique: will ensure a callback can only be added once (no duplicate in the list)
*
* stopOnFalse: interrupt callings when a callback returns false
*
*/
jQuery.Callbacks = function( flags ) {
// Convert flags from String-formatted to Object-formatted
// (we check in cache first)
flags = flags ? ( flagsCache[ flags ] || createFlags( flags ) ) : {};
var // Actual callback list
list = [],
// Stack of fire calls for repeatable lists
stack = [],
// Last fire value (for non-forgettable lists)
memory,
// Flag to know if list 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,
// Add one or several callbacks to the list
add = function( args ) {
var i,
length,
elem,
type,
actual;
for ( i = 0, length = args.length; i < length; i++ ) {
elem = args[ i ];
type = jQuery.type( elem );
if ( type === "array" ) {
// Inspect recursively
add( elem );
} else if ( type === "function" ) {
// Add if not in unique mode and callback is not in
if ( !flags.unique || !self.has( elem ) ) {
list.push( elem );
}
}
}
},
// Fire callbacks
fire = function( context, args ) {
args = args || [];
memory = !flags.memory || [ context, args ];
fired = true;
firing = true;
firingIndex = firingStart || 0;
firingStart = 0;
firingLength = list.length;
for ( ; list && firingIndex < firingLength; firingIndex++ ) {
if ( list[ firingIndex ].apply( context, args ) === false && flags.stopOnFalse ) {
memory = true; // Mark as halted
break;
}
}
firing = false;
if ( list ) {
if ( !flags.once ) {
if ( stack && stack.length ) {
memory = stack.shift();
self.fireWith( memory[ 0 ], memory[ 1 ] );
}
} else if ( memory === true ) {
self.disable();
} else {
list = [];
}
}
},
// Actual Callbacks object
self = {
// Add a callback or a collection of callbacks to the list
add: function() {
if ( list ) {
var length = list.length;
add( arguments );
// Do we need to add the callbacks to the
// current firing batch?
if ( firing ) {
firingLength = list.length;
// With memory, if we're not firing then
// we should call right away, unless previous
// firing was halted (stopOnFalse)
} else if ( memory && memory !== true ) {
firingStart = length;
fire( memory[ 0 ], memory[ 1 ] );
}
}
return this;
},
// Remove a callback from the list
remove: function() {
if ( list ) {
var args = arguments,
argIndex = 0,
argLength = args.length;
for ( ; argIndex < argLength ; argIndex++ ) {
for ( var i = 0; i < list.length; i++ ) {
if ( args[ argIndex ] === list[ i ] ) {
// Handle firingIndex and firingLength
if ( firing ) {
if ( i <= firingLength ) {
firingLength--;
if ( i <= firingIndex ) {
firingIndex--;
}
}
}
// Remove the element
list.splice( i--, 1 );
// If we have some unicity property then
// we only need to do this once
if ( flags.unique ) {
break;
}
}
}
}
}
return this;
},
// Control if a given callback is in the list
has: function( fn ) {
if ( list ) {
var i = 0,
length = list.length;
for ( ; i < length; i++ ) {
if ( fn === list[ i ] ) {
return true;
}
}
}
return false;
},
// Remove all callbacks from the list
empty: function() {
list = [];
return this;
},
// Have the list do nothing anymore
disable: function() {
list = stack = memory = undefined;
return this;
},
// Is it disabled?
disabled: function() {
return !list;
},
// Lock the list in its current state
lock: function() {
stack = undefined;
if ( !memory || memory === true ) {
self.disable();
}
return this;
},
// Is it locked?
locked: function() {
return !stack;
},
// Call all callbacks with the given context and arguments
fireWith: function( context, args ) {
if ( stack ) {
if ( firing ) {
if ( !flags.once ) {
stack.push( [ context, args ] );
}
} else if ( !( flags.once && memory ) ) {
fire( context, args );
}
}
return this;
},
// Call all the callbacks with the given arguments
fire: function() {
self.fireWith( this, arguments );
return this;
},
// To know if the callbacks have already been called at least once
fired: function() {
return !!fired;
}
};
return self;
};
var // Static reference to slice
sliceDeferred = [].slice;
jQuery.extend({
Deferred: function( func ) {
var doneList = jQuery.Callbacks( "once memory" ),
failList = jQuery.Callbacks( "once memory" ),
progressList = jQuery.Callbacks( "memory" ),
state = "pending",
lists = {
resolve: doneList,
reject: failList,
notify: progressList
},
promise = {
done: doneList.add,
fail: failList.add,
progress: progressList.add,
state: function() {
return state;
},
// Deprecated
isResolved: doneList.fired,
isRejected: failList.fired,
then: function( doneCallbacks, failCallbacks, progressCallbacks ) {
deferred.done( doneCallbacks ).fail( failCallbacks ).progress( progressCallbacks );
return this;
},
always: function() {
deferred.done.apply( deferred, arguments ).fail.apply( deferred, arguments );
return this;
},
pipe: function( fnDone, fnFail, fnProgress ) {
return jQuery.Deferred(function( newDefer ) {
jQuery.each( {
done: [ fnDone, "resolve" ],
fail: [ fnFail, "reject" ],
progress: [ fnProgress, "notify" ]
}, function( handler, data ) {
var fn = data[ 0 ],
action = data[ 1 ],
returned;
if ( jQuery.isFunction( fn ) ) {
deferred[ handler ](function() {
returned = fn.apply( this, arguments );
if ( returned && jQuery.isFunction( returned.promise ) ) {
returned.promise().then( newDefer.resolve, newDefer.reject, newDefer.notify );
} else {
newDefer[ action + "With" ]( this === deferred ? newDefer : this, [ returned ] );
}
});
} else {
deferred[ handler ]( newDefer[ action ] );
}
});
}).promise();
},
// Get a promise for this deferred
// If obj is provided, the promise aspect is added to the object
promise: function( obj ) {
if ( obj == null ) {
obj = promise;
} else {
for ( var key in promise ) {
obj[ key ] = promise[ key ];
}
}
return obj;
}
},
deferred = promise.promise({}),
key;
for ( key in lists ) {
deferred[ key ] = lists[ key ].fire;
deferred[ key + "With" ] = lists[ key ].fireWith;
}
// Handle state
deferred.done( function() {
state = "resolved";
}, failList.disable, progressList.lock ).fail( function() {
state = "rejected";
}, doneList.disable, progressList.lock );
// Call given func if any
if ( func ) {
func.call( deferred, deferred );
}
// All done!
return deferred;
},
// Deferred helper
when: function( firstParam ) {
var args = sliceDeferred.call( arguments, 0 ),
i = 0,
length = args.length,
pValues = new Array( length ),
count = length,
pCount = length,
deferred = length <= 1 && firstParam && jQuery.isFunction( firstParam.promise ) ?
firstParam :
jQuery.Deferred(),
promise = deferred.promise();
function resolveFunc( i ) {
return function( value ) {
args[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value;
if ( !( --count ) ) {
deferred.resolveWith( deferred, args );
}
};
}
function progressFunc( i ) {
return function( value ) {
pValues[ i ] = arguments.length > 1 ? sliceDeferred.call( arguments, 0 ) : value;
deferred.notifyWith( promise, pValues );
};
}
if ( length > 1 ) {
for ( ; i < length; i++ ) {
if ( args[ i ] && args[ i ].promise && jQuery.isFunction( args[ i ].promise ) ) {
args[ i ].promise().then( resolveFunc(i), deferred.reject, progressFunc(i) );
} else {
--count;
}
}
if ( !count ) {
deferred.resolveWith( deferred, args );
}
} else if ( deferred !== firstParam ) {
deferred.resolveWith( deferred, length ? [ firstParam ] : [] );
}
return promise;
}
});
jQuery.support = (function() {
var support,
all,
a,
select,
opt,
input,
fragment,
tds,
events,
eventName,
i,
isSupported,
div = document.createElement( "div" ),
documentElement = document.documentElement;
// Preliminary tests
div.setAttribute("className", "t");
div.innerHTML = " <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>";
all = div.getElementsByTagName( "*" );
a = div.getElementsByTagName( "a" )[ 0 ];
// Can't get basic test support
if ( !all || !all.length || !a ) {
return {};
}
// First batch of supports tests
select = document.createElement( "select" );
opt = select.appendChild( document.createElement("option") );
input = div.getElementsByTagName( "input" )[ 0 ];
support = {
// IE strips leading whitespace when .innerHTML is used
leadingWhitespace: ( div.firstChild.nodeType === 3 ),
// Make sure that tbody elements aren't automatically inserted
// IE will insert them into empty tables
tbody: !div.getElementsByTagName("tbody").length,
// Make sure that link elements get serialized correctly by innerHTML
// This requires a wrapper element in IE
htmlSerialize: !!div.getElementsByTagName("link").length,
// Get the style information from getAttribute
// (IE uses .cssText instead)
style: /top/.test( a.getAttribute("style") ),
// Make sure that URLs aren't manipulated
// (IE normalizes it by default)
hrefNormalized: ( a.getAttribute("href") === "/a" ),
// Make sure that element opacity exists
// (IE uses filter instead)
// Use a regex to work around a WebKit issue. See #5145
opacity: /^0.55/.test( a.style.opacity ),
// Verify style float existence
// (IE uses styleFloat instead of cssFloat)
cssFloat: !!a.style.cssFloat,
// Make sure that if no value is specified for a checkbox
// that it defaults to "on".
// (WebKit defaults to "" instead)
checkOn: ( input.value === "on" ),
// Make sure that a selected-by-default option has a working selected property.
// (WebKit defaults to false instead of true, IE too, if it's in an optgroup)
optSelected: opt.selected,
// Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7)
getSetAttribute: div.className !== "t",
// Tests for enctype support on a form(#6743)
enctype: !!document.createElement("form").enctype,
// Makes sure cloning an html5 element does not cause problems
// Where outerHTML is undefined, this still works
html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>",
// Will be defined later
submitBubbles: true,
changeBubbles: true,
focusinBubbles: false,
deleteExpando: true,
noCloneEvent: true,
inlineBlockNeedsLayout: false,
shrinkWrapBlocks: false,
reliableMarginRight: true,
pixelMargin: true
};
// jQuery.boxModel DEPRECATED in 1.3, use jQuery.support.boxModel instead
jQuery.boxModel = support.boxModel = (document.compatMode === "CSS1Compat");
// Make sure checked status is properly cloned
input.checked = true;
support.noCloneChecked = input.cloneNode( true ).checked;
// Make sure that the options inside disabled selects aren't marked as disabled
// (WebKit marks them as disabled)
select.disabled = true;
support.optDisabled = !opt.disabled;
// Test to see if it's possible to delete an expando from an element
// Fails in Internet Explorer
try {
delete div.test;
} catch( e ) {
support.deleteExpando = false;
}
if ( !div.addEventListener && div.attachEvent && div.fireEvent ) {
div.attachEvent( "onclick", function() {
// Cloning a node shouldn't copy over any
// bound event handlers (IE does this)
support.noCloneEvent = false;
});
div.cloneNode( true ).fireEvent( "onclick" );
}
// Check if a radio maintains its value
// after being appended to the DOM
input = document.createElement("input");
input.value = "t";
input.setAttribute("type", "radio");
support.radioValue = input.value === "t";
input.setAttribute("checked", "checked");
// #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: 1,
change: 1,
focusin: 1
}) {
eventName = "on" + i;
isSupported = ( eventName in div );
if ( !isSupported ) {
div.setAttribute( eventName, "return;" );
isSupported = ( typeof div[ eventName ] === "function" );
}
support[ i + "Bubbles" ] = isSupported;
}
}
fragment.removeChild( div );
// Null elements to avoid leaks in IE
fragment = select = opt = div = input = null;
// Run tests that need a body at doc ready
jQuery(function() {
var container, outer, inner, table, td, offsetSupport,
marginDiv, conMarginTop, style, html, positionTopLeftWidthHeight,
paddingMarginBorderVisibility, paddingMarginBorder,
body = document.getElementsByTagName("body")[0];
if ( !body ) {
// Return for frameset docs that don't have a body
return;
}
conMarginTop = 1;
paddingMarginBorder = "padding:0;margin:0;border:";
positionTopLeftWidthHeight = "position:absolute;top:0;left:0;width:1px;height:1px;";
paddingMarginBorderVisibility = paddingMarginBorder + "0;visibility:hidden;";
style = "style='" + positionTopLeftWidthHeight + paddingMarginBorder + "5px solid #000;";
html = "<div " + style + "display:block;'><div style='" + paddingMarginBorder + "0;display:block;overflow:hidden;'></div></div>" +
"<table " + style + "' cellpadding='0' cellspacing='0'>" +
"<tr><td></td></tr></table>";
container = document.createElement("div");
container.style.cssText = paddingMarginBorderVisibility + "width:0;height:0;position:static;top:0;margin-top:" + conMarginTop + "px";
body.insertBefore( container, body.firstChild );
// Construct the test element
div = document.createElement("div");
container.appendChild( div );
// Check if table cells still have offsetWidth/Height when they are set
// to display:none and there are still other visible table cells in a
// table row; if so, offsetWidth/Height are not reliable for use when
// determining if an element has been hidden directly using
// display:none (it is still safe to use offsets if a parent element is
// hidden; don safety goggles and see bug #4512 for more information).
// (only IE 8 fails this test)
div.innerHTML = "<table><tr><td style='" + paddingMarginBorder + "0;display:none'></td><td>t</td></tr></table>";
tds = div.getElementsByTagName( "td" );
isSupported = ( tds[ 0 ].offsetHeight === 0 );
tds[ 0 ].style.display = "";
tds[ 1 ].style.display = "none";
// Check if empty table cells still have offsetWidth/Height
// (IE <= 8 fail this test)
support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 );
// Check if div with explicit width and no margin-right incorrectly
// gets computed margin-right based on width of container. For more
// info see bug #3333
// Fails in WebKit before Feb 2011 nightlies
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
if ( window.getComputedStyle ) {
div.innerHTML = "";
marginDiv = document.createElement( "div" );
marginDiv.style.width = "0";
marginDiv.style.marginRight = "0";
div.style.width = "2px";
div.appendChild( marginDiv );
support.reliableMarginRight =
( parseInt( ( window.getComputedStyle( marginDiv, null ) || { marginRight: 0 } ).marginRight, 10 ) || 0 ) === 0;
}
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.width = div.style.padding = "1px";
div.style.border = 0;
div.style.overflow = "hidden";
div.style.display = "inline";
div.style.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 style='width:5px;'></div>";
support.shrinkWrapBlocks = ( div.offsetWidth !== 3 );
}
div.style.cssText = positionTopLeftWidthHeight + paddingMarginBorderVisibility;
div.innerHTML = html;
outer = div.firstChild;
inner = outer.firstChild;
td = outer.nextSibling.firstChild.firstChild;
offsetSupport = {
doesNotAddBorder: ( inner.offsetTop !== 5 ),
doesAddBorderForTableAndCells: ( td.offsetTop === 5 )
};
inner.style.position = "fixed";
inner.style.top = "20px";
// safari subtracts parent border width here which is 5px
offsetSupport.fixedPosition = ( inner.offsetTop === 20 || inner.offsetTop === 15 );
inner.style.position = inner.style.top = "";
outer.style.overflow = "hidden";
outer.style.position = "relative";
offsetSupport.subtractsBorderForOverflowNotVisible = ( inner.offsetTop === -5 );
offsetSupport.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== conMarginTop );
if ( window.getComputedStyle ) {
div.style.marginTop = "1%";
support.pixelMargin = ( window.getComputedStyle( div, null ) || { marginTop: 0 } ).marginTop !== "1%";
}
if ( typeof container.style.zoom !== "undefined" ) {
container.style.zoom = 1;
}
body.removeChild( container );
marginDiv = div = container = null;
jQuery.extend( support, offsetSupport );
});
return support;
})();
var rbrace = /^(?:\{.*\}|\[.*\])$/,
rmultiDash = /([A-Z])/g;
jQuery.extend({
cache: {},
// Please use with caution
uuid: 0,
// Unique for each copy of jQuery on the page
// Non-digits removed to match rinlinejQuery
expando: "jQuery" + ( jQuery.fn.jquery + Math.random() ).replace( /\D/g, "" ),
// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
noData: {
"embed": true,
// Ban all objects except for Flash (which handle expandos)
"object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",
"applet": true
},
hasData: function( elem ) {
elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ];
return !!elem && !isEmptyDataObject( elem );
},
data: function( elem, name, data, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var privateCache, thisCache, ret,
internalKey = jQuery.expando,
getByName = typeof name === "string",
// We have to handle DOM nodes and JS objects differently because IE6-7
// can't GC object references properly across the DOM-JS boundary
isNode = elem.nodeType,
// Only DOM nodes need the global jQuery cache; JS object data is
// attached directly to the object so GC can occur automatically
cache = isNode ? jQuery.cache : elem,
// Only defining an ID for JS objects if its cache already exists allows
// the code to shortcut on the same path as a DOM node with no cache
id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey,
isEvents = name === "events";
// Avoid doing any more work than we need to when trying to get data on an
// object that has no data at all
if ( (!id || !cache[id] || (!isEvents && !pvt && !cache[id].data)) && getByName && data === undefined ) {
return;
}
if ( !id ) {
// Only DOM nodes need a new unique ID for each element since their data
// ends up in the global cache
if ( isNode ) {
elem[ internalKey ] = id = ++jQuery.uuid;
} else {
id = internalKey;
}
}
if ( !cache[ id ] ) {
cache[ id ] = {};
// Avoids exposing jQuery metadata on plain JS objects when the object
// is serialized using JSON.stringify
if ( !isNode ) {
cache[ id ].toJSON = jQuery.noop;
}
}
// An object can be passed to jQuery.data instead of a key/value pair; this gets
// shallow copied over onto the existing cache
if ( typeof name === "object" || typeof name === "function" ) {
if ( pvt ) {
cache[ id ] = jQuery.extend( cache[ id ], name );
} else {
cache[ id ].data = jQuery.extend( cache[ id ].data, name );
}
}
privateCache = thisCache = cache[ id ];
// jQuery data() is stored in a separate object inside the object's internal data
// cache in order to avoid key collisions between internal data and user-defined
// data.
if ( !pvt ) {
if ( !thisCache.data ) {
thisCache.data = {};
}
thisCache = thisCache.data;
}
if ( data !== undefined ) {
thisCache[ jQuery.camelCase( name ) ] = data;
}
// Users should not attempt to inspect the internal events object using jQuery.data,
// it is undocumented and subject to change. But does anyone listen? No.
if ( isEvents && !thisCache[ name ] ) {
return privateCache.events;
}
// Check for both converted-to-camel and non-converted data property names
// If a data property was specified
if ( getByName ) {
// First Try to find as-is property data
ret = thisCache[ name ];
// Test for null|undefined property data
if ( ret == null ) {
// Try to find the camelCased property
ret = thisCache[ jQuery.camelCase( name ) ];
}
} else {
ret = thisCache;
}
return ret;
},
removeData: function( elem, name, pvt /* Internal Use Only */ ) {
if ( !jQuery.acceptData( elem ) ) {
return;
}
var thisCache, i, l,
// Reference to internal data cache key
internalKey = jQuery.expando,
isNode = elem.nodeType,
// See jQuery.data for more information
cache = isNode ? jQuery.cache : elem,
// See jQuery.data for more information
id = isNode ? elem[ internalKey ] : internalKey;
// If there is already no cache entry for this object, there is no
// purpose in continuing
if ( !cache[ id ] ) {
return;
}
if ( name ) {
thisCache = pvt ? cache[ id ] : cache[ id ].data;
if ( thisCache ) {
// Support array or space separated string names for data keys
if ( !jQuery.isArray( name ) ) {
// try the string as a key before any manipulation
if ( name in thisCache ) {
name = [ name ];
} else {
// split the camel cased version by spaces unless a key with the spaces exists
name = jQuery.camelCase( name );
if ( name in thisCache ) {
name = [ name ];
} else {
name = name.split( " " );
}
}
}
for ( i = 0, l = name.length; i < l; i++ ) {
delete thisCache[ name[i] ];
}
// If there is no data left in the cache, we want to continue
// and let the cache object itself get destroyed
if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) {
return;
}
}
}
// See jQuery.data for more information
if ( !pvt ) {
delete cache[ id ].data;
// Don't destroy the parent cache unless the internal data object
// had been the only thing left in it
if ( !isEmptyDataObject(cache[ id ]) ) {
return;
}
}
// Browsers that fail expando deletion also refuse to delete expandos on
// the window, but it will allow it on all other JS objects; other browsers
// don't care
// Ensure that `cache` is not a window object #10080
if ( jQuery.support.deleteExpando || !cache.setInterval ) {
delete cache[ id ];
} else {
cache[ id ] = null;
}
// We destroyed the cache and need to eliminate the expando on the node to avoid
// false lookups in the cache for entries that no longer exist
if ( isNode ) {
// IE does not allow us to delete expando properties from nodes,
// nor does it have a removeAttribute function on Document nodes;
// we must handle all of these cases
if ( jQuery.support.deleteExpando ) {
delete elem[ internalKey ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( internalKey );
} else {
elem[ internalKey ] = null;
}
}
},
// For internal use only.
_data: function( elem, name, data ) {
return jQuery.data( elem, name, data, true );
},
// A method for determining if a DOM node can handle the data expando
acceptData: function( elem ) {
if ( elem.nodeName ) {
var match = jQuery.noData[ elem.nodeName.toLowerCase() ];
if ( match ) {
return !(match === true || elem.getAttribute("classid") !== match);
}
}
return true;
}
});
jQuery.fn.extend({
data: function( key, value ) {
var parts, 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-" ) === 0 ) {
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 :
jQuery.isNumeric( 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 ) {
for ( var name in obj ) {
// if the public data object is empty, the private is still empty
if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) {
continue;
}
if ( name !== "toJSON" ) {
return false;
}
}
return true;
}
function handleQueueMarkDefer( elem, type, src ) {
var deferDataKey = type + "defer",
queueDataKey = type + "queue",
markDataKey = type + "mark",
defer = jQuery._data( elem, deferDataKey );
if ( defer &&
( src === "queue" || !jQuery._data(elem, queueDataKey) ) &&
( src === "mark" || !jQuery._data(elem, markDataKey) ) ) {
// Give room for hard-coded callbacks to fire first
// and eventually mark/queue something else on the element
setTimeout( function() {
if ( !jQuery._data( elem, queueDataKey ) &&
!jQuery._data( elem, markDataKey ) ) {
jQuery.removeData( elem, deferDataKey, true );
defer.fire();
}
}, 0 );
}
}
jQuery.extend({
_mark: function( elem, type ) {
if ( elem ) {
type = ( type || "fx" ) + "mark";
jQuery._data( elem, type, (jQuery._data( elem, type ) || 0) + 1 );
}
},
_unmark: function( force, elem, type ) {
if ( force !== true ) {
type = elem;
elem = force;
force = false;
}
if ( elem ) {
type = type || "fx";
var key = type + "mark",
count = force ? 0 : ( (jQuery._data( elem, key ) || 1) - 1 );
if ( count ) {
jQuery._data( elem, key, count );
} else {
jQuery.removeData( elem, key, true );
handleQueueMarkDefer( elem, type, "mark" );
}
}
},
queue: function( elem, type, data ) {
var q;
if ( elem ) {
type = ( type || "fx" ) + "queue";
q = jQuery._data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( data ) {
if ( !q || jQuery.isArray(data) ) {
q = jQuery._data( elem, type, jQuery.makeArray(data) );
} else {
q.push( data );
}
}
return q || [];
}
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ),
fn = queue.shift(),
hooks = {};
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift( "inprogress" );
}
jQuery._data( elem, type + ".run", hooks );
fn.call( elem, function() {
jQuery.dequeue( elem, type );
}, hooks );
}
if ( !queue.length ) {
jQuery.removeData( elem, type + "queue " + type + ".run", true );
handleQueueMarkDefer( elem, type, "queue" );
}
}
});
jQuery.fn.extend({
queue: function( type, data ) {
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 );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
delay: function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time;
type = type || "fx";
return this.queue( type, function( next, hooks ) {
var timeout = setTimeout( next, time );
hooks.stop = function() {
clearTimeout( timeout );
};
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
},
// Get a promise resolved when queues of a certain type
// are emptied (fx is the type by default)
promise: function( type, object ) {
if ( typeof type !== "string" ) {
object = type;
type = undefined;
}
type = type || "fx";
var defer = jQuery.Deferred(),
elements = this,
i = elements.length,
count = 1,
deferDataKey = type + "defer",
queueDataKey = type + "queue",
markDataKey = type + "mark",
tmp;
function resolve() {
if ( !( --count ) ) {
defer.resolveWith( elements, [ elements ] );
}
}
while( i-- ) {
if (( tmp = jQuery.data( elements[ i ], deferDataKey, undefined, true ) ||
( jQuery.data( elements[ i ], queueDataKey, undefined, true ) ||
jQuery.data( elements[ i ], markDataKey, undefined, true ) ) &&
jQuery.data( elements[ i ], deferDataKey, jQuery.Callbacks( "once memory" ), true ) )) {
count++;
tmp.add( resolve );
}
}
resolve();
return defer.promise( object );
}
});
var rclass = /[\n\t\r]/g,
rspace = /\s+/,
rreturn = /\r/g,
rtype = /^(?:button|input)$/i,
rfocusable = /^(?:button|input|object|select|textarea)$/i,
rclickable = /^a(?:rea)?$/i,
rboolean = /^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,
getSetAttribute = jQuery.support.getSetAttribute,
nodeHook, boolHook, fixSpecified;
jQuery.fn.extend({
attr: function( name, value ) {
return jQuery.access( this, 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( rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 ) {
if ( !elem.className && classNames.length === 1 ) {
elem.className = value;
} else {
setClass = " " + elem.className + " ";
for ( c = 0, cl = classNames.length; c < cl; c++ ) {
if ( !~setClass.indexOf( " " + classNames[ c ] + " " ) ) {
setClass += classNames[ c ] + " ";
}
}
elem.className = jQuery.trim( setClass );
}
}
}
}
return this;
},
removeClass: function( value ) {
var classNames, i, l, elem, className, c, cl;
if ( jQuery.isFunction( value ) ) {
return this.each(function( j ) {
jQuery( this ).removeClass( value.call(this, j, this.className) );
});
}
if ( (value && typeof value === "string") || value === undefined ) {
classNames = ( value || "" ).split( rspace );
for ( i = 0, l = this.length; i < l; i++ ) {
elem = this[ i ];
if ( elem.nodeType === 1 && elem.className ) {
if ( value ) {
className = (" " + elem.className + " ").replace( rclass, " " );
for ( c = 0, cl = classNames.length; c < cl; c++ ) {
className = className.replace(" " + classNames[ c ] + " ", " ");
}
elem.className = jQuery.trim( className );
} else {
elem.className = "";
}
}
}
}
return this;
},
toggleClass: function( value, stateVal ) {
var type = typeof value,
isBool = typeof stateVal === "boolean";
if ( jQuery.isFunction( value ) ) {
return this.each(function( i ) {
jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal );
});
}
return this.each(function() {
if ( type === "string" ) {
// toggle individual class names
var className,
i = 0,
self = jQuery( this ),
state = stateVal,
classNames = value.split( rspace );
while ( (className = classNames[ i++ ]) ) {
// check each className given, space seperated list
state = isBool ? state : !self.hasClass( className );
self[ state ? "addClass" : "removeClass" ]( className );
}
} else if ( type === "undefined" || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery._data( this, "__className__", this.className );
}
// toggle whole className
this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ",
i = 0,
l = this.length;
for ( ; i < l; i++ ) {
if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) > -1 ) {
return true;
}
}
return false;
},
val: function( value ) {
var hooks, ret, isFunction,
elem = this[0];
if ( !arguments.length ) {
if ( elem ) {
hooks = jQuery.valHooks[ elem.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 self = jQuery(this), val;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call( this, i, self.val() );
} else {
val = value;
}
// Treat null/undefined as ""; convert numbers to string
if ( val == null ) {
val = "";
} else if ( typeof val === "number" ) {
val += "";
} else if ( jQuery.isArray( val ) ) {
val = jQuery.map(val, function ( value ) {
return value == null ? "" : value + "";
});
}
hooks = jQuery.valHooks[ this.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, i, max, option,
index = elem.selectedIndex,
values = [],
options = elem.options,
one = elem.type === "select-one";
// Nothing was selected
if ( index < 0 ) {
return null;
}
// Loop through all the selected options
i = one ? index : 0;
max = one ? index + 1 : options.length;
for ( ; i < max; i++ ) {
option = options[ i ];
// Don't return options that are disabled or in a disabled optgroup
if ( option.selected && (jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null) &&
(!option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" )) ) {
// Get the specific value for the option
value = jQuery( option ).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
// Fixes Bug #2551 -- select.val() broken in IE after form.reset()
if ( one && !values.length && options.length ) {
return jQuery( options[ index ] ).val();
}
return values;
},
set: function( elem, value ) {
var values = jQuery.makeArray( value );
jQuery(elem).find("option").each(function() {
this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
});
if ( !values.length ) {
elem.selectedIndex = -1;
}
return values;
}
}
},
attrFn: {
val: true,
css: true,
html: true,
text: true,
data: true,
width: true,
height: true,
offset: true
},
attr: function( elem, name, value, pass ) {
var ret, hooks, notxml,
nType = elem.nodeType;
// don't get/set attributes on text, comment and attribute nodes
if ( !elem || nType === 3 || nType === 8 || nType === 2 ) {
return;
}
if ( pass && name in jQuery.attrFn ) {
return jQuery( elem )[ name ]( value );
}
// Fallback to prop when attributes are not supported
if ( typeof elem.getAttribute === "undefined" ) {
return jQuery.prop( elem, name, value );
}
notxml = nType !== 1 || !jQuery.isXMLDoc( elem );
// All attributes are lowercase
// Grab necessary hook if one is defined
if ( notxml ) {
name = name.toLowerCase();
hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook );
}
if ( value !== undefined ) {
if ( value === null ) {
jQuery.removeAttr( elem, name );
return;
} else if ( hooks && "set" in hooks && notxml && (ret = hooks.set( elem, value, name )) !== undefined ) {
return ret;
} else {
elem.setAttribute( name, "" + value );
return value;
}
} else if ( hooks && "get" in hooks && notxml && (ret = hooks.get( elem, name )) !== null ) {
return ret;
} else {
ret = elem.getAttribute( name );
// Non-existent attributes return null, we normalize to undefined
return ret === null ?
undefined :
ret;
}
},
removeAttr: function( elem, value ) {
var propName, attrNames, name, l, isBool,
i = 0;
if ( value && elem.nodeType === 1 ) {
attrNames = value.toLowerCase().split( rspace );
l = attrNames.length;
for ( ; i < l; i++ ) {
name = attrNames[ i ];
if ( name ) {
propName = jQuery.propFix[ name ] || name;
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;
}
}
}
});
// Add the tabIndex propHook to attrHooks for back-compat (different case is intentional)
jQuery.attrHooks.tabindex = jQuery.propHooks.tabIndex;
// Hook for boolean attributes
boolHook = {
get: function( elem, name ) {
// Align boolean attributes with corresponding properties
// Fall back to attribute presence where some booleans are not supported
var attrNode,
property = jQuery.prop( elem, name );
return property === true || typeof property !== "boolean" && ( attrNode = elem.getAttributeNode(name) ) && attrNode.nodeValue !== false ?
name.toLowerCase() :
undefined;
},
set: function( elem, value, name ) {
var propName;
if ( value === false ) {
// Remove boolean attributes when set to false
jQuery.removeAttr( elem, name );
} else {
// value is true since we know at this point it's type boolean and not false
// Set boolean attributes to the same name and set the DOM property
propName = jQuery.propFix[ name ] || name;
if ( propName in elem ) {
// Only set the IDL specifically if it already exists on the element
elem[ propName ] = true;
}
elem.setAttribute( name, name.toLowerCase() );
}
return name;
}
};
// IE6/7 do not support getting/setting some attributes with get/setAttribute
if ( !getSetAttribute ) {
fixSpecified = {
name: true,
id: true,
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.nodeValue !== "" : ret.specified ) ?
ret.nodeValue :
undefined;
},
set: function( elem, value, name ) {
// Set the existing or create a new attribute node
var ret = elem.getAttributeNode( name );
if ( !ret ) {
ret = document.createAttribute( name );
elem.setAttributeNode( ret );
}
return ( ret.nodeValue = value + "" );
}
};
// Apply the nodeHook to tabindex
jQuery.attrHooks.tabindex.set = nodeHook.set;
// Set width and height to auto instead of 0 on empty string( Bug #8150 )
// This is for removals
jQuery.each([ "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
set: function( elem, value ) {
if ( value === "" ) {
elem.setAttribute( name, "auto" );
return value;
}
}
});
});
// Set contenteditable to false on removals(#10429)
// Setting to empty string throws an error as an invalid value
jQuery.attrHooks.contenteditable = {
get: nodeHook.get,
set: function( elem, value, name ) {
if ( value === "" ) {
value = "false";
}
nodeHook.set( elem, value, name );
}
};
}
// Some attributes require a special call on IE
if ( !jQuery.support.hrefNormalized ) {
jQuery.each([ "href", "src", "width", "height" ], function( i, name ) {
jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], {
get: function( elem ) {
var ret = elem.getAttribute( name, 2 );
return ret === null ? undefined : ret;
}
});
});
}
if ( !jQuery.support.style ) {
jQuery.attrHooks.style = {
get: function( elem ) {
// Return undefined in the case of empty string
// Normalize to lowercase since IE uppercases css property names
return elem.style.cssText.toLowerCase() || undefined;
},
set: function( elem, value ) {
return ( elem.style.cssText = "" + value );
}
};
}
// Safari mis-reports the default selected property of an option
// Accessing the parent's selectedIndex property fixes it
if ( !jQuery.support.optSelected ) {
jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, {
get: function( elem ) {
var parent = elem.parentNode;
if ( parent ) {
parent.selectedIndex;
// Make sure that it also works with optgroups, see #5701
if ( parent.parentNode ) {
parent.parentNode.selectedIndex;
}
}
return null;
}
});
}
// IE6/7 call enctype encoding
if ( !jQuery.support.enctype ) {
jQuery.propFix.enctype = "encoding";
}
// Radios and checkboxes getter/setter
if ( !jQuery.support.checkOn ) {
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = {
get: function( elem ) {
// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
return elem.getAttribute("value") === null ? "on" : elem.value;
}
};
});
}
jQuery.each([ "radio", "checkbox" ], function() {
jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], {
set: function( elem, value ) {
if ( jQuery.isArray( value ) ) {
return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 );
}
}
});
});
var rformElems = /^(?:textarea|input|select)$/i,
rtypenamespace = /^([^\.]*)?(?:\.(.+))?$/,
rhoverHack = /(?:^|\s)hover(\.\S+)?\b/,
rkeyEvent = /^key/,
rmouseEvent = /^(?:mouse|contextmenu)|click/,
rfocusMorph = /^(?:focusinfocus|focusoutblur)$/,
rquickIs = /^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,
quickParse = function( selector ) {
var quick = rquickIs.exec( selector );
if ( quick ) {
// 0 1 2 3
// [ _, tag, id, class ]
quick[1] = ( quick[1] || "" ).toLowerCase();
quick[3] = quick[3] && new RegExp( "(?:^|\\s)" + quick[3] + "(?:\\s|$)" );
}
return quick;
},
quickIs = function( elem, m ) {
var attrs = elem.attributes || {};
return (
(!m[1] || elem.nodeName.toLowerCase() === m[1]) &&
(!m[2] || (attrs.id || {}).value === m[2]) &&
(!m[3] || m[3].test( (attrs[ "class" ] || {}).value ))
);
},
hoverHack = function( events ) {
return jQuery.event.special.hover ? events : events.replace( rhoverHack, "mouseenter$1 mouseleave$1" );
};
/*
* Helper functions for managing events -- not part of the public interface.
* Props to Dean Edwards' addEvent library for many of the ideas.
*/
jQuery.event = {
add: function( elem, types, handler, data, selector ) {
var elemData, eventHandle, events,
t, tns, type, namespaces, handleObj,
handleObjIn, quick, handlers, special;
// Don't attach events to noData or text/comment nodes (allow plain objects tho)
if ( elem.nodeType === 3 || elem.nodeType === 8 || !types || !handler || !(elemData = jQuery._data( elem )) ) {
return;
}
// Caller can pass in an object of custom data in lieu of the handler
if ( handler.handler ) {
handleObjIn = handler;
handler = handleObjIn.handler;
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,
quick: selector && quickParse( selector ),
namespace: namespaces.join(".")
}, handleObjIn );
// Init the event handler queue if we're the first
handlers = events[ type ];
if ( !handlers ) {
handlers = events[ type ] = [];
handlers.delegateCount = 0;
// Only use addEventListener/attachEvent if the special events handler returns false
if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) {
// Bind the global event handler to the element
if ( elem.addEventListener ) {
elem.addEventListener( type, eventHandle, false );
} else if ( elem.attachEvent ) {
elem.attachEvent( "on" + type, eventHandle );
}
}
}
if ( special.add ) {
special.add.call( elem, handleObj );
if ( !handleObj.handler.guid ) {
handleObj.handler.guid = handler.guid;
}
}
// Add to the element's handler list, delegates in front
if ( selector ) {
handlers.splice( handlers.delegateCount++, 0, handleObj );
} else {
handlers.push( handleObj );
}
// Keep track of which events have ever been used, for event optimization
jQuery.event.global[ type ] = true;
}
// Nullify elem to prevent memory leaks in IE
elem = null;
},
global: {},
// Detach an event or set of events from an element
remove: function( elem, types, handler, selector, mappedTypes ) {
var elemData = jQuery.hasData( elem ) && jQuery._data( elem ),
t, tns, type, origType, namespaces, origCount,
j, events, special, handle, eventType, handleObj;
if ( !elemData || !(events = elemData.events) ) {
return;
}
// Once for each type.namespace in types; type may be omitted
types = jQuery.trim( hoverHack( types || "" ) ).split(" ");
for ( t = 0; t < types.length; t++ ) {
tns = rtypenamespace.exec( types[t] ) || [];
type = origType = tns[1];
namespaces = tns[2];
// Unbind all events (on this namespace, if provided) for the element
if ( !type ) {
for ( type in events ) {
jQuery.event.remove( elem, type + types[ t ], handler, selector, true );
}
continue;
}
special = jQuery.event.special[ type ] || {};
type = ( selector? special.delegateType : special.bindType ) || type;
eventType = events[ type ] || [];
origCount = eventType.length;
namespaces = namespaces ? new RegExp("(^|\\.)" + namespaces.split(".").sort().join("\\.(?:.*\\.)?") + "(\\.|$)") : null;
// Remove matching events
for ( j = 0; j < eventType.length; j++ ) {
handleObj = eventType[ j ];
if ( ( mappedTypes || origType === handleObj.origType ) &&
( !handler || handler.guid === handleObj.guid ) &&
( !namespaces || namespaces.test( handleObj.namespace ) ) &&
( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) {
eventType.splice( j--, 1 );
if ( handleObj.selector ) {
eventType.delegateCount--;
}
if ( special.remove ) {
special.remove.call( elem, handleObj );
}
}
}
// Remove generic event handler if we removed something and no more handlers exist
// (avoids potential for endless recursion during removal of special event handlers)
if ( eventType.length === 0 && origCount !== eventType.length ) {
if ( !special.teardown || special.teardown.call( elem, namespaces ) === false ) {
jQuery.removeEvent( elem, type, elemData.handle );
}
delete events[ type ];
}
}
// Remove the expando if it's no longer used
if ( jQuery.isEmptyObject( events ) ) {
handle = elemData.handle;
if ( handle ) {
handle.elem = null;
}
// removeData also checks for emptiness and clears the expando if empty
// so use it instead of delete
jQuery.removeData( elem, [ "events", "handle" ], true );
}
},
// Events that are safe to short-circuit if no handlers are attached.
// Native DOM events should not be added, they may have inline handlers.
customEvent: {
"getData": true,
"setData": true,
"changeData": true
},
trigger: function( event, data, elem, onlyHandlers ) {
// Don't do events on text and comment nodes
if ( elem && (elem.nodeType === 3 || elem.nodeType === 8) ) {
return;
}
// Event object or event type
var type = event.type || event,
namespaces = [],
cache, exclusive, i, cur, old, ontype, special, handle, eventPath, bubbleType;
// focus/blur morphs to focusin/out; ensure we're not firing them right now
if ( rfocusMorph.test( type + jQuery.event.triggered ) ) {
return;
}
if ( type.indexOf( "!" ) >= 0 ) {
// Exclusive events trigger only for the exact event (no namespaces)
type = type.slice(0, -1);
exclusive = true;
}
if ( type.indexOf( "." ) >= 0 ) {
// Namespaced trigger; create a regexp to match event type in handle()
namespaces = type.split(".");
type = namespaces.shift();
namespaces.sort();
}
if ( (!elem || jQuery.event.customEvent[ type ]) && !jQuery.event.global[ type ] ) {
// No jQuery handlers for this event type, and it can't have inline handlers
return;
}
// Caller can pass in an Event, Object, or just an event type string
event = typeof event === "object" ?
// jQuery.Event object
event[ jQuery.expando ] ? event :
// Object literal
new jQuery.Event( type, event ) :
// Just the event type (string)
new jQuery.Event( type );
event.type = type;
event.isTrigger = true;
event.exclusive = exclusive;
event.namespace = namespaces.join( "." );
event.namespace_re = event.namespace? new RegExp("(^|\\.)" + namespaces.join("\\.(?:.*\\.)?") + "(\\.|$)") : null;
ontype = type.indexOf( ":" ) < 0 ? "on" + type : "";
// Handle a global trigger
if ( !elem ) {
// TODO: Stop taunting the data cache; remove global events and always attach to document
cache = jQuery.cache;
for ( i in cache ) {
if ( cache[ i ].events && cache[ i ].events[ type ] ) {
jQuery.event.trigger( event, data, cache[ i ].handle.elem, true );
}
}
return;
}
// Clean up the event in case it is being reused
event.result = undefined;
if ( !event.target ) {
event.target = elem;
}
// Clone any incoming data and prepend the event, creating the handler arg list
data = data != null ? jQuery.makeArray( data ) : [];
data.unshift( event );
// Allow special events to draw outside the lines
special = jQuery.event.special[ type ] || {};
if ( special.trigger && special.trigger.apply( elem, data ) === false ) {
return;
}
// Determine event propagation path in advance, per W3C events spec (#9951)
// Bubble up to document, then to window; watch for a global ownerDocument var (#9724)
eventPath = [[ elem, special.bindType || type ]];
if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) {
bubbleType = special.delegateType || type;
cur = rfocusMorph.test( bubbleType + type ) ? elem : elem.parentNode;
old = null;
for ( ; cur; cur = cur.parentNode ) {
eventPath.push([ cur, bubbleType ]);
old = cur;
}
// Only add window if we got to document (e.g., not plain obj or detached DOM)
if ( old && old === elem.ownerDocument ) {
eventPath.push([ old.defaultView || old.parentWindow || window, bubbleType ]);
}
}
// Fire handlers on the event path
for ( i = 0; i < eventPath.length && !event.isPropagationStopped(); i++ ) {
cur = eventPath[i][0];
event.type = eventPath[i][1];
handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" );
if ( handle ) {
handle.apply( cur, data );
}
// Note that this is a bare JS function and not a jQuery handler
handle = ontype && cur[ ontype ];
if ( handle && jQuery.acceptData( cur ) && handle.apply( cur, data ) === false ) {
event.preventDefault();
}
}
event.type = type;
// If nobody prevented the default action, do it now
if ( !onlyHandlers && !event.isDefaultPrevented() ) {
if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) &&
!(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) {
// Call a native DOM method on the target with the same name name as the event.
// Can't use an .isFunction() check here because IE6/7 fails that test.
// Don't do default actions on window, that's where global variables be (#6170)
// IE<9 dies on focus/blur to hidden element (#1486)
if ( ontype && elem[ type ] && ((type !== "focus" && type !== "blur") || event.target.offsetWidth !== 0) && !jQuery.isWindow( elem ) ) {
// Don't re-trigger an onFOO event when we call its FOO() method
old = elem[ ontype ];
if ( old ) {
elem[ ontype ] = null;
}
// Prevent re-triggering of the same event, since we already bubbled it above
jQuery.event.triggered = type;
elem[ type ]();
jQuery.event.triggered = undefined;
if ( old ) {
elem[ ontype ] = old;
}
}
}
}
return event.result;
},
dispatch: function( event ) {
// Make a writable jQuery.Event from the native event object
event = jQuery.event.fix( event || window.event );
var handlers = ( (jQuery._data( this, "events" ) || {} )[ event.type ] || []),
delegateCount = handlers.delegateCount,
args = [].slice.call( arguments, 0 ),
run_all = !event.exclusive && !event.namespace,
special = jQuery.event.special[ event.type ] || {},
handlerQueue = [],
i, j, cur, jqcur, ret, selMatch, matched, matches, handleObj, sel, related;
// Use the fix-ed jQuery.Event rather than the (read-only) native event
args[0] = event;
event.delegateTarget = this;
// 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") ) {
// Pregenerate a single jQuery object for reuse with .is()
jqcur = jQuery(this);
jqcur.context = this.ownerDocument || this;
for ( cur = event.target; cur != this; cur = cur.parentNode || this ) {
// Don't process events on disabled elements (#6911, #8165)
if ( cur.disabled !== true ) {
selMatch = {};
matches = [];
jqcur[0] = cur;
for ( i = 0; i < delegateCount; i++ ) {
handleObj = handlers[ i ];
sel = handleObj.selector;
if ( selMatch[ sel ] === undefined ) {
selMatch[ sel ] = (
handleObj.quick ? quickIs( cur, handleObj.quick ) : jqcur.is( sel )
);
}
if ( selMatch[ sel ] ) {
matches.push( handleObj );
}
}
if ( matches.length ) {
handlerQueue.push({ elem: cur, matches: matches });
}
}
}
}
// Add the remaining (directly-bound) handlers
if ( handlers.length > delegateCount ) {
handlerQueue.push({ elem: this, matches: handlers.slice( delegateCount ) });
}
// Run delegates first; they may want to stop propagation beneath us
for ( i = 0; i < handlerQueue.length && !event.isPropagationStopped(); i++ ) {
matched = handlerQueue[ i ];
event.currentTarget = matched.elem;
for ( j = 0; j < matched.matches.length && !event.isImmediatePropagationStopped(); j++ ) {
handleObj = matched.matches[ j ];
// Triggered event must either 1) be non-exclusive and have no namespace, or
// 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace).
if ( run_all || (!event.namespace && !handleObj.namespace) || event.namespace_re && event.namespace_re.test( handleObj.namespace ) ) {
event.data = handleObj.data;
event.handleObj = handleObj;
ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler )
.apply( matched.elem, args );
if ( ret !== undefined ) {
event.result = ret;
if ( ret === false ) {
event.preventDefault();
event.stopPropagation();
}
}
}
}
}
// 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; add metaKey if it's not there (#3368, IE6/7/8)
if ( event.metaKey === undefined ) {
event.metaKey = event.ctrlKey;
}
return fixHook.filter? fixHook.filter( event, originalEvent ) : event;
},
special: {
ready: {
// Make sure the ready event is setup
setup: jQuery.bindReady
},
load: {
// Prevent triggered image.load events from bubbling to window.load
noBubble: true
},
focus: {
delegateType: "focusin"
},
blur: {
delegateType: "focusout"
},
beforeunload: {
setup: function( data, namespaces, eventHandle ) {
// We only want to do this special case on windows
if ( jQuery.isWindow( this ) ) {
this.onbeforeunload = eventHandle;
}
},
teardown: function( namespaces, eventHandle ) {
if ( this.onbeforeunload === eventHandle ) {
this.onbeforeunload = null;
}
}
}
},
simulate: function( type, elem, event, bubble ) {
// Piggyback on a donor event to simulate a different one.
// Fake originalEvent to avoid donor's stopPropagation, but if the
// simulated event prevents default then we do the same on the donor.
var e = jQuery.extend(
new jQuery.Event(),
event,
{ type: type,
isSimulated: true,
originalEvent: {}
}
);
if ( bubble ) {
jQuery.event.trigger( e, null, elem );
} else {
jQuery.event.dispatch.call( elem, e );
}
if ( e.isDefaultPrevented() ) {
event.preventDefault();
}
}
};
// Some plugins are using, but it's undocumented/deprecated and will be removed.
// The 1.7 special event interface should provide all the hooks needed now.
jQuery.event.handle = jQuery.event.dispatch;
jQuery.removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
if ( elem.removeEventListener ) {
elem.removeEventListener( type, handle, false );
}
} :
function( elem, type, handle ) {
if ( elem.detachEvent ) {
elem.detachEvent( "on" + type, handle );
}
};
jQuery.Event = function( src, props ) {
// Allow instantiation without the 'new' keyword
if ( !(this instanceof jQuery.Event) ) {
return new jQuery.Event( src, props );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Events bubbling up the document may have been marked as prevented
// by a handler lower down the tree; reflect the correct value.
this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false ||
src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse;
// Event type
} else {
this.type = src;
}
// Put explicitly provided properties onto the event object
if ( props ) {
jQuery.extend( this, props );
}
// Create a timestamp if incoming event doesn't have one
this.timeStamp = src && src.timeStamp || jQuery.now();
// Mark it as fixed
this[ jQuery.expando ] = true;
};
function returnFalse() {
return false;
}
function returnTrue() {
return true;
}
// jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding
// http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html
jQuery.Event.prototype = {
preventDefault: function() {
this.isDefaultPrevented = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if preventDefault exists run it on the original event
if ( e.preventDefault ) {
e.preventDefault();
// otherwise set the returnValue property of the original event to false (IE)
} else {
e.returnValue = false;
}
},
stopPropagation: function() {
this.isPropagationStopped = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if stopPropagation exists run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// otherwise set the cancelBubble property of the original event to true (IE)
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
},
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse
};
// Create mouseenter/leave events using mouseover/out and event-time checks
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
delegateType: fix,
bindType: fix,
handle: function( event ) {
var target = this,
related = event.relatedTarget,
handleObj = event.handleObj,
selector = handleObj.selector,
ret;
// For mousenter/leave call the handler if related is outside the target.
// NB: No relatedTarget if the mouse left/entered the browser window
if ( !related || (related !== target && !jQuery.contains( target, related )) ) {
event.type = handleObj.origType;
ret = handleObj.handler.apply( this, arguments );
event.type = fix;
}
return ret;
}
};
});
// IE submit delegation
if ( !jQuery.support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function() {
// Only need this for delegated form submit events
if ( jQuery.nodeName( this, "form" ) ) {
return false;
}
// Lazy-add a submit handler when a descendant form may potentially be submitted
jQuery.event.add( this, "click._submit keypress._submit", function( e ) {
// Node name check avoids a VML-related crash in IE (#9807)
var elem = e.target,
form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined;
if ( form && !form._submit_attached ) {
jQuery.event.add( form, "submit._submit", function( event ) {
event._submit_bubble = true;
});
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;
jQuery.event.simulate( "change", this, event, true );
}
});
}
return false;
}
// Delegated event; lazy-add a change handler on descendant inputs
jQuery.event.add( this, "beforeactivate._change", function( e ) {
var elem = e.target;
if ( rformElems.test( elem.nodeName ) && !elem._change_attached ) {
jQuery.event.add( elem, "change._change", function( event ) {
if ( this.parentNode && !event.isSimulated && !event.isTrigger ) {
jQuery.event.simulate( "change", this.parentNode, event, true );
}
});
elem._change_attached = true;
}
});
},
handle: function( event ) {
var elem = event.target;
// Swallow native change events from checkbox/radio, we already triggered them above
if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) {
return event.handleObj.handler.apply( this, arguments );
}
},
teardown: function() {
jQuery.event.remove( this, "._change" );
return rformElems.test( this.nodeName );
}
};
}
// Create "bubbling" focus and blur events
if ( !jQuery.support.focusinBubbles ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
// Attach a single capturing handler while someone wants focusin/focusout
var attaches = 0,
handler = function( event ) {
jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true );
};
jQuery.event.special[ fix ] = {
setup: function() {
if ( attaches++ === 0 ) {
document.addEventListener( orig, handler, true );
}
},
teardown: function() {
if ( --attaches === 0 ) {
document.removeEventListener( orig, handler, true );
}
}
};
});
}
jQuery.fn.extend({
on: function( types, selector, data, fn, /*INTERNAL*/ one ) {
var origFn, type;
// Types can be a map of types/handlers
if ( typeof types === "object" ) {
// ( types-Object, selector, data )
if ( typeof selector !== "string" ) { // && 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 ) {
if ( types && types.preventDefault && types.handleObj ) {
// ( event ) dispatched jQuery.Event
var 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 ( var type in types ) {
this.off( type, selector, types[ type ] );
}
return this;
}
if ( selector === false || typeof selector === "function" ) {
// ( types [, fn] )
fn = selector;
selector = undefined;
}
if ( fn === false ) {
fn = returnFalse;
}
return this.each(function() {
jQuery.event.remove( this, types, fn, selector );
});
},
bind: function( types, data, fn ) {
return this.on( types, null, data, fn );
},
unbind: function( types, fn ) {
return this.off( types, null, fn );
},
live: function( types, data, fn ) {
jQuery( this.context ).on( types, this.selector, data, fn );
return this;
},
die: function( types, fn ) {
jQuery( this.context ).off( types, this.selector || "**", fn );
return this;
},
delegate: function( selector, types, data, fn ) {
return this.on( types, selector, data, fn );
},
undelegate: function( selector, types, fn ) {
// ( namespace ) or ( selector, types [, fn] )
return arguments.length == 1? this.off( selector, "**" ) : this.off( types, selector, fn );
},
trigger: function( type, data ) {
return this.each(function() {
jQuery.event.trigger( type, data, this );
});
},
triggerHandler: function( type, data ) {
if ( this[0] ) {
return jQuery.event.trigger( type, data, this[0], true );
}
},
toggle: function( fn ) {
// Save reference to arguments for access in closure
var args = arguments,
guid = fn.guid || jQuery.guid++,
i = 0,
toggler = function( event ) {
// Figure out which function to execute
var lastToggle = ( jQuery._data( this, "lastToggle" + fn.guid ) || 0 ) % i;
jQuery._data( this, "lastToggle" + fn.guid, lastToggle + 1 );
// Make sure that clicks stop
event.preventDefault();
// and execute the function
return args[ lastToggle ].apply( this, arguments ) || false;
};
// link all the functions, so any of them can unbind this click handler
toggler.guid = guid;
while ( i < args.length ) {
args[ i++ ].guid = guid;
}
return this.click( toggler );
},
hover: function( fnOver, fnOut ) {
return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver );
}
});
jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " +
"mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " +
"change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) {
// Handle event binding
jQuery.fn[ name ] = function( data, fn ) {
if ( fn == null ) {
fn = data;
data = null;
}
return arguments.length > 0 ?
this.on( name, null, data, fn ) :
this.trigger( name );
};
if ( jQuery.attrFn ) {
jQuery.attrFn[ name ] = true;
}
if ( rkeyEvent.test( name ) ) {
jQuery.event.fixHooks[ name ] = jQuery.event.keyHooks;
}
if ( rmouseEvent.test( name ) ) {
jQuery.event.fixHooks[ name ] = jQuery.event.mouseHooks;
}
});
/*!
* Sizzle CSS Selector Engine
* Copyright 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,
expando = "sizcache" + (Math.random() + '').replace('.', ''),
done = 0,
toString = Object.prototype.toString,
hasDuplicate = false,
baseHasDuplicate = true,
rBackslash = /\\/g,
rReturn = /\r\n/g,
rNonWord = /\W/;
// Here we check if the JavaScript engine is using some sort of
// optimization where it does not always call our comparision
// function. If that is the case, discard the hasDuplicate value.
// Thus far that includes Google Chrome.
[0, 0].sort(function() {
baseHasDuplicate = false;
return 0;
});
var Sizzle = function( selector, context, results, seed ) {
results = results || [];
context = context || document;
var origContext = context;
if ( context.nodeType !== 1 && context.nodeType !== 9 ) {
return [];
}
if ( !selector || typeof selector !== "string" ) {
return results;
}
var m, set, checkSet, extra, ret, cur, pop, i,
prune = true,
contextXML = Sizzle.isXML( context ),
parts = [],
soFar = selector;
// Reset the position of the chunker regexp (start from head)
do {
chunker.exec( "" );
m = chunker.exec( soFar );
if ( m ) {
soFar = m[3];
parts.push( m[1] );
if ( m[2] ) {
extra = m[3];
break;
}
}
} while ( m );
if ( parts.length > 1 && origPOS.exec( selector ) ) {
if ( parts.length === 2 && Expr.relative[ parts[0] ] ) {
set = posProcess( parts[0] + parts[1], context, seed );
} else {
set = Expr.relative[ parts[0] ] ?
[ context ] :
Sizzle( parts.shift(), context );
while ( parts.length ) {
selector = parts.shift();
if ( Expr.relative[ selector ] ) {
selector += parts.shift();
}
set = posProcess( selector, set, seed );
}
}
} else {
// Take a shortcut and set the context if the root selector is an ID
// (but not if it'll be faster if the inner selector is an ID)
if ( !seed && parts.length > 1 && context.nodeType === 9 && !contextXML &&
Expr.match.ID.test(parts[0]) && !Expr.match.ID.test(parts[parts.length - 1]) ) {
ret = Sizzle.find( parts.shift(), context, contextXML );
context = ret.expr ?
Sizzle.filter( ret.expr, ret.set )[0] :
ret.set[0];
}
if ( context ) {
ret = seed ?
{ expr: parts.pop(), set: makeArray(seed) } :
Sizzle.find( parts.pop(), parts.length === 1 && (parts[0] === "~" || parts[0] === "+") && context.parentNode ? context.parentNode : context, contextXML );
set = ret.expr ?
Sizzle.filter( ret.expr, ret.set ) :
ret.set;
if ( parts.length > 0 ) {
checkSet = makeArray( set );
} else {
prune = false;
}
while ( parts.length ) {
cur = parts.pop();
pop = cur;
if ( !Expr.relative[ cur ] ) {
cur = "";
} else {
pop = parts.pop();
}
if ( pop == null ) {
pop = context;
}
Expr.relative[ cur ]( checkSet, pop, contextXML );
}
} else {
checkSet = parts = [];
}
}
if ( !checkSet ) {
checkSet = set;
}
if ( !checkSet ) {
Sizzle.error( cur || selector );
}
if ( toString.call(checkSet) === "[object Array]" ) {
if ( !prune ) {
results.push.apply( results, checkSet );
} else if ( context && context.nodeType === 1 ) {
for ( i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && Sizzle.contains(context, checkSet[i])) ) {
results.push( set[i] );
}
}
} else {
for ( i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && checkSet[i].nodeType === 1 ) {
results.push( set[i] );
}
}
}
} else {
makeArray( checkSet, results );
}
if ( extra ) {
Sizzle( extra, origContext, results, seed );
Sizzle.uniqueSort( results );
}
return results;
};
Sizzle.uniqueSort = function( results ) {
if ( sortOrder ) {
hasDuplicate = baseHasDuplicate;
results.sort( sortOrder );
if ( hasDuplicate ) {
for ( var i = 1; i < results.length; i++ ) {
if ( results[i] === results[ i - 1 ] ) {
results.splice( i--, 1 );
}
}
}
}
return results;
};
Sizzle.matches = function( expr, set ) {
return Sizzle( expr, null, null, set );
};
Sizzle.matchesSelector = function( node, expr ) {
return Sizzle( expr, null, null, [node] ).length > 0;
};
Sizzle.find = function( expr, context, isXML ) {
var set, i, len, match, type, left;
if ( !expr ) {
return [];
}
for ( i = 0, len = Expr.order.length; i < len; i++ ) {
type = Expr.order[i];
if ( (match = Expr.leftMatch[ type ].exec( expr )) ) {
left = match[1];
match.splice( 1, 1 );
if ( left.substr( left.length - 1 ) !== "\\" ) {
match[1] = (match[1] || "").replace( rBackslash, "" );
set = Expr.find[ type ]( match, context, isXML );
if ( set != null ) {
expr = expr.replace( Expr.match[ type ], "" );
break;
}
}
}
}
if ( !set ) {
set = typeof context.getElementsByTagName !== "undefined" ?
context.getElementsByTagName( "*" ) :
[];
}
return { set: set, expr: expr };
};
Sizzle.filter = function( expr, set, inplace, not ) {
var match, anyFound,
type, found, item, filter, left,
i, pass,
old = expr,
result = [],
curLoop = set,
isXMLFilter = set && set[0] && Sizzle.isXML( set[0] );
while ( expr && set.length ) {
for ( type in Expr.filter ) {
if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) {
filter = Expr.filter[ type ];
left = match[1];
anyFound = false;
match.splice(1,1);
if ( left.substr( left.length - 1 ) === "\\" ) {
continue;
}
if ( curLoop === result ) {
result = [];
}
if ( Expr.preFilter[ type ] ) {
match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );
if ( !match ) {
anyFound = found = true;
} else if ( match === true ) {
continue;
}
}
if ( match ) {
for ( i = 0; (item = curLoop[i]) != null; i++ ) {
if ( item ) {
found = filter( item, match, i, curLoop );
pass = not ^ found;
if ( inplace && found != null ) {
if ( pass ) {
anyFound = true;
} else {
curLoop[i] = false;
}
} else if ( pass ) {
result.push( item );
anyFound = true;
}
}
}
}
if ( found !== undefined ) {
if ( !inplace ) {
curLoop = result;
}
expr = expr.replace( Expr.match[ type ], "" );
if ( !anyFound ) {
return [];
}
break;
}
}
}
// Improper expression
if ( expr === old ) {
if ( anyFound == null ) {
Sizzle.error( expr );
} else {
break;
}
}
old = expr;
}
return curLoop;
};
Sizzle.error = function( msg ) {
throw new Error( "Syntax error, unrecognized expression: " + msg );
};
/**
* Utility function for retreiving the text value of an array of DOM nodes
* @param {Array|Element} elem
*/
var getText = Sizzle.getText = function( elem ) {
var i, node,
nodeType = elem.nodeType,
ret = "";
if ( nodeType ) {
if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) {
// Use textContent || innerText for elements
if ( typeof elem.textContent === 'string' ) {
return elem.textContent;
} else if ( typeof elem.innerText === 'string' ) {
// Replace IE's carriage returns
return elem.innerText.replace( rReturn, '' );
} else {
// Traverse it's children
for ( elem = elem.firstChild; elem; elem = elem.nextSibling) {
ret += getText( elem );
}
}
} else if ( nodeType === 3 || nodeType === 4 ) {
return elem.nodeValue;
}
} else {
// If no nodeType, this is expected to be an array
for ( i = 0; (node = elem[i]); i++ ) {
// Do not traverse comment nodes
if ( node.nodeType !== 8 ) {
ret += getText( node );
}
}
}
return ret;
};
var Expr = Sizzle.selectors = {
order: [ "ID", "NAME", "TAG" ],
match: {
ID: /#((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
CLASS: /\.((?:[\w\u00c0-\uFFFF\-]|\\.)+)/,
NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF\-]|\\.)+)['"]*\]/,
ATTR: /\[\s*((?:[\w\u00c0-\uFFFF\-]|\\.)+)\s*(?:(\S?=)\s*(?:(['"])(.*?)\3|(#?(?:[\w\u00c0-\uFFFF\-]|\\.)*)|)|)\s*\]/,
TAG: /^((?:[\w\u00c0-\uFFFF\*\-]|\\.)+)/,
CHILD: /:(only|nth|last|first)-child(?:\(\s*(even|odd|(?:[+\-]?\d+|(?:[+\-]?\d*)?n\s*(?:[+\-]\s*\d+)?))\s*\))?/,
POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^\-]|$)/,
PSEUDO: /:((?:[\w\u00c0-\uFFFF\-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/
},
leftMatch: {},
attrMap: {
"class": "className",
"for": "htmlFor"
},
attrHandle: {
href: function( elem ) {
return elem.getAttribute( "href" );
},
type: function( elem ) {
return elem.getAttribute( "type" );
}
},
relative: {
"+": function(checkSet, part){
var isPartStr = typeof part === "string",
isTag = isPartStr && !rNonWord.test( part ),
isPartStrNotTag = isPartStr && !isTag;
if ( isTag ) {
part = part.toLowerCase();
}
for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {
if ( (elem = checkSet[i]) ) {
while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}
checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ?
elem || false :
elem === part;
}
}
if ( isPartStrNotTag ) {
Sizzle.filter( part, checkSet, true );
}
},
">": function( checkSet, part ) {
var elem,
isPartStr = typeof part === "string",
i = 0,
l = checkSet.length;
if ( isPartStr && !rNonWord.test( part ) ) {
part = part.toLowerCase();
for ( ; i < l; i++ ) {
elem = checkSet[i];
if ( elem ) {
var parent = elem.parentNode;
checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false;
}
}
} else {
for ( ; i < l; i++ ) {
elem = checkSet[i];
if ( elem ) {
checkSet[i] = isPartStr ?
elem.parentNode :
elem.parentNode === part;
}
}
if ( isPartStr ) {
Sizzle.filter( part, checkSet, true );
}
}
},
"": function(checkSet, part, isXML){
var nodeCheck,
doneName = done++,
checkFn = dirCheck;
if ( typeof part === "string" && !rNonWord.test( part ) ) {
part = part.toLowerCase();
nodeCheck = part;
checkFn = dirNodeCheck;
}
checkFn( "parentNode", part, doneName, checkSet, nodeCheck, isXML );
},
"~": function( checkSet, part, isXML ) {
var nodeCheck,
doneName = done++,
checkFn = dirCheck;
if ( typeof part === "string" && !rNonWord.test( part ) ) {
part = part.toLowerCase();
nodeCheck = part;
checkFn = dirNodeCheck;
}
checkFn( "previousSibling", part, doneName, checkSet, nodeCheck, isXML );
}
},
find: {
ID: function( match, context, isXML ) {
if ( typeof context.getElementById !== "undefined" && !isXML ) {
var m = context.getElementById(match[1]);
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
return m && m.parentNode ? [m] : [];
}
},
NAME: function( match, context ) {
if ( typeof context.getElementsByName !== "undefined" ) {
var ret = [],
results = context.getElementsByName( match[1] );
for ( var i = 0, l = results.length; i < l; i++ ) {
if ( results[i].getAttribute("name") === match[1] ) {
ret.push( results[i] );
}
}
return ret.length === 0 ? null : ret;
}
},
TAG: function( match, context ) {
if ( typeof context.getElementsByTagName !== "undefined" ) {
return context.getElementsByTagName( match[1] );
}
}
},
preFilter: {
CLASS: function( match, curLoop, inplace, result, not, isXML ) {
match = " " + match[1].replace( rBackslash, "" ) + " ";
if ( isXML ) {
return match;
}
for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
if ( elem ) {
if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n\r]/g, " ").indexOf(match) >= 0) ) {
if ( !inplace ) {
result.push( elem );
}
} else if ( inplace ) {
curLoop[i] = false;
}
}
}
return false;
},
ID: function( match ) {
return match[1].replace( rBackslash, "" );
},
TAG: function( match, curLoop ) {
return match[1].replace( rBackslash, "" ).toLowerCase();
},
CHILD: function( match ) {
if ( match[1] === "nth" ) {
if ( !match[2] ) {
Sizzle.error( match[0] );
}
match[2] = match[2].replace(/^\+|\s*/g, '');
// parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
var test = /(-?)(\d*)(?:n([+\-]?\d*))?/.exec(
match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" ||
!/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);
// calculate the numbers (first)n+(last) including if they are negative
match[2] = (test[1] + (test[2] || 1)) - 0;
match[3] = test[3] - 0;
}
else if ( match[2] ) {
Sizzle.error( match[0] );
}
// TODO: Move to normal caching system
match[0] = done++;
return match;
},
ATTR: function( match, curLoop, inplace, result, not, isXML ) {
var name = match[1] = match[1].replace( rBackslash, "" );
if ( !isXML && Expr.attrMap[name] ) {
match[1] = Expr.attrMap[name];
}
// Handle if an un-quoted value was used
match[4] = ( match[4] || match[5] || "" ).replace( rBackslash, "" );
if ( match[2] === "~=" ) {
match[4] = " " + match[4] + " ";
}
return match;
},
PSEUDO: function( match, curLoop, inplace, result, not ) {
if ( match[1] === "not" ) {
// If we're dealing with a complex expression, or a simple one
if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) {
match[3] = Sizzle(match[3], null, null, curLoop);
} else {
var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);
if ( !inplace ) {
result.push.apply( result, ret );
}
return false;
}
} else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {
return true;
}
return match;
},
POS: function( match ) {
match.unshift( true );
return match;
}
},
filters: {
enabled: function( elem ) {
return elem.disabled === false && elem.type !== "hidden";
},
disabled: function( elem ) {
return elem.disabled === true;
},
checked: function( elem ) {
return elem.checked === true;
},
selected: function( elem ) {
// Accessing this property makes selected-by-default
// options in Safari work properly
if ( elem.parentNode ) {
elem.parentNode.selectedIndex;
}
return elem.selected === true;
},
parent: function( elem ) {
return !!elem.firstChild;
},
empty: function( elem ) {
return !elem.firstChild;
},
has: function( elem, i, match ) {
return !!Sizzle( match[3], elem ).length;
},
header: function( elem ) {
return (/h\d/i).test( elem.nodeName );
},
text: function( elem ) {
var attr = elem.getAttribute( "type" ), type = elem.type;
// IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc)
// use getAttribute instead to test this case
return elem.nodeName.toLowerCase() === "input" && "text" === type && ( attr === type || attr === null );
},
radio: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "radio" === elem.type;
},
checkbox: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "checkbox" === elem.type;
},
file: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "file" === elem.type;
},
password: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "password" === elem.type;
},
submit: function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && "submit" === elem.type;
},
image: function( elem ) {
return elem.nodeName.toLowerCase() === "input" && "image" === elem.type;
},
reset: function( elem ) {
var name = elem.nodeName.toLowerCase();
return (name === "input" || name === "button") && "reset" === elem.type;
},
button: function( elem ) {
var name = elem.nodeName.toLowerCase();
return name === "input" && "button" === elem.type || name === "button";
},
input: function( elem ) {
return (/input|select|textarea|button/i).test( elem.nodeName );
},
focus: function( elem ) {
return elem === elem.ownerDocument.activeElement;
}
},
setFilters: {
first: function( elem, i ) {
return i === 0;
},
last: function( elem, i, match, array ) {
return i === array.length - 1;
},
even: function( elem, i ) {
return i % 2 === 0;
},
odd: function( elem, i ) {
return i % 2 === 1;
},
lt: function( elem, i, match ) {
return i < match[3] - 0;
},
gt: function( elem, i, match ) {
return i > match[3] - 0;
},
nth: function( elem, i, match ) {
return match[3] - 0 === i;
},
eq: function( elem, i, match ) {
return match[3] - 0 === i;
}
},
filter: {
PSEUDO: function( elem, match, i, array ) {
var name = match[1],
filter = Expr.filters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
} else if ( name === "contains" ) {
return (elem.textContent || elem.innerText || getText([ elem ]) || "").indexOf(match[3]) >= 0;
} else if ( name === "not" ) {
var not = match[3];
for ( var j = 0, l = not.length; j < l; j++ ) {
if ( not[j] === elem ) {
return false;
}
}
return true;
} else {
Sizzle.error( name );
}
},
CHILD: function( elem, match ) {
var first, last,
doneName, parent, cache,
count, diff,
type = match[1],
node = elem;
switch ( type ) {
case "only":
case "first":
while ( (node = node.previousSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
if ( type === "first" ) {
return true;
}
node = elem;
/* falls through */
case "last":
while ( (node = node.nextSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
return true;
case "nth":
first = match[2];
last = match[3];
if ( first === 1 && last === 0 ) {
return true;
}
doneName = match[0];
parent = elem.parentNode;
if ( parent && (parent[ expando ] !== doneName || !elem.nodeIndex) ) {
count = 0;
for ( node = parent.firstChild; node; node = node.nextSibling ) {
if ( node.nodeType === 1 ) {
node.nodeIndex = ++count;
}
}
parent[ expando ] = doneName;
}
diff = elem.nodeIndex - last;
if ( first === 0 ) {
return diff === 0;
} else {
return ( diff % first === 0 && diff / first >= 0 );
}
}
},
ID: function( elem, match ) {
return elem.nodeType === 1 && elem.getAttribute("id") === match;
},
TAG: function( elem, match ) {
return (match === "*" && elem.nodeType === 1) || !!elem.nodeName && elem.nodeName.toLowerCase() === match;
},
CLASS: function( elem, match ) {
return (" " + (elem.className || elem.getAttribute("class")) + " ")
.indexOf( match ) > -1;
},
ATTR: function( elem, match ) {
var name = match[1],
result = Sizzle.attr ?
Sizzle.attr( elem, name ) :
Expr.attrHandle[ name ] ?
Expr.attrHandle[ name ]( elem ) :
elem[ name ] != null ?
elem[ name ] :
elem.getAttribute( name ),
value = result + "",
type = match[2],
check = match[4];
return result == null ?
type === "!=" :
!type && Sizzle.attr ?
result != null :
type === "=" ?
value === check :
type === "*=" ?
value.indexOf(check) >= 0 :
type === "~=" ?
(" " + value + " ").indexOf(check) >= 0 :
!check ?
value && result !== false :
type === "!=" ?
value !== check :
type === "^=" ?
value.indexOf(check) === 0 :
type === "$=" ?
value.substr(value.length - check.length) === check :
type === "|=" ?
value === check || value.substr(0, check.length + 1) === check + "-" :
false;
},
POS: function( elem, match, i, array ) {
var name = match[2],
filter = Expr.setFilters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
}
}
}
};
var origPOS = Expr.match.POS,
fescape = function(all, num){
return "\\" + (num - 0 + 1);
};
for ( var type in Expr.match ) {
Expr.match[ type ] = new RegExp( Expr.match[ type ].source + (/(?![^\[]*\])(?![^\(]*\))/.source) );
Expr.leftMatch[ type ] = new RegExp( /(^(?:.|\r|\n)*?)/.source + Expr.match[ type ].source.replace(/\\(\d+)/g, fescape) );
}
// Expose origPOS
// "global" as in regardless of relation to brackets/parens
Expr.match.globalPOS = origPOS;
var makeArray = function( array, results ) {
array = Array.prototype.slice.call( array, 0 );
if ( results ) {
results.push.apply( results, array );
return results;
}
return array;
};
// Perform a simple check to determine if the browser is capable of
// converting a NodeList to an array using builtin methods.
// Also verifies that the returned array holds DOM nodes
// (which is not the case in the Blackberry browser)
try {
Array.prototype.slice.call( document.documentElement.childNodes, 0 )[0].nodeType;
// Provide a fallback method if it does not work
} catch( e ) {
makeArray = function( array, results ) {
var i = 0,
ret = results || [];
if ( toString.call(array) === "[object Array]" ) {
Array.prototype.push.apply( ret, array );
} else {
if ( typeof array.length === "number" ) {
for ( var l = array.length; i < l; i++ ) {
ret.push( array[i] );
}
} else {
for ( ; array[i]; i++ ) {
ret.push( array[i] );
}
}
}
return ret;
};
}
var sortOrder, siblingCheck;
if ( document.documentElement.compareDocumentPosition ) {
sortOrder = function( a, b ) {
if ( a === b ) {
hasDuplicate = true;
return 0;
}
if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) {
return a.compareDocumentPosition ? -1 : 1;
}
return a.compareDocumentPosition(b) & 4 ? -1 : 1;
};
} else {
sortOrder = function( a, b ) {
// The nodes are identical, we can exit early
if ( a === b ) {
hasDuplicate = true;
return 0;
// Fallback to using sourceIndex (in IE) if it's available on both nodes
} else if ( a.sourceIndex && b.sourceIndex ) {
return a.sourceIndex - b.sourceIndex;
}
var al, bl,
ap = [],
bp = [],
aup = a.parentNode,
bup = b.parentNode,
cur = aup;
// If the nodes are siblings (or identical) we can do a quick check
if ( aup === bup ) {
return siblingCheck( a, b );
// If no parents were found then the nodes are disconnected
} else if ( !aup ) {
return -1;
} else if ( !bup ) {
return 1;
}
// Otherwise they're somewhere else in the tree so we need
// to build up a full list of the parentNodes for comparison
while ( cur ) {
ap.unshift( cur );
cur = cur.parentNode;
}
cur = bup;
while ( cur ) {
bp.unshift( cur );
cur = cur.parentNode;
}
al = ap.length;
bl = bp.length;
// Start walking down the tree looking for a discrepancy
for ( var i = 0; i < al && i < bl; i++ ) {
if ( ap[i] !== bp[i] ) {
return siblingCheck( ap[i], bp[i] );
}
}
// We ended someplace up the tree so do a sibling check
return i === al ?
siblingCheck( a, bp[i], -1 ) :
siblingCheck( ap[i], b, 1 );
};
siblingCheck = function( a, b, ret ) {
if ( a === b ) {
return ret;
}
var cur = a.nextSibling;
while ( cur ) {
if ( cur === b ) {
return -1;
}
cur = cur.nextSibling;
}
return 1;
};
}
// Check to see if the browser returns elements by name when
// querying by getElementById (and provide a workaround)
(function(){
// We're going to inject a fake input element with a specified name
var form = document.createElement("div"),
id = "script" + (new Date()).getTime(),
root = document.documentElement;
form.innerHTML = "<a name='" + id + "'/>";
// Inject it into the root element, check its status, and remove it quickly
root.insertBefore( form, root.firstChild );
// The workaround has to do additional checks after a getElementById
// Which slows things down for other browsers (hence the branching)
if ( document.getElementById( id ) ) {
Expr.find.ID = function( match, context, isXML ) {
if ( typeof context.getElementById !== "undefined" && !isXML ) {
var m = context.getElementById(match[1]);
return m ?
m.id === match[1] || typeof m.getAttributeNode !== "undefined" && m.getAttributeNode("id").nodeValue === match[1] ?
[m] :
undefined :
[];
}
};
Expr.filter.ID = function( elem, match ) {
var node = typeof elem.getAttributeNode !== "undefined" && elem.getAttributeNode("id");
return elem.nodeType === 1 && node && node.nodeValue === match;
};
}
root.removeChild( form );
// release memory in IE
root = form = null;
})();
(function(){
// Check to see if the browser returns only elements
// when doing getElementsByTagName("*")
// Create a fake element
var div = document.createElement("div");
div.appendChild( document.createComment("") );
// Make sure no comments are found
if ( div.getElementsByTagName("*").length > 0 ) {
Expr.find.TAG = function( match, context ) {
var results = context.getElementsByTagName( match[1] );
// Filter out possible comments
if ( match[1] === "*" ) {
var tmp = [];
for ( var i = 0; results[i]; i++ ) {
if ( results[i].nodeType === 1 ) {
tmp.push( results[i] );
}
}
results = tmp;
}
return results;
};
}
// Check to see if an attribute returns normalized href attributes
div.innerHTML = "<a href='#'></a>";
if ( div.firstChild && typeof div.firstChild.getAttribute !== "undefined" &&
div.firstChild.getAttribute("href") !== "#" ) {
Expr.attrHandle.href = function( elem ) {
return elem.getAttribute( "href", 2 );
};
}
// release memory in IE
div = null;
})();
if ( document.querySelectorAll ) {
(function(){
var oldSizzle = Sizzle,
div = document.createElement("div"),
id = "__sizzle__";
div.innerHTML = "<p class='TEST'></p>";
// Safari can't handle uppercase or unicode characters when
// in quirks mode.
if ( div.querySelectorAll && div.querySelectorAll(".TEST").length === 0 ) {
return;
}
Sizzle = function( query, context, extra, seed ) {
context = context || document;
// Only use querySelectorAll on non-XML documents
// (ID selectors don't work in non-HTML documents)
if ( !seed && !Sizzle.isXML(context) ) {
// See if we find a selector to speed up
var match = /^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec( query );
if ( match && (context.nodeType === 1 || context.nodeType === 9) ) {
// Speed-up: Sizzle("TAG")
if ( match[1] ) {
return makeArray( context.getElementsByTagName( query ), extra );
// Speed-up: Sizzle(".CLASS")
} else if ( match[2] && Expr.find.CLASS && context.getElementsByClassName ) {
return makeArray( context.getElementsByClassName( match[2] ), extra );
}
}
if ( context.nodeType === 9 ) {
// Speed-up: Sizzle("body")
// The body element only exists once, optimize finding it
if ( query === "body" && context.body ) {
return makeArray( [ context.body ], extra );
// Speed-up: Sizzle("#ID")
} else if ( match && match[3] ) {
var elem = context.getElementById( match[3] );
// Check parentNode to catch when Blackberry 4.6 returns
// nodes that are no longer in the document #6963
if ( elem && elem.parentNode ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id === match[3] ) {
return makeArray( [ elem ], extra );
}
} else {
return makeArray( [], extra );
}
}
try {
return makeArray( context.querySelectorAll(query), extra );
} catch(qsaError) {}
// qSA works strangely on Element-rooted queries
// We can work around this by specifying an extra ID on the root
// and working up from there (Thanks to Andrew Dupont for the technique)
// IE 8 doesn't work on object elements
} else if ( context.nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) {
var oldContext = context,
old = context.getAttribute( "id" ),
nid = old || id,
hasParent = context.parentNode,
relativeHierarchySelector = /^\s*[+~]/.test( query );
if ( !old ) {
context.setAttribute( "id", nid );
} else {
nid = nid.replace( /'/g, "\\$&" );
}
if ( relativeHierarchySelector && hasParent ) {
context = context.parentNode;
}
try {
if ( !relativeHierarchySelector || hasParent ) {
return makeArray( context.querySelectorAll( "[id='" + nid + "'] " + query ), extra );
}
} catch(pseudoError) {
} finally {
if ( !old ) {
oldContext.removeAttribute( "id" );
}
}
}
}
return oldSizzle(query, context, extra, seed);
};
for ( var prop in oldSizzle ) {
Sizzle[ prop ] = oldSizzle[ prop ];
}
// release memory in IE
div = null;
})();
}
(function(){
var html = document.documentElement,
matches = html.matchesSelector || html.mozMatchesSelector || html.webkitMatchesSelector || html.msMatchesSelector;
if ( matches ) {
// Check to see if it's possible to do matchesSelector
// on a disconnected node (IE 9 fails this)
var disconnectedMatch = !matches.call( document.createElement( "div" ), "div" ),
pseudoWorks = false;
try {
// This should fail with an exception
// Gecko does not error, returns false instead
matches.call( document.documentElement, "[test!='']:sizzle" );
} catch( pseudoError ) {
pseudoWorks = true;
}
Sizzle.matchesSelector = function( node, expr ) {
// Make sure that attribute selectors are quoted
expr = expr.replace(/\=\s*([^'"\]]*)\s*\]/g, "='$1']");
if ( !Sizzle.isXML( node ) ) {
try {
if ( pseudoWorks || !Expr.match.PSEUDO.test( expr ) && !/!=/.test( expr ) ) {
var ret = matches.call( node, expr );
// IE 9's matchesSelector returns false on disconnected nodes
if ( ret || !disconnectedMatch ||
// As well, disconnected nodes are said to be in a document
// fragment in IE 9, so check for that
node.document && node.document.nodeType !== 11 ) {
return ret;
}
}
} catch(e) {}
}
return Sizzle(expr, null, null, [node]).length > 0;
};
}
})();
(function(){
var div = document.createElement("div");
div.innerHTML = "<div class='test e'></div><div class='test'></div>";
// Opera can't find a second classname (in 9.6)
// Also, make sure that getElementsByClassName actually exists
if ( !div.getElementsByClassName || div.getElementsByClassName("e").length === 0 ) {
return;
}
// Safari caches class attributes, doesn't catch changes (in 3.2)
div.lastChild.className = "e";
if ( div.getElementsByClassName("e").length === 1 ) {
return;
}
Expr.order.splice(1, 0, "CLASS");
Expr.find.CLASS = function( match, context, isXML ) {
if ( typeof context.getElementsByClassName !== "undefined" && !isXML ) {
return context.getElementsByClassName(match[1]);
}
};
// release memory in IE
div = null;
})();
function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
var match = false;
elem = elem[dir];
while ( elem ) {
if ( elem[ expando ] === doneName ) {
match = checkSet[elem.sizset];
break;
}
if ( elem.nodeType === 1 && !isXML ){
elem[ expando ] = doneName;
elem.sizset = i;
}
if ( elem.nodeName.toLowerCase() === cur ) {
match = elem;
break;
}
elem = elem[dir];
}
checkSet[i] = match;
}
}
}
function dirCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
var match = false;
elem = elem[dir];
while ( elem ) {
if ( elem[ expando ] === doneName ) {
match = checkSet[elem.sizset];
break;
}
if ( elem.nodeType === 1 ) {
if ( !isXML ) {
elem[ expando ] = doneName;
elem.sizset = i;
}
if ( typeof cur !== "string" ) {
if ( elem === cur ) {
match = true;
break;
}
} else if ( Sizzle.filter( cur, [elem] ).length > 0 ) {
match = elem;
break;
}
}
elem = elem[dir];
}
checkSet[i] = match;
}
}
}
if ( document.documentElement.contains ) {
Sizzle.contains = function( a, b ) {
return a !== b && (a.contains ? a.contains(b) : true);
};
} else if ( document.documentElement.compareDocumentPosition ) {
Sizzle.contains = function( a, b ) {
return !!(a.compareDocumentPosition(b) & 16);
};
} else {
Sizzle.contains = function() {
return false;
};
}
Sizzle.isXML = function( elem ) {
// documentElement is verified for cases where it doesn't yet exist
// (such as loading iframes in IE - #4833)
var documentElement = (elem ? elem.ownerDocument || elem : 0).documentElement;
return documentElement ? documentElement.nodeName !== "HTML" : false;
};
var posProcess = function( selector, context, seed ) {
var match,
tmpSet = [],
later = "",
root = context.nodeType ? [context] : context;
// Position selectors must be done after the filter
// And so must :not(positional) so we move all PSEUDOs to the end
while ( (match = Expr.match.PSEUDO.exec( selector )) ) {
later += match[0];
selector = selector.replace( Expr.match.PSEUDO, "" );
}
selector = Expr.relative[selector] ? selector + "*" : selector;
for ( var i = 0, l = root.length; i < l; i++ ) {
Sizzle( selector, root[i], tmpSet, seed );
}
return Sizzle.filter( later, tmpSet );
};
// EXPOSE
// Override sizzle attribute retrieval
Sizzle.attr = jQuery.attr;
Sizzle.selectors.attrMap = {};
jQuery.find = Sizzle;
jQuery.expr = Sizzle.selectors;
jQuery.expr[":"] = jQuery.expr.filters;
jQuery.unique = Sizzle.uniqueSort;
jQuery.text = Sizzle.getText;
jQuery.isXMLDoc = Sizzle.isXML;
jQuery.contains = Sizzle.contains;
})();
var runtil = /Until$/,
rparentsprev = /^(?:parents|prevUntil|prevAll)/,
// Note: This RegExp should be improved, or likely pulled from Sizzle
rmultiselector = /,/,
isSimple = /^.[^:#\[\.,]*$/,
slice = Array.prototype.slice,
POS = jQuery.expr.match.globalPOS,
// methods guaranteed to produce a unique set when starting from a unique set
guaranteedUnique = {
children: true,
contents: true,
next: true,
prev: true
};
jQuery.fn.extend({
find: function( selector ) {
var self = this,
i, l;
if ( typeof selector !== "string" ) {
return jQuery( selector ).filter(function() {
for ( i = 0, l = self.length; i < l; i++ ) {
if ( jQuery.contains( self[ i ], this ) ) {
return true;
}
}
});
}
var ret = this.pushStack( "", "find", selector ),
length, n, r;
for ( i = 0, l = this.length; i < l; i++ ) {
length = ret.length;
jQuery.find( selector, this[i], ret );
if ( i > 0 ) {
// Make sure that the results are unique
for ( n = length; n < ret.length; n++ ) {
for ( r = 0; r < length; r++ ) {
if ( ret[r] === ret[n] ) {
ret.splice(n--, 1);
break;
}
}
}
}
}
return ret;
},
has: function( target ) {
var targets = jQuery( target );
return this.filter(function() {
for ( var i = 0, l = targets.length; i < l; i++ ) {
if ( jQuery.contains( this, targets[i] ) ) {
return true;
}
}
});
},
not: function( selector ) {
return this.pushStack( winnow(this, selector, false), "not", selector);
},
filter: function( selector ) {
return this.pushStack( winnow(this, selector, true), "filter", selector );
},
is: function( selector ) {
return !!selector && (
typeof selector === "string" ?
// If this is a positional selector, check membership in the returned set
// so $("p:first").is("p:last") won't return true for a doc with two "p".
POS.test( selector ) ?
jQuery( selector, this.context ).index( this[0] ) >= 0 :
jQuery.filter( selector, this ).length > 0 :
this.filter( selector ).length > 0 );
},
closest: function( selectors, context ) {
var ret = [], i, l, cur = this[0];
// Array (deprecated as of jQuery 1.7)
if ( jQuery.isArray( selectors ) ) {
var level = 1;
while ( cur && cur.ownerDocument && cur !== context ) {
for ( i = 0; i < selectors.length; i++ ) {
if ( jQuery( cur ).is( selectors[ i ] ) ) {
ret.push({ selector: selectors[ i ], elem: cur, level: level });
}
}
cur = cur.parentNode;
level++;
}
return ret;
}
// String
var pos = POS.test( selectors ) || typeof selectors !== "string" ?
jQuery( selectors, context || this.context ) :
0;
for ( i = 0, l = this.length; i < l; i++ ) {
cur = this[i];
while ( cur ) {
if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) {
ret.push( cur );
break;
} else {
cur = cur.parentNode;
if ( !cur || !cur.ownerDocument || cur === context || cur.nodeType === 11 ) {
break;
}
}
}
}
ret = ret.length > 1 ? jQuery.unique( ret ) : ret;
return this.pushStack( ret, "closest", selectors );
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
// No argument, return index in parent
if ( !elem ) {
return ( this[0] && this[0].parentNode ) ? this.prevAll().length : -1;
}
// index in selector
if ( typeof elem === "string" ) {
return jQuery.inArray( this[0], jQuery( elem ) );
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem, this );
},
add: function( selector, context ) {
var set = typeof selector === "string" ?
jQuery( selector, context ) :
jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ),
all = jQuery.merge( this.get(), set );
return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ?
all :
jQuery.unique( all ) );
},
andSelf: function() {
return this.add( this.prevObject );
}
});
// A painfully simple check to see if an element is disconnected
// from a document (should be improved, where feasible).
function isDisconnected( node ) {
return !node || !node.parentNode || node.parentNode.nodeType === 11;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return jQuery.nth( elem, 2, "nextSibling" );
},
prev: function( elem ) {
return jQuery.nth( elem, 2, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.makeArray( elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until );
if ( !runtil.test( name ) ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret;
if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret, name, slice.call( arguments ).join(",") );
};
});
jQuery.extend({
filter: function( expr, elems, not ) {
if ( not ) {
expr = ":not(" + expr + ")";
}
return elems.length === 1 ?
jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] :
jQuery.find.matches(expr, elems);
},
dir: function( elem, dir, until ) {
var matched = [],
cur = elem[ dir ];
while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) {
if ( cur.nodeType === 1 ) {
matched.push( cur );
}
cur = cur[dir];
}
return matched;
},
nth: function( cur, result, dir, elem ) {
result = result || 1;
var num = 0;
for ( ; cur; cur = cur[dir] ) {
if ( cur.nodeType === 1 && ++num === result ) {
break;
}
}
return cur;
},
sibling: function( n, elem ) {
var r = [];
for ( ; n; n = n.nextSibling ) {
if ( n.nodeType === 1 && n !== elem ) {
r.push( n );
}
}
return r;
}
});
// Implement the identical functionality for filter and not
function winnow( elements, qualifier, keep ) {
// Can't pass null or undefined to indexOf in Firefox 4
// Set to 0 to skip string check
qualifier = qualifier || 0;
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep(elements, function( elem, i ) {
var retVal = !!qualifier.call( elem, i, elem );
return retVal === keep;
});
} else if ( qualifier.nodeType ) {
return jQuery.grep(elements, function( elem, i ) {
return ( elem === qualifier ) === keep;
});
} else if ( typeof qualifier === "string" ) {
var filtered = jQuery.grep(elements, function( elem ) {
return elem.nodeType === 1;
});
if ( isSimple.test( qualifier ) ) {
return jQuery.filter(qualifier, filtered, !keep);
} else {
qualifier = jQuery.filter( qualifier, filtered );
}
}
return jQuery.grep(elements, function( elem, i ) {
return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep;
});
}
function createSafeFragment( document ) {
var list = nodeNames.split( "|" ),
safeFrag = document.createDocumentFragment();
if ( safeFrag.createElement ) {
while ( list.length ) {
safeFrag.createElement(
list.pop()
);
}
}
return safeFrag;
}
var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" +
"header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",
rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g,
rleadingWhitespace = /^\s+/,
rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnoInnerhtml = /<(?:script|style)/i,
rnocache = /<(?:script|object|embed|option|style)/i,
rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"),
// checked="checked" or checked
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i,
rscriptType = /\/(java|ecma)script/i,
rcleanScript = /^\s*<!(?:\[CDATA\[|\-\-)/,
wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
area: [ 1, "<map>", "</map>" ],
_default: [ 0, "", "" ]
},
safeFragment = createSafeFragment( document );
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
// IE can't serialize <link> and <script> tags normally
if ( !jQuery.support.htmlSerialize ) {
wrapMap._default = [ 1, "div<div>", "</div>" ];
}
jQuery.fn.extend({
text: function( 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.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 ) {
this.insertBefore( elem, this.firstChild );
}
});
},
before: function() {
if ( this[0] && this[0].parentNode ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this );
});
} else if ( arguments.length ) {
var set = jQuery.clean( arguments );
set.push.apply( set, this.toArray() );
return this.pushStack( set, "before", arguments );
}
},
after: function() {
if ( this[0] && this[0].parentNode ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this.nextSibling );
});
} else if ( arguments.length ) {
var set = this.pushStack( this, "after", arguments );
set.push.apply( set, jQuery.clean(arguments) );
return set;
}
},
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
jQuery.cleanData( [ elem ] );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
}
}
return this;
},
empty: function() {
for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
}
return this;
},
clone: function( dataAndEvents, deepDataAndEvents ) {
dataAndEvents = dataAndEvents == null ? false : dataAndEvents;
deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents;
return this.map( function () {
return jQuery.clone( this, dataAndEvents, deepDataAndEvents );
});
},
html: function( value ) {
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, "" ) :
null;
}
if ( typeof value === "string" && !rnoInnerhtml.test( value ) &&
( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) &&
!wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) {
value = value.replace( rxhtmlTag, "<$1></$2>" );
try {
for (; 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 ( this[0] && this[0].parentNode ) {
// Make sure that the elements are removed from the DOM before they are inserted
// this can help fix replacing a parent with child elements
if ( jQuery.isFunction( value ) ) {
return this.each(function(i) {
var self = jQuery(this), old = self.html();
self.replaceWith( value.call( this, i, old ) );
});
}
if ( typeof value !== "string" ) {
value = jQuery( value ).detach();
}
return this.each(function() {
var next = this.nextSibling,
parent = this.parentNode;
jQuery( this ).remove();
if ( next ) {
jQuery(next).before( value );
} else {
jQuery(parent).append( value );
}
});
} else {
return this.length ?
this.pushStack( jQuery(jQuery.isFunction(value) ? value() : value), "replaceWith", value ) :
this;
}
},
detach: function( selector ) {
return this.remove( selector, true );
},
domManip: function( args, table, callback ) {
var results, first, fragment, parent,
value = args[0],
scripts = [];
// We can't cloneNode fragments that contain checked, in WebKit
if ( !jQuery.support.checkClone && arguments.length === 3 && typeof value === "string" && rchecked.test( value ) ) {
return this.each(function() {
jQuery(this).domManip( args, table, callback, true );
});
}
if ( jQuery.isFunction(value) ) {
return this.each(function(i) {
var self = jQuery(this);
args[0] = value.call(this, i, table ? self.html() : undefined);
self.domManip( args, table, callback );
});
}
if ( this[0] ) {
parent = value && value.parentNode;
// If we're in a fragment, just use that instead of building a new one
if ( jQuery.support.parentNode && parent && parent.nodeType === 11 && parent.childNodes.length === this.length ) {
results = { fragment: parent };
} else {
results = jQuery.buildFragment( args, this, scripts );
}
fragment = results.fragment;
if ( fragment.childNodes.length === 1 ) {
first = fragment = fragment.firstChild;
} else {
first = fragment.firstChild;
}
if ( first ) {
table = table && jQuery.nodeName( first, "tr" );
for ( var i = 0, l = this.length, lastIndex = l - 1; i < l; i++ ) {
callback.call(
table ?
root(this[i], first) :
this[i],
// Make sure that we do not leak memory by inadvertently discarding
// the original fragment (which might have attached data) instead of
// using it; in addition, use the original fragment object for the last
// item instead of first because it can end up being emptied incorrectly
// in certain situations (Bug #8070).
// Fragments from the fragment cache must always be cloned and never used
// in place.
results.cacheable || ( l > 1 && i < lastIndex ) ?
jQuery.clone( fragment, true, true ) :
fragment
);
}
}
if ( scripts.length ) {
jQuery.each( scripts, function( i, elem ) {
if ( elem.src ) {
jQuery.ajax({
type: "GET",
global: false,
url: elem.src,
async: false,
dataType: "script"
});
} else {
jQuery.globalEval( ( elem.text || elem.textContent || elem.innerHTML || "" ).replace( rcleanScript, "/*$0*/" ) );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
});
}
}
return this;
}
});
function root( elem, cur ) {
return jQuery.nodeName(elem, "table") ?
(elem.getElementsByTagName("tbody")[0] ||
elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
elem;
}
function cloneCopyEvent( src, dest ) {
if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) {
return;
}
var type, i, l,
oldData = jQuery._data( src ),
curData = jQuery._data( dest, oldData ),
events = oldData.events;
if ( events ) {
delete curData.handle;
curData.events = {};
for ( type in events ) {
for ( i = 0, l = events[ type ].length; i < l; i++ ) {
jQuery.event.add( dest, type, events[ type ][ i ] );
}
}
}
// make the cloned public data object a copy from the original
if ( curData.data ) {
curData.data = jQuery.extend( {}, curData.data );
}
}
function cloneFixAttributes( src, dest ) {
var nodeName;
// We do not need to do anything for non-Elements
if ( dest.nodeType !== 1 ) {
return;
}
// clearAttributes removes the attributes, which we don't want,
// but also removes the attachEvent events, which we *do* want
if ( dest.clearAttributes ) {
dest.clearAttributes();
}
// mergeAttributes, in contrast, only merges back on the
// original attributes, not the events
if ( dest.mergeAttributes ) {
dest.mergeAttributes( src );
}
nodeName = dest.nodeName.toLowerCase();
// IE6-8 fail to clone children inside object elements that use
// the proprietary classid attribute value (rather than the type
// attribute) to identify the type of content to display
if ( nodeName === "object" ) {
dest.outerHTML = src.outerHTML;
} else if ( nodeName === "input" && (src.type === "checkbox" || src.type === "radio") ) {
// IE6-8 fails to persist the checked state of a cloned checkbox
// or radio button. Worse, IE6-7 fail to give the cloned element
// a checked appearance if the defaultChecked value isn't also set
if ( src.checked ) {
dest.defaultChecked = dest.checked = src.checked;
}
// IE6-7 get confused and end up setting the value of a cloned
// checkbox/radio button to an empty string instead of "on"
if ( dest.value !== src.value ) {
dest.value = src.value;
}
// IE6-8 fails to return the selected option to the default selected
// state when cloning options
} else if ( nodeName === "option" ) {
dest.selected = src.defaultSelected;
// IE6-8 fails to set the defaultValue to the correct value when
// cloning other types of input fields
} else if ( nodeName === "input" || nodeName === "textarea" ) {
dest.defaultValue = src.defaultValue;
// 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 );
// Clear flags for bubbling special change/submit events, they must
// be reattached when the newly cloned events are first activated
dest.removeAttribute( "_submit_attached" );
dest.removeAttribute( "_change_attached" );
}
jQuery.buildFragment = function( args, nodes, scripts ) {
var fragment, cacheable, cacheresults, doc,
first = args[ 0 ];
// nodes may contain either an explicit document object,
// a jQuery collection or context object.
// If nodes[0] contains a valid object to assign to doc
if ( nodes && nodes[0] ) {
doc = nodes[0].ownerDocument || nodes[0];
}
// Ensure that an attr object doesn't incorrectly stand in as a document object
// Chrome and Firefox seem to allow this to occur and will throw exception
// Fixes #8950
if ( !doc.createDocumentFragment ) {
doc = document;
}
// Only cache "small" (1/2 KB) HTML strings that are associated with the main document
// Cloning options loses the selected state, so don't cache them
// IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
// Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
// Lastly, IE6,7,8 will not correctly reuse cached fragments that were created from unknown elems #10501
if ( args.length === 1 && typeof first === "string" && first.length < 512 && doc === document &&
first.charAt(0) === "<" && !rnocache.test( first ) &&
(jQuery.support.checkClone || !rchecked.test( first )) &&
(jQuery.support.html5Clone || !rnoshimcache.test( first )) ) {
cacheable = true;
cacheresults = jQuery.fragments[ first ];
if ( cacheresults && cacheresults !== 1 ) {
fragment = cacheresults;
}
}
if ( !fragment ) {
fragment = doc.createDocumentFragment();
jQuery.clean( args, doc, fragment, scripts );
}
if ( cacheable ) {
jQuery.fragments[ first ] = cacheresults ? fragment : 1;
}
return { fragment: fragment, cacheable: cacheable };
};
jQuery.fragments = {};
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var ret = [],
insert = jQuery( selector ),
parent = this.length === 1 && this[0].parentNode;
if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) {
insert[ original ]( this[0] );
return this;
} else {
for ( var i = 0, l = insert.length; i < l; i++ ) {
var elems = ( i > 0 ? this.clone(true) : this ).get();
jQuery( insert[i] )[ original ]( elems );
ret = ret.concat( elems );
}
return this.pushStack( ret, name, insert.selector );
}
};
});
function getAll( elem ) {
if ( typeof elem.getElementsByTagName !== "undefined" ) {
return elem.getElementsByTagName( "*" );
} else if ( typeof elem.querySelectorAll !== "undefined" ) {
return elem.querySelectorAll( "*" );
} else {
return [];
}
}
// Used in clean, fixes the defaultChecked property
function fixDefaultChecked( elem ) {
if ( elem.type === "checkbox" || elem.type === "radio" ) {
elem.defaultChecked = elem.checked;
}
}
// Finds all inputs and passes them to fixDefaultChecked
function findInputs( elem ) {
var nodeName = ( elem.nodeName || "" ).toLowerCase();
if ( nodeName === "input" ) {
fixDefaultChecked( elem );
// Skip scripts, get other children
} else if ( nodeName !== "script" && typeof elem.getElementsByTagName !== "undefined" ) {
jQuery.grep( elem.getElementsByTagName("input"), fixDefaultChecked );
}
}
// Derived From: http://www.iecss.com/shimprove/javascript/shimprove.1-0-1.js
function shimCloneNode( elem ) {
var div = document.createElement( "div" );
safeFragment.appendChild( div );
div.innerHTML = elem.outerHTML;
return div.firstChild;
}
jQuery.extend({
clone: function( elem, dataAndEvents, deepDataAndEvents ) {
var srcElements,
destElements,
i,
// IE<=8 does not properly clone detached, unknown element nodes
clone = jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ?
elem.cloneNode( true ) :
shimCloneNode( elem );
if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) &&
(elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) {
// IE copies events bound via attachEvent when using cloneNode.
// Calling detachEvent on the clone will also remove the events
// from the original. In order to get around this, we use some
// proprietary methods to clear the events. Thanks to MooTools
// guys for this hotness.
cloneFixAttributes( elem, clone );
// Using Sizzle here is crazy slow, so we use getElementsByTagName instead
srcElements = getAll( elem );
destElements = getAll( clone );
// Weird iteration because IE will replace the length property
// with an element if you are cloning the body and one of the
// elements on the page has a name or id of "length"
for ( i = 0; srcElements[i]; ++i ) {
// Ensure that the destination node is not null; Fixes #9587
if ( destElements[i] ) {
cloneFixAttributes( srcElements[i], destElements[i] );
}
}
}
// Copy the events from the original to the clone
if ( dataAndEvents ) {
cloneCopyEvent( elem, clone );
if ( deepDataAndEvents ) {
srcElements = getAll( elem );
destElements = getAll( clone );
for ( i = 0; srcElements[i]; ++i ) {
cloneCopyEvent( srcElements[i], destElements[i] );
}
}
}
srcElements = destElements = null;
// Return the cloned set
return clone;
},
clean: function( elems, context, fragment, scripts ) {
var checkScriptType, script, j,
ret = [];
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;
}
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
if ( typeof elem === "number" ) {
elem += "";
}
if ( !elem ) {
continue;
}
// Convert html string into DOM nodes
if ( typeof elem === "string" ) {
if ( !rhtml.test( elem ) ) {
elem = context.createTextNode( elem );
} else {
// Fix "XHTML"-style tags in all browsers
elem = elem.replace(rxhtmlTag, "<$1></$2>");
// Trim whitespace, otherwise indexOf won't work as expected
var tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(),
wrap = wrapMap[ tag ] || wrapMap._default,
depth = wrap[0],
div = context.createElement("div"),
safeChildNodes = safeFragment.childNodes,
remove;
// Append wrapper element to unknown element safe doc fragment
if ( context === document ) {
// Use the fragment we've already created for this document
safeFragment.appendChild( div );
} else {
// Use a fragment created with the owner document
createSafeFragment( context ).appendChild( div );
}
// Go to html and back, then peel off extra wrappers
div.innerHTML = wrap[1] + elem + wrap[2];
// Move to the right depth
while ( depth-- ) {
div = div.lastChild;
}
// Remove IE's autoinserted <tbody> from table fragments
if ( !jQuery.support.tbody ) {
// String was a <table>, *may* have spurious <tbody>
var hasBody = rtbody.test(elem),
tbody = tag === "table" && !hasBody ?
div.firstChild && div.firstChild.childNodes :
// String was a bare <thead> or <tfoot>
wrap[1] === "<table>" && !hasBody ?
div.childNodes :
[];
for ( j = tbody.length - 1; j >= 0 ; --j ) {
if ( jQuery.nodeName( tbody[ j ], "tbody" ) && !tbody[ j ].childNodes.length ) {
tbody[ j ].parentNode.removeChild( tbody[ j ] );
}
}
}
// IE completely kills leading whitespace when innerHTML is used
if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) {
div.insertBefore( context.createTextNode( rleadingWhitespace.exec(elem)[0] ), div.firstChild );
}
elem = div.childNodes;
// Clear elements from DocumentFragment (safeFragment or otherwise)
// to avoid hoarding elements. Fixes #11356
if ( div ) {
div.parentNode.removeChild( div );
// Guard against -1 index exceptions in FF3.6
if ( safeChildNodes.length > 0 ) {
remove = safeChildNodes[ safeChildNodes.length - 1 ];
if ( remove && remove.parentNode ) {
remove.parentNode.removeChild( remove );
}
}
}
}
}
// Resets defaultChecked for any radios and checkboxes
// about to be appended to the DOM in IE 6/7 (#8060)
var len;
if ( !jQuery.support.appendChecked ) {
if ( elem[0] && typeof (len = elem.length) === "number" ) {
for ( j = 0; j < len; j++ ) {
findInputs( elem[j] );
}
} else {
findInputs( elem );
}
}
if ( elem.nodeType ) {
ret.push( elem );
} else {
ret = jQuery.merge( ret, elem );
}
}
if ( fragment ) {
checkScriptType = function( elem ) {
return !elem.type || rscriptType.test( elem.type );
};
for ( i = 0; ret[i]; i++ ) {
script = ret[i];
if ( scripts && jQuery.nodeName( script, "script" ) && (!script.type || rscriptType.test( script.type )) ) {
scripts.push( script.parentNode ? script.parentNode.removeChild( script ) : script );
} else {
if ( script.nodeType === 1 ) {
var jsTags = jQuery.grep( script.getElementsByTagName( "script" ), checkScriptType );
ret.splice.apply( ret, [i + 1, 0].concat( jsTags ) );
}
fragment.appendChild( script );
}
}
}
return ret;
},
cleanData: function( elems ) {
var data, id,
cache = jQuery.cache,
special = jQuery.event.special,
deleteExpando = jQuery.support.deleteExpando;
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) {
continue;
}
id = elem[ jQuery.expando ];
if ( id ) {
data = cache[ id ];
if ( data && data.events ) {
for ( var type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
// This is a shortcut to avoid jQuery.event.remove's overhead
} else {
jQuery.removeEvent( elem, type, data.handle );
}
}
// Null the DOM reference to avoid IE6/7/8 leak (#7054)
if ( data.handle ) {
data.handle.elem = null;
}
}
if ( deleteExpando ) {
delete elem[ jQuery.expando ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( jQuery.expando );
}
delete cache[ id ];
}
}
}
});
var ralpha = /alpha\([^)]*\)/i,
ropacity = /opacity=([^)]*)/,
// fixed for IE9, see #8346
rupper = /([A-Z]|^ms)/g,
rnum = /^[\-+]?(?:\d*\.)?\d+$/i,
rnumnonpx = /^-?(?:\d*\.)?\d+(?!px)[^\d\s]+$/i,
rrelNum = /^([\-+])=([\-+.\de]+)/,
rmargin = /^margin/,
cssShow = { position: "absolute", visibility: "hidden", display: "block" },
// order is important!
cssExpand = [ "Top", "Right", "Bottom", "Left" ],
curCSS,
getComputedStyle,
currentStyle;
jQuery.fn.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 );
};
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;
} else {
return elem.style.opacity;
}
}
}
},
// Exclude the following css properties to add px
cssNumber: {
"fillOpacity": true,
"fontWeight": true,
"lineHeight": true,
"opacity": true,
"orphans": true,
"widows": true,
"zIndex": true,
"zoom": true
},
// Add in properties whose names you wish to fix before
// setting or getting the value
cssProps: {
// normalize float css property
"float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat"
},
// Get and set the style property on a DOM Node
style: function( elem, name, value, extra ) {
// Don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) {
return;
}
// Make sure that we're working with the right name
var ret, type, origName = jQuery.camelCase( name ),
style = elem.style, hooks = jQuery.cssHooks[ origName ];
name = jQuery.cssProps[ origName ] || origName;
// Check if we're setting a value
if ( value !== undefined ) {
type = typeof value;
// convert relative number strings (+= or -=) to relative numbers. #7345
if ( type === "string" && (ret = rrelNum.exec( value )) ) {
value = ( +( ret[1] + 1) * +ret[2] ) + parseFloat( jQuery.css( elem, name ) );
// Fixes bug #9237
type = "number";
}
// Make sure that NaN and null values aren't set. See: #7116
if ( value == null || type === "number" && isNaN( value ) ) {
return;
}
// If a number was passed in, add 'px' to the (except for certain CSS properties)
if ( type === "number" && !jQuery.cssNumber[ origName ] ) {
value += "px";
}
// If a hook was provided, use that value, otherwise just set the specified value
if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value )) !== undefined ) {
// Wrapped to prevent IE from throwing errors when 'invalid' values are provided
// Fixes bug #5509
try {
style[ name ] = value;
} catch(e) {}
}
} else {
// If a hook was provided get the non-computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) {
return ret;
}
// Otherwise just get the value from the style object
return style[ name ];
}
},
css: function( elem, name, extra ) {
var ret, hooks;
// Make sure that we're working with the right name
name = jQuery.camelCase( name );
hooks = jQuery.cssHooks[ name ];
name = jQuery.cssProps[ name ] || name;
// cssFloat needs a special treatment
if ( name === "cssFloat" ) {
name = "float";
}
// If a hook was provided get the computed value from there
if ( hooks && "get" in hooks && (ret = hooks.get( elem, true, extra )) !== undefined ) {
return ret;
// Otherwise, if a way to get the computed value exists, use that
} else if ( curCSS ) {
return curCSS( elem, name );
}
},
// A method for quickly swapping in/out CSS properties to get correct calculations
swap: function( elem, options, callback ) {
var old = {},
ret, name;
// 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;
}
});
// DEPRECATED in 1.3, Use jQuery.css() instead
jQuery.curCSS = jQuery.css;
if ( document.defaultView && document.defaultView.getComputedStyle ) {
getComputedStyle = function( elem, name ) {
var ret, defaultView, computedStyle, width,
style = elem.style;
name = name.replace( rupper, "-$1" ).toLowerCase();
if ( (defaultView = elem.ownerDocument.defaultView) &&
(computedStyle = defaultView.getComputedStyle( elem, null )) ) {
ret = computedStyle.getPropertyValue( name );
if ( ret === "" && !jQuery.contains( elem.ownerDocument.documentElement, elem ) ) {
ret = jQuery.style( elem, name );
}
}
// A tribute to the "awesome hack by Dean Edwards"
// WebKit uses "computed value (percentage if specified)" instead of "used value" for margins
// which is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values
if ( !jQuery.support.pixelMargin && computedStyle && rmargin.test( name ) && rnumnonpx.test( ret ) ) {
width = style.width;
style.width = ret;
ret = computedStyle.width;
style.width = width;
}
return ret;
};
}
if ( document.documentElement.currentStyle ) {
currentStyle = function( elem, name ) {
var left, rsLeft, uncomputed,
ret = elem.currentStyle && elem.currentStyle[ name ],
style = elem.style;
// Avoid setting ret to empty string here
// so we don't default to auto
if ( ret == null && style && (uncomputed = style[ name ]) ) {
ret = uncomputed;
}
// From the awesome hack by Dean Edwards
// http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291
// If we're not dealing with a regular pixel number
// but a number that has a weird ending, we need to convert it to pixels
if ( rnumnonpx.test( ret ) ) {
// Remember the original values
left = style.left;
rsLeft = elem.runtimeStyle && elem.runtimeStyle.left;
// Put in the new values to get a computed value out
if ( rsLeft ) {
elem.runtimeStyle.left = elem.currentStyle.left;
}
style.left = name === "fontSize" ? "1em" : ret;
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 getWidthOrHeight( elem, name, extra ) {
// Start with offset property
var val = name === "width" ? elem.offsetWidth : elem.offsetHeight,
i = name === "width" ? 1 : 0,
len = 4;
if ( val > 0 ) {
if ( extra !== "border" ) {
for ( ; i < len; i += 2 ) {
if ( !extra ) {
val -= parseFloat( jQuery.css( elem, "padding" + cssExpand[ i ] ) ) || 0;
}
if ( extra === "margin" ) {
val += parseFloat( jQuery.css( elem, extra + cssExpand[ i ] ) ) || 0;
} else {
val -= parseFloat( jQuery.css( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0;
}
}
}
return val + "px";
}
// 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;
}
// Normalize "", auto, and prepare for extra
val = parseFloat( val ) || 0;
// Add padding, border, margin
if ( extra ) {
for ( ; i < len; i += 2 ) {
val += parseFloat( jQuery.css( elem, "padding" + cssExpand[ i ] ) ) || 0;
if ( extra !== "padding" ) {
val += parseFloat( jQuery.css( elem, "border" + cssExpand[ i ] + "Width" ) ) || 0;
}
if ( extra === "margin" ) {
val += parseFloat( jQuery.css( elem, extra + cssExpand[ i ]) ) || 0;
}
}
}
return val + "px";
}
jQuery.each([ "height", "width" ], function( i, name ) {
jQuery.cssHooks[ name ] = {
get: function( elem, computed, extra ) {
if ( computed ) {
if ( elem.offsetWidth !== 0 ) {
return getWidthOrHeight( elem, name, extra );
} else {
return jQuery.swap( elem, cssShow, function() {
return getWidthOrHeight( elem, name, extra );
});
}
}
},
set: function( elem, value ) {
return rnum.test( value ) ?
value + "px" :
value;
}
};
});
if ( !jQuery.support.opacity ) {
jQuery.cssHooks.opacity = {
get: function( elem, computed ) {
// IE uses filters for opacity
return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ?
( parseFloat( RegExp.$1 ) / 100 ) + "" :
computed ? "1" : "";
},
set: function( elem, value ) {
var style = elem.style,
currentStyle = elem.currentStyle,
opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "",
filter = currentStyle && currentStyle.filter || style.filter || "";
// IE has trouble with opacity if it does not have layout
// Force it by setting the zoom level
style.zoom = 1;
// if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652
if ( value >= 1 && jQuery.trim( filter.replace( ralpha, "" ) ) === "" ) {
// Setting style.filter to null, "" & " " still leave "filter:" in the cssText
// if "filter:" is present at all, clearType is disabled, we want to avoid this
// style.removeAttribute is IE Only, but so apparently is this code path...
style.removeAttribute( "filter" );
// if there there is no filter style applied in a css rule, we are done
if ( currentStyle && !currentStyle.filter ) {
return;
}
}
// otherwise, set new filter values
style.filter = ralpha.test( filter ) ?
filter.replace( ralpha, opacity ) :
filter + " " + opacity;
}
};
}
jQuery(function() {
// This hook cannot be added until DOM ready because the support test
// for it is not run until after DOM ready
if ( !jQuery.support.reliableMarginRight ) {
jQuery.cssHooks.marginRight = {
get: function( elem, computed ) {
// WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right
// Work around by temporarily setting element display to inline-block
return jQuery.swap( elem, { "display": "inline-block" }, function() {
if ( computed ) {
return curCSS( elem, "margin-right" );
} else {
return elem.style.marginRight;
}
});
}
};
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.hidden = function( elem ) {
var width = elem.offsetWidth,
height = elem.offsetHeight;
return ( width === 0 && height === 0 ) || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none");
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
}
// 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;
}
};
});
var r20 = /%20/g,
rbracket = /\[\]$/,
rCRLF = /\r?\n/g,
rhash = /#.*$/,
rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL
rinput = /^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,
// #7653, #8125, #8152: local protocol detection
rlocalProtocol = /^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,
rnoContent = /^(?:GET|HEAD)$/,
rprotocol = /^\/\//,
rquery = /\?/,
rscript = /<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,
rselectTextarea = /^(?:select|textarea)/i,
rspacesAjax = /\s+/,
rts = /([?&])_=[^&]*/,
rurl = /^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,
// Keep a copy of the old load method
_load = jQuery.fn.load,
/* Prefilters
* 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example)
* 2) These are called:
* - BEFORE asking for a transport
* - AFTER param serialization (s.data is a string if s.processData is true)
* 3) key is the dataType
* 4) the catchall symbol "*" can be used
* 5) execution will start with transport dataType and THEN continue down to "*" if needed
*/
prefilters = {},
/* Transports bindings
* 1) key is the dataType
* 2) the catchall symbol "*" can be used
* 3) selection will start with transport dataType and THEN go to "*" if needed
*/
transports = {},
// Document location
ajaxLocation,
// Document location segments
ajaxLocParts,
// Avoid comment-prolog char sequence (#10098); must appease lint and evade compression
allTypes = ["*/"] + ["*"];
// #8138, IE may throw an exception when accessing
// a field from window.location if document.domain has been set
try {
ajaxLocation = location.href;
} catch( e ) {
// Use the href attribute of an A element
// since IE will modify it given document.location
ajaxLocation = document.createElement( "a" );
ajaxLocation.href = "";
ajaxLocation = ajaxLocation.href;
}
// Segment location into parts
ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || [];
// Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport
function addToPrefiltersOrTransports( structure ) {
// dataTypeExpression is optional and defaults to "*"
return function( dataTypeExpression, func ) {
if ( typeof dataTypeExpression !== "string" ) {
func = dataTypeExpression;
dataTypeExpression = "*";
}
if ( jQuery.isFunction( func ) ) {
var dataTypes = dataTypeExpression.toLowerCase().split( rspacesAjax ),
i = 0,
length = dataTypes.length,
dataType,
list,
placeBefore;
// For each dataType in the dataTypeExpression
for ( ; i < length; i++ ) {
dataType = dataTypes[ i ];
// We control if we're asked to add before
// any existing element
placeBefore = /^\+/.test( dataType );
if ( placeBefore ) {
dataType = dataType.substr( 1 ) || "*";
}
list = structure[ dataType ] = structure[ dataType ] || [];
// then we add to the structure accordingly
list[ placeBefore ? "unshift" : "push" ]( func );
}
}
};
}
// Base inspection function for prefilters and transports
function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR,
dataType /* internal */, inspected /* internal */ ) {
dataType = dataType || options.dataTypes[ 0 ];
inspected = inspected || {};
inspected[ dataType ] = true;
var list = structure[ dataType ],
i = 0,
length = list ? list.length : 0,
executeOnly = ( structure === prefilters ),
selection;
for ( ; i < length && ( executeOnly || !selection ); i++ ) {
selection = list[ i ]( options, originalOptions, jqXHR );
// If we got redirected to another dataType
// we try there if executing only and not done already
if ( typeof selection === "string" ) {
if ( !executeOnly || inspected[ selection ] ) {
selection = undefined;
} else {
options.dataTypes.unshift( selection );
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, selection, inspected );
}
}
}
// If we're only executing or nothing was selected
// we try the catchall dataType if not done already
if ( ( executeOnly || !selection ) && !inspected[ "*" ] ) {
selection = inspectPrefiltersOrTransports(
structure, options, originalOptions, jqXHR, "*", inspected );
}
// unnecessary when only executing (prefilters)
// but it'll be ignored by the caller in that case
return selection;
}
// A special extend for ajax options
// that takes "flat" options (not to be deep extended)
// Fixes #9887
function ajaxExtend( target, src ) {
var key, deep,
flatOptions = jQuery.ajaxSettings.flatOptions || {};
for ( key in src ) {
if ( src[ key ] !== undefined ) {
( flatOptions[ key ] ? target : ( deep || ( deep = {} ) ) )[ key ] = src[ key ];
}
}
if ( deep ) {
jQuery.extend( true, target, deep );
}
}
jQuery.fn.extend({
load: function( url, params, callback ) {
if ( typeof url !== "string" && _load ) {
return _load.apply( this, arguments );
// Don't do a request if no elements are being requested
} else if ( !this.length ) {
return this;
}
var off = url.indexOf( " " );
if ( off >= 0 ) {
var selector = url.slice( off, url.length );
url = url.slice( 0, off );
}
// Default to a GET request
var type = "GET";
// If the second parameter was provided
if ( params ) {
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = undefined;
// Otherwise, build a param string
} else if ( typeof params === "object" ) {
params = jQuery.param( params, jQuery.ajaxSettings.traditional );
type = "POST";
}
}
var self = this;
// Request the remote document
jQuery.ajax({
url: url,
type: type,
dataType: "html",
data: params,
// Complete callback (responseText is used internally)
complete: function( jqXHR, status, responseText ) {
// Store the response as specified by the jqXHR object
responseText = jqXHR.responseText;
// If successful, inject the HTML into all the matched elements
if ( jqXHR.isResolved() ) {
// #4825: Get the actual response in case
// a dataFilter is present in ajaxSettings
jqXHR.done(function( r ) {
responseText = r;
});
// See if a selector was specified
self.html( selector ?
// Create a dummy div to hold the results
jQuery("<div>")
// inject the contents of the document in, removing the scripts
// to avoid any 'Permission Denied' errors in IE
.append(responseText.replace(rscript, ""))
// Locate the specified elements
.find(selector) :
// If not, just inject the full result
responseText );
}
if ( callback ) {
self.each( callback, [ responseText, status, jqXHR ] );
}
}
});
return this;
},
serialize: function() {
return jQuery.param( this.serializeArray() );
},
serializeArray: function() {
return this.map(function(){
return this.elements ? jQuery.makeArray( this.elements ) : this;
})
.filter(function(){
return this.name && !this.disabled &&
( this.checked || rselectTextarea.test( this.nodeName ) ||
rinput.test( this.type ) );
})
.map(function( i, elem ){
var val = jQuery( this ).val();
return val == null ?
null :
jQuery.isArray( val ) ?
jQuery.map( val, function( val, i ){
return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}) :
{ name: elem.name, value: val.replace( rCRLF, "\r\n" ) };
}).get();
}
});
// Attach a bunch of functions for handling common AJAX events
jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split( " " ), function( i, o ){
jQuery.fn[ o ] = function( f ){
return this.on( o, f );
};
});
jQuery.each( [ "get", "post" ], function( i, method ) {
jQuery[ method ] = function( url, data, callback, type ) {
// shift arguments if data argument was omitted
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = undefined;
}
return jQuery.ajax({
type: method,
url: url,
data: data,
success: callback,
dataType: type
});
};
});
jQuery.extend({
getScript: function( url, callback ) {
return jQuery.get( url, undefined, callback, "script" );
},
getJSON: function( url, data, callback ) {
return jQuery.get( url, data, callback, "json" );
},
// Creates a full fledged settings object into target
// with both ajaxSettings and settings fields.
// If target is omitted, writes into ajaxSettings.
ajaxSetup: function( target, settings ) {
if ( settings ) {
// Building a settings object
ajaxExtend( target, jQuery.ajaxSettings );
} else {
// Extending ajaxSettings
settings = target;
target = jQuery.ajaxSettings;
}
ajaxExtend( target, settings );
return target;
},
ajaxSettings: {
url: ajaxLocation,
isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ),
global: true,
type: "GET",
contentType: "application/x-www-form-urlencoded; charset=UTF-8",
processData: true,
async: true,
/*
timeout: 0,
data: null,
dataType: null,
username: null,
password: null,
cache: null,
traditional: false,
headers: {},
*/
accepts: {
xml: "application/xml, text/xml",
html: "text/html",
text: "text/plain",
json: "application/json, text/javascript",
"*": allTypes
},
contents: {
xml: /xml/,
html: /html/,
json: /json/
},
responseFields: {
xml: "responseXML",
text: "responseText"
},
// List of data converters
// 1) key format is "source_type destination_type" (a single space in-between)
// 2) the catchall symbol "*" can be used for source_type
converters: {
// Convert anything to text
"* text": window.String,
// Text to html (true = no transformation)
"text html": true,
// Evaluate text as a json expression
"text json": jQuery.parseJSON,
// Parse text as xml
"text xml": jQuery.parseXML
},
// For options that shouldn't be deep extended:
// you can add your own custom options here if
// and when you create one that shouldn't be
// deep extended (see ajaxExtend)
flatOptions: {
context: true,
url: true
}
},
ajaxPrefilter: addToPrefiltersOrTransports( prefilters ),
ajaxTransport: addToPrefiltersOrTransports( transports ),
// Main method
ajax: function( url, options ) {
// If url is an object, simulate pre-1.5 signature
if ( typeof url === "object" ) {
options = url;
url = undefined;
}
// Force options to be an object
options = options || {};
var // Create the final options object
s = jQuery.ajaxSetup( {}, options ),
// Callbacks context
callbackContext = s.context || s,
// Context for global events
// It's the callbackContext if one was provided in the options
// and if it's a DOM node or a jQuery collection
globalEventContext = callbackContext !== s &&
( callbackContext.nodeType || callbackContext instanceof jQuery ) ?
jQuery( callbackContext ) : jQuery.event,
// Deferreds
deferred = jQuery.Deferred(),
completeDeferred = jQuery.Callbacks( "once memory" ),
// Status-dependent callbacks
statusCode = s.statusCode || {},
// ifModified key
ifModifiedKey,
// Headers (they are sent all at once)
requestHeaders = {},
requestHeadersNames = {},
// Response headers
responseHeadersString,
responseHeaders,
// transport
transport,
// timeout handle
timeoutTimer,
// Cross-domain detection vars
parts,
// The jqXHR state
state = 0,
// To know if global events are to be dispatched
fireGlobals,
// Loop variable
i,
// Fake xhr
jqXHR = {
readyState: 0,
// Caches the header
setRequestHeader: function( name, value ) {
if ( !state ) {
var lname = name.toLowerCase();
name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name;
requestHeaders[ name ] = value;
}
return this;
},
// Raw string
getAllResponseHeaders: function() {
return state === 2 ? responseHeadersString : null;
},
// Builds headers hashtable if needed
getResponseHeader: function( key ) {
var match;
if ( state === 2 ) {
if ( !responseHeaders ) {
responseHeaders = {};
while( ( match = rheaders.exec( responseHeadersString ) ) ) {
responseHeaders[ match[1].toLowerCase() ] = match[ 2 ];
}
}
match = responseHeaders[ key.toLowerCase() ];
}
return match === undefined ? null : match;
},
// Overrides response content-type header
overrideMimeType: function( type ) {
if ( !state ) {
s.mimeType = type;
}
return this;
},
// Cancel the request
abort: function( statusText ) {
statusText = statusText || "abort";
if ( transport ) {
transport.abort( statusText );
}
done( 0, statusText );
return this;
}
};
// Callback for when everything is done
// It is defined here because jslint complains if it is declared
// at the end of the function (which would be more logical and readable)
function done( status, nativeStatusText, responses, headers ) {
// Called once
if ( state === 2 ) {
return;
}
// State is "done" now
state = 2;
// Clear timeout if it exists
if ( timeoutTimer ) {
clearTimeout( timeoutTimer );
}
// Dereference transport for early garbage collection
// (no matter how long the jqXHR object will be used)
transport = undefined;
// Cache response headers
responseHeadersString = headers || "";
// Set readyState
jqXHR.readyState = status > 0 ? 4 : 0;
var isSuccess,
success,
error,
statusText = nativeStatusText,
response = responses ? ajaxHandleResponses( s, jqXHR, responses ) : undefined,
lastModified,
etag;
// If successful, handle type chaining
if ( status >= 200 && status < 300 || status === 304 ) {
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( ( lastModified = jqXHR.getResponseHeader( "Last-Modified" ) ) ) {
jQuery.lastModified[ ifModifiedKey ] = lastModified;
}
if ( ( etag = jqXHR.getResponseHeader( "Etag" ) ) ) {
jQuery.etag[ ifModifiedKey ] = etag;
}
}
// If not modified
if ( status === 304 ) {
statusText = "notmodified";
isSuccess = true;
// If we have data
} else {
try {
success = ajaxConvert( s, response );
statusText = "success";
isSuccess = true;
} catch(e) {
// We have a parsererror
statusText = "parsererror";
error = e;
}
}
} else {
// We extract error from statusText
// then normalize statusText and status for non-aborts
error = statusText;
if ( !statusText || status ) {
statusText = "error";
if ( status < 0 ) {
status = 0;
}
}
}
// Set data for the fake xhr object
jqXHR.status = status;
jqXHR.statusText = "" + ( nativeStatusText || statusText );
// Success/Error
if ( isSuccess ) {
deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] );
} else {
deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] );
}
// Status-dependent callbacks
jqXHR.statusCode( statusCode );
statusCode = undefined;
if ( fireGlobals ) {
globalEventContext.trigger( "ajax" + ( isSuccess ? "Success" : "Error" ),
[ jqXHR, s, isSuccess ? success : error ] );
}
// Complete
completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] );
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] );
// Handle the global AJAX counter
if ( !( --jQuery.active ) ) {
jQuery.event.trigger( "ajaxStop" );
}
}
}
// Attach deferreds
deferred.promise( jqXHR );
jqXHR.success = jqXHR.done;
jqXHR.error = jqXHR.fail;
jqXHR.complete = completeDeferred.add;
// Status-dependent callbacks
jqXHR.statusCode = function( map ) {
if ( map ) {
var tmp;
if ( state < 2 ) {
for ( tmp in map ) {
statusCode[ tmp ] = [ statusCode[tmp], map[tmp] ];
}
} else {
tmp = map[ jqXHR.status ];
jqXHR.then( tmp, tmp );
}
}
return this;
};
// Remove hash character (#7531: and string promotion)
// Add protocol if not provided (#5866: IE7 issue with protocol-less urls)
// We also use the url parameter if available
s.url = ( ( url || s.url ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" );
// Extract dataTypes list
s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().split( rspacesAjax );
// Determine if a cross-domain request is in order
if ( s.crossDomain == null ) {
parts = rurl.exec( s.url.toLowerCase() );
s.crossDomain = !!( parts &&
( parts[ 1 ] != ajaxLocParts[ 1 ] || parts[ 2 ] != ajaxLocParts[ 2 ] ||
( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) !=
( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) )
);
}
// Convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Apply prefilters
inspectPrefiltersOrTransports( prefilters, s, options, jqXHR );
// If request was aborted inside a prefilter, stop there
if ( state === 2 ) {
return false;
}
// We can fire global events as of now if asked to
fireGlobals = s.global;
// Uppercase the type
s.type = s.type.toUpperCase();
// Determine if request has content
s.hasContent = !rnoContent.test( s.type );
// Watch for a new set of requests
if ( fireGlobals && jQuery.active++ === 0 ) {
jQuery.event.trigger( "ajaxStart" );
}
// More options handling for requests with no content
if ( !s.hasContent ) {
// If data is available, append data to url
if ( s.data ) {
s.url += ( rquery.test( s.url ) ? "&" : "?" ) + s.data;
// #9682: remove data so that it's not used in an eventual retry
delete s.data;
}
// Get ifModifiedKey before adding the anti-cache parameter
ifModifiedKey = s.url;
// Add anti-cache in url if needed
if ( s.cache === false ) {
var ts = jQuery.now(),
// try replacing _= if it is there
ret = s.url.replace( rts, "$1_=" + ts );
// if nothing was replaced, add timestamp to the end
s.url = ret + ( ( ret === s.url ) ? ( rquery.test( s.url ) ? "&" : "?" ) + "_=" + ts : "" );
}
}
// Set the correct header, if data is being sent
if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) {
jqXHR.setRequestHeader( "Content-Type", s.contentType );
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
ifModifiedKey = ifModifiedKey || s.url;
if ( jQuery.lastModified[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ ifModifiedKey ] );
}
if ( jQuery.etag[ ifModifiedKey ] ) {
jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ ifModifiedKey ] );
}
}
// Set the Accepts header for the server, depending on the dataType
jqXHR.setRequestHeader(
"Accept",
s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ?
s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) :
s.accepts[ "*" ]
);
// Check for headers option
for ( i in s.headers ) {
jqXHR.setRequestHeader( i, s.headers[ i ] );
}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) {
// Abort if not done already
jqXHR.abort();
return false;
}
// Install callbacks on deferreds
for ( i in { success: 1, error: 1, complete: 1 } ) {
jqXHR[ i ]( s[ i ] );
}
// Get transport
transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR );
// If no transport, we auto-abort
if ( !transport ) {
done( -1, "No Transport" );
} else {
jqXHR.readyState = 1;
// Send global event
if ( fireGlobals ) {
globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] );
}
// Timeout
if ( s.async && s.timeout > 0 ) {
timeoutTimer = setTimeout( function(){
jqXHR.abort( "timeout" );
}, s.timeout );
}
try {
state = 1;
transport.send( requestHeaders, done );
} catch (e) {
// Propagate exception as error if not done
if ( state < 2 ) {
done( -1, e );
// Simply rethrow otherwise
} else {
throw e;
}
}
}
return jqXHR;
},
// Serialize an array of form elements or a set of
// key/values into a query string
param: function( a, traditional ) {
var s = [],
add = function( key, value ) {
// If value is a function, invoke it and return its value
value = jQuery.isFunction( value ) ? value() : value;
s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value );
};
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( var prefix in a ) {
buildParams( prefix, a[ prefix ], traditional, add );
}
}
// Return the resulting serialization
return s.join( "&" ).replace( r20, "+" );
}
});
function buildParams( prefix, obj, traditional, add ) {
if ( jQuery.isArray( obj ) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || rbracket.test( prefix ) ) {
// Treat each array item as a scalar.
add( prefix, v );
} else {
// If array item is non-scalar (array or object), encode its
// numeric index to resolve deserialization ambiguity issues.
// Note that rack (as of 1.0.0) can't currently deserialize
// nested arrays properly, and attempting to do so may cause
// a server error. Possible fixes are to modify rack's
// deserialization algorithm or to provide an option or flag
// to force array serialization to be shallow.
buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add );
}
});
} else if ( !traditional && jQuery.type( obj ) === "object" ) {
// Serialize object item.
for ( var name in obj ) {
buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add );
}
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
// This is still on the jQuery object... for now
// Want to move this to jQuery.ajax some day
jQuery.extend({
// Counter for holding the number of active queries
active: 0,
// Last-Modified header cache for next request
lastModified: {},
etag: {}
});
/* Handles responses to an ajax request:
* - sets all responseXXX fields accordingly
* - finds the right dataType (mediates between content-type and expected dataType)
* - returns the corresponding response
*/
function ajaxHandleResponses( s, jqXHR, responses ) {
var contents = s.contents,
dataTypes = s.dataTypes,
responseFields = s.responseFields,
ct,
type,
finalDataType,
firstDataType;
// Fill responseXXX fields
for ( type in responseFields ) {
if ( type in responses ) {
jqXHR[ responseFields[type] ] = responses[ type ];
}
}
// Remove auto dataType and get content-type in the process
while( dataTypes[ 0 ] === "*" ) {
dataTypes.shift();
if ( ct === undefined ) {
ct = s.mimeType || jqXHR.getResponseHeader( "content-type" );
}
}
// Check if we're dealing with a known content-type
if ( ct ) {
for ( type in contents ) {
if ( contents[ type ] && contents[ type ].test( ct ) ) {
dataTypes.unshift( type );
break;
}
}
}
// Check to see if we have a response for the expected dataType
if ( dataTypes[ 0 ] in responses ) {
finalDataType = dataTypes[ 0 ];
} else {
// Try convertible dataTypes
for ( type in responses ) {
if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) {
finalDataType = type;
break;
}
if ( !firstDataType ) {
firstDataType = type;
}
}
// Or just use first one
finalDataType = finalDataType || firstDataType;
}
// If we found a dataType
// We add the dataType to the list if needed
// and return the corresponding response
if ( finalDataType ) {
if ( finalDataType !== dataTypes[ 0 ] ) {
dataTypes.unshift( finalDataType );
}
return responses[ finalDataType ];
}
}
// Chain conversions given the request and the original response
function ajaxConvert( s, response ) {
// Apply the dataFilter if provided
if ( s.dataFilter ) {
response = s.dataFilter( response, s.dataType );
}
var dataTypes = s.dataTypes,
converters = {},
i,
key,
length = dataTypes.length,
tmp,
// Current and previous dataTypes
current = dataTypes[ 0 ],
prev,
// Conversion expression
conversion,
// Conversion function
conv,
// Conversion functions (transitive conversion)
conv1,
conv2;
// For each dataType in the chain
for ( i = 1; i < length; i++ ) {
// Create converters map
// with lowercased keys
if ( i === 1 ) {
for ( key in s.converters ) {
if ( typeof key === "string" ) {
converters[ key.toLowerCase() ] = s.converters[ key ];
}
}
}
// Get the dataTypes
prev = current;
current = dataTypes[ i ];
// If current is auto dataType, update it to prev
if ( current === "*" ) {
current = prev;
// If no auto and dataTypes are actually different
} else if ( prev !== "*" && prev !== current ) {
// Get the converter
conversion = prev + " " + current;
conv = converters[ conversion ] || converters[ "* " + current ];
// If there is no direct converter, search transitively
if ( !conv ) {
conv2 = undefined;
for ( conv1 in converters ) {
tmp = conv1.split( " " );
if ( tmp[ 0 ] === prev || tmp[ 0 ] === "*" ) {
conv2 = converters[ tmp[1] + " " + current ];
if ( conv2 ) {
conv1 = converters[ conv1 ];
if ( conv1 === true ) {
conv = conv2;
} else if ( conv2 === true ) {
conv = conv1;
}
break;
}
}
}
}
// If we found no converter, dispatch an error
if ( !( conv || conv2 ) ) {
jQuery.error( "No conversion from " + conversion.replace(" "," to ") );
}
// If found converter is not an equivalence
if ( conv !== true ) {
// Convert with 1 or 2 converters accordingly
response = conv ? conv( response ) : conv2( conv1(response) );
}
}
}
return response;
}
var jsc = jQuery.now(),
jsre = /(\=)\?(&|$)|\?\?/i;
// Default jsonp settings
jQuery.ajaxSetup({
jsonp: "callback",
jsonpCallback: function() {
return jQuery.expando + "_" + ( jsc++ );
}
});
// Detect, normalize options and install callbacks for jsonp requests
jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) {
var inspectData = ( typeof s.data === "string" ) && /^application\/x\-www\-form\-urlencoded/.test( s.contentType );
if ( s.dataTypes[ 0 ] === "jsonp" ||
s.jsonp !== false && ( jsre.test( s.url ) ||
inspectData && jsre.test( s.data ) ) ) {
var responseContainer,
jsonpCallback = s.jsonpCallback =
jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback,
previous = window[ jsonpCallback ],
url = s.url,
data = s.data,
replace = "$1" + jsonpCallback + "$2";
if ( s.jsonp !== false ) {
url = url.replace( jsre, replace );
if ( s.url === url ) {
if ( inspectData ) {
data = data.replace( jsre, replace );
}
if ( s.data === data ) {
// Add callback manually
url += (/\?/.test( url ) ? "&" : "?") + s.jsonp + "=" + jsonpCallback;
}
}
}
s.url = url;
s.data = data;
// Install callback
window[ jsonpCallback ] = function( response ) {
responseContainer = [ response ];
};
// Clean-up function
jqXHR.always(function() {
// Set callback back to previous value
window[ jsonpCallback ] = previous;
// Call if it was a function and we have a response
if ( responseContainer && jQuery.isFunction( previous ) ) {
window[ jsonpCallback ]( responseContainer[ 0 ] );
}
});
// Use data converter to retrieve json after script execution
s.converters["script json"] = function() {
if ( !responseContainer ) {
jQuery.error( jsonpCallback + " was not called" );
}
return responseContainer[ 0 ];
};
// force json dataType
s.dataTypes[ 0 ] = "json";
// Delegate to script
return "script";
}
});
// Install script dataType
jQuery.ajaxSetup({
accepts: {
script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"
},
contents: {
script: /javascript|ecmascript/
},
converters: {
"text script": function( text ) {
jQuery.globalEval( text );
return text;
}
}
});
// Handle cache's special case and global
jQuery.ajaxPrefilter( "script", function( s ) {
if ( s.cache === undefined ) {
s.cache = false;
}
if ( s.crossDomain ) {
s.type = "GET";
s.global = false;
}
});
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
var script,
head = document.head || document.getElementsByTagName( "head" )[0] || document.documentElement;
return {
send: function( _, callback ) {
script = document.createElement( "script" );
script.async = "async";
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
script.src = s.url;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function( _, isAbort ) {
if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) {
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
// Remove the script
if ( head && script.parentNode ) {
head.removeChild( script );
}
// Dereference the script
script = undefined;
// Callback if not abort
if ( !isAbort ) {
callback( 200, "success" );
}
}
};
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
// This arises when a base node is used (#2709 and #4378).
head.insertBefore( script, head.firstChild );
},
abort: function() {
if ( script ) {
script.onload( 0, 1 );
}
}
};
}
});
var // #5280: Internet Explorer will keep connections alive if we don't abort on unload
xhrOnUnloadAbort = window.ActiveXObject ? function() {
// Abort all pending requests
for ( var key in xhrCallbacks ) {
xhrCallbacks[ key ]( 0, 1 );
}
} : false,
xhrId = 0,
xhrCallbacks;
// Functions to create xhrs
function createStandardXHR() {
try {
return new window.XMLHttpRequest();
} catch( e ) {}
}
function createActiveXHR() {
try {
return new window.ActiveXObject( "Microsoft.XMLHTTP" );
} catch( e ) {}
}
// Create the request object
// (This is still attached to ajaxSettings for backward compatibility)
jQuery.ajaxSettings.xhr = window.ActiveXObject ?
/* Microsoft failed to properly
* implement the XMLHttpRequest in IE7 (can't request local files),
* so we use the ActiveXObject when it is available
* Additionally XMLHttpRequest can be disabled in IE7/IE8 so
* we need a fallback.
*/
function() {
return !this.isLocal && createStandardXHR() || createActiveXHR();
} :
// For all other browsers, use the standard XMLHttpRequest object
createStandardXHR;
// Determine support properties
(function( xhr ) {
jQuery.extend( jQuery.support, {
ajax: !!xhr,
cors: !!xhr && ( "withCredentials" in xhr )
});
})( jQuery.ajaxSettings.xhr() );
// Create transport if the browser can provide an xhr
if ( jQuery.support.ajax ) {
jQuery.ajaxTransport(function( s ) {
// Cross domain only allowed if supported through XMLHttpRequest
if ( !s.crossDomain || jQuery.support.cors ) {
var callback;
return {
send: function( headers, complete ) {
// Get a new xhr
var xhr = s.xhr(),
handle,
i;
// Open the socket
// Passing null username, generates a login popup on Opera (#2865)
if ( s.username ) {
xhr.open( s.type, s.url, s.async, s.username, s.password );
} else {
xhr.open( s.type, s.url, s.async );
}
// Apply custom fields if provided
if ( s.xhrFields ) {
for ( i in s.xhrFields ) {
xhr[ i ] = s.xhrFields[ i ];
}
}
// Override mime type if needed
if ( s.mimeType && xhr.overrideMimeType ) {
xhr.overrideMimeType( s.mimeType );
}
// X-Requested-With header
// For cross-domain requests, seeing as conditions for a preflight are
// akin to a jigsaw puzzle, we simply never set it to be sure.
// (it can always be set on a per-request basis or even using ajaxSetup)
// For same-domain requests, won't change header if already provided.
if ( !s.crossDomain && !headers["X-Requested-With"] ) {
headers[ "X-Requested-With" ] = "XMLHttpRequest";
}
// Need an extra try/catch for cross domain requests in Firefox 3
try {
for ( i in headers ) {
xhr.setRequestHeader( i, headers[ i ] );
}
} catch( _ ) {}
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( ( s.hasContent && s.data ) || null );
// Listener
callback = function( _, isAbort ) {
var status,
statusText,
responseHeaders,
responses,
xml;
// Firefox throws exceptions when accessing properties
// of an xhr when a network error occured
// http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE)
try {
// Was never called and is aborted or complete
if ( callback && ( isAbort || xhr.readyState === 4 ) ) {
// Only called once
callback = undefined;
// Do not keep as active anymore
if ( handle ) {
xhr.onreadystatechange = jQuery.noop;
if ( xhrOnUnloadAbort ) {
delete xhrCallbacks[ handle ];
}
}
// If it's an abort
if ( isAbort ) {
// Abort it manually if needed
if ( xhr.readyState !== 4 ) {
xhr.abort();
}
} else {
status = xhr.status;
responseHeaders = xhr.getAllResponseHeaders();
responses = {};
xml = xhr.responseXML;
// Construct response list
if ( xml && xml.documentElement /* #4958 */ ) {
responses.xml = xml;
}
// When requesting binary data, IE6-9 will throw an exception
// on any attempt to access responseText (#11426)
try {
responses.text = xhr.responseText;
} catch( _ ) {
}
// Firefox throws an exception when accessing
// statusText for faulty cross-domain requests
try {
statusText = xhr.statusText;
} catch( e ) {
// We normalize with Webkit giving an empty statusText
statusText = "";
}
// Filter status for non standard behaviors
// If the request is local and we have data: assume a success
// (success with no data won't get notified, that's the best we
// can do given current implementations)
if ( !status && s.isLocal && !s.crossDomain ) {
status = responses.text ? 200 : 404;
// IE - #1450: sometimes returns 1223 when it should be 204
} else if ( status === 1223 ) {
status = 204;
}
}
}
} catch( firefoxAccessException ) {
if ( !isAbort ) {
complete( -1, firefoxAccessException );
}
}
// Call complete if needed
if ( responses ) {
complete( status, statusText, responses, responseHeaders );
}
};
// if we're in sync mode or it's in cache
// and has been retrieved directly (IE6 & IE7)
// we need to manually fire the callback
if ( !s.async || xhr.readyState === 4 ) {
callback();
} else {
handle = ++xhrId;
if ( xhrOnUnloadAbort ) {
// Create the active xhrs callbacks list if needed
// and attach the unload handler
if ( !xhrCallbacks ) {
xhrCallbacks = {};
jQuery( window ).unload( xhrOnUnloadAbort );
}
// Add to list of active xhrs callbacks
xhrCallbacks[ handle ] = callback;
}
xhr.onreadystatechange = callback;
}
},
abort: function() {
if ( callback ) {
callback(0,1);
}
}
};
}
});
}
var elemdisplay = {},
iframe, iframeDoc,
rfxtypes = /^(?:toggle|show|hide)$/,
rfxnum = /^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,
timerId,
fxAttrs = [
// height animations
[ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ],
// width animations
[ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ],
// opacity animations
[ "opacity" ]
],
fxNow;
jQuery.fn.extend({
show: function( speed, easing, callback ) {
var elem, display;
if ( speed || speed === 0 ) {
return this.animate( genFx("show", 3), speed, easing, callback );
} else {
for ( var i = 0, j = this.length; i < j; i++ ) {
elem = this[ i ];
if ( elem.style ) {
display = elem.style.display;
// Reset the inline display of this element to learn if it is
// being hidden by cascaded rules or not
if ( !jQuery._data(elem, "olddisplay") && display === "none" ) {
display = elem.style.display = "";
}
// Set elements which have been overridden with display: none
// in a stylesheet to whatever the default browser style is
// for such an element
if ( (display === "" && jQuery.css(elem, "display") === "none") ||
!jQuery.contains( elem.ownerDocument.documentElement, elem ) ) {
jQuery._data( elem, "olddisplay", defaultDisplay(elem.nodeName) );
}
}
}
// Set the display of most of the elements in a second loop
// to avoid the constant reflow
for ( i = 0; i < j; i++ ) {
elem = this[ i ];
if ( elem.style ) {
display = elem.style.display;
if ( display === "" || display === "none" ) {
elem.style.display = jQuery._data( elem, "olddisplay" ) || "";
}
}
}
return this;
}
},
hide: function( speed, easing, callback ) {
if ( speed || speed === 0 ) {
return this.animate( genFx("hide", 3), speed, easing, callback);
} else {
var elem, display,
i = 0,
j = this.length;
for ( ; i < j; i++ ) {
elem = this[i];
if ( elem.style ) {
display = jQuery.css( elem, "display" );
if ( display !== "none" && !jQuery._data( elem, "olddisplay" ) ) {
jQuery._data( elem, "olddisplay", display );
}
}
}
// Set the display of the elements in a second loop
// to avoid the constant reflow
for ( i = 0; i < j; i++ ) {
if ( this[i].style ) {
this[i].style.display = "none";
}
}
return this;
}
},
// Save the old toggle function
_toggle: jQuery.fn.toggle,
toggle: function( fn, fn2, callback ) {
var bool = typeof fn === "boolean";
if ( jQuery.isFunction(fn) && jQuery.isFunction(fn2) ) {
this._toggle.apply( this, arguments );
} else if ( fn == null || bool ) {
this.each(function() {
var state = bool ? fn : jQuery(this).is(":hidden");
jQuery(this)[ state ? "show" : "hide" ]();
});
} else {
this.animate(genFx("toggle", 3), fn, fn2, callback);
}
return this;
},
fadeTo: function( speed, to, easing, callback ) {
return this.filter(":hidden").css("opacity", 0).show().end()
.animate({opacity: to}, speed, easing, callback);
},
animate: function( prop, speed, easing, callback ) {
var optall = jQuery.speed( speed, easing, callback );
if ( jQuery.isEmptyObject( prop ) ) {
return this.each( optall.complete, [ false ] );
}
// Do not change referenced properties as per-property easing will be lost
prop = jQuery.extend( {}, prop );
function doAnimation() {
// XXX 'this' does not always have a nodeName when running the
// test suite
if ( optall.queue === false ) {
jQuery._mark( this );
}
var opt = jQuery.extend( {}, optall ),
isElement = this.nodeType === 1,
hidden = isElement && jQuery(this).is(":hidden"),
name, val, p, e, hooks, replace,
parts, start, end, unit,
method;
// will store per property easing and be used to determine when an animation is complete
opt.animatedProperties = {};
// first pass over propertys to expand / normalize
for ( p in prop ) {
name = jQuery.camelCase( p );
if ( p !== name ) {
prop[ name ] = prop[ p ];
delete prop[ p ];
}
if ( ( hooks = jQuery.cssHooks[ name ] ) && "expand" in hooks ) {
replace = hooks.expand( prop[ name ] );
delete prop[ name ];
// not quite $.extend, this wont overwrite keys already present.
// also - reusing 'p' from above because we have the correct "name"
for ( p in replace ) {
if ( ! ( p in prop ) ) {
prop[ p ] = replace[ p ];
}
}
}
}
for ( name in prop ) {
val = prop[ name ];
// easing resolution: per property > opt.specialEasing > opt.easing > 'swing' (default)
if ( jQuery.isArray( val ) ) {
opt.animatedProperties[ name ] = val[ 1 ];
val = prop[ name ] = val[ 0 ];
} else {
opt.animatedProperties[ name ] = opt.specialEasing && opt.specialEasing[ name ] || opt.easing || 'swing';
}
if ( val === "hide" && hidden || val === "show" && !hidden ) {
return opt.complete.call( this );
}
if ( isElement && ( name === "height" || name === "width" ) ) {
// Make sure that nothing sneaks out
// Record all 3 overflow attributes because IE does not
// change the overflow attribute when overflowX and
// overflowY are set to the same value
opt.overflow = [ this.style.overflow, this.style.overflowX, this.style.overflowY ];
// Set display property to inline-block for height/width
// animations on inline elements that are having width/height animated
if ( jQuery.css( this, "display" ) === "inline" &&
jQuery.css( this, "float" ) === "none" ) {
// inline-level elements accept inline-block;
// block-level elements need to be inline with layout
if ( !jQuery.support.inlineBlockNeedsLayout || defaultDisplay( this.nodeName ) === "inline" ) {
this.style.display = "inline-block";
} else {
this.style.zoom = 1;
}
}
}
}
if ( opt.overflow != null ) {
this.style.overflow = "hidden";
}
for ( p in prop ) {
e = new jQuery.fx( this, opt, p );
val = prop[ p ];
if ( rfxtypes.test( val ) ) {
// Tracks whether to show or hide based on private
// data attached to the element
method = jQuery._data( this, "toggle" + p ) || ( val === "toggle" ? hidden ? "show" : "hide" : 0 );
if ( method ) {
jQuery._data( this, "toggle" + p, method === "show" ? "hide" : "show" );
e[ method ]();
} else {
e[ val ]();
}
} else {
parts = rfxnum.exec( val );
start = e.cur();
if ( parts ) {
end = parseFloat( parts[2] );
unit = parts[3] || ( jQuery.cssNumber[ p ] ? "" : "px" );
// We need to compute starting value
if ( unit !== "px" ) {
jQuery.style( this, p, (end || 1) + unit);
start = ( (end || 1) / e.cur() ) * start;
jQuery.style( this, p, start + unit);
}
// If a +=/-= token was provided, we're doing a relative animation
if ( parts[1] ) {
end = ( (parts[ 1 ] === "-=" ? -1 : 1) * end ) + start;
}
e.custom( start, end, unit );
} else {
e.custom( start, val, "" );
}
}
}
// For JS strict compliance
return true;
}
return optall.queue === false ?
this.each( doAnimation ) :
this.queue( optall.queue, doAnimation );
},
stop: function( type, clearQueue, gotoEnd ) {
if ( typeof type !== "string" ) {
gotoEnd = clearQueue;
clearQueue = type;
type = undefined;
}
if ( clearQueue && type !== false ) {
this.queue( type || "fx", [] );
}
return this.each(function() {
var index,
hadTimers = false,
timers = jQuery.timers,
data = jQuery._data( this );
// clear marker counters if we know they won't be
if ( !gotoEnd ) {
jQuery._unmark( true, this );
}
function stopQueue( elem, data, index ) {
var hooks = data[ index ];
jQuery.removeData( elem, index, true );
hooks.stop( gotoEnd );
}
if ( type == null ) {
for ( index in data ) {
if ( data[ index ] && data[ index ].stop && index.indexOf(".run") === index.length - 4 ) {
stopQueue( this, data, index );
}
}
} else if ( data[ index = type + ".run" ] && data[ index ].stop ){
stopQueue( this, data, index );
}
for ( index = timers.length; index--; ) {
if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) {
if ( gotoEnd ) {
// force the next step to be the last
timers[ index ]( true );
} else {
timers[ index ].saveState();
}
hadTimers = true;
timers.splice( index, 1 );
}
}
// start the next in the queue if the last step wasn't forced
// timers currently will call their complete callbacks, which will dequeue
// but only if they were gotoEnd
if ( !( gotoEnd && hadTimers ) ) {
jQuery.dequeue( this, type );
}
});
}
});
// Animations created synchronously will run synchronously
function createFxNow() {
setTimeout( clearFxNow, 0 );
return ( fxNow = jQuery.now() );
}
function clearFxNow() {
fxNow = undefined;
}
// Generate parameters to create a standard animation
function genFx( type, num ) {
var obj = {};
jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice( 0, num )), function() {
obj[ this ] = type;
});
return obj;
}
// Generate shortcuts for custom animations
jQuery.each({
slideDown: genFx( "show", 1 ),
slideUp: genFx( "hide", 1 ),
slideToggle: genFx( "toggle", 1 ),
fadeIn: { opacity: "show" },
fadeOut: { opacity: "hide" },
fadeToggle: { opacity: "toggle" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, easing, callback ) {
return this.animate( props, speed, easing, callback );
};
});
jQuery.extend({
speed: function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : {
complete: fn || !fn && easing ||
jQuery.isFunction( speed ) && speed,
duration: speed,
easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing
};
opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration :
opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default;
// normalize opt.queue - true/undefined/null -> "fx"
if ( opt.queue == null || opt.queue === true ) {
opt.queue = "fx";
}
// Queueing
opt.old = opt.complete;
opt.complete = function( noUnmark ) {
if ( jQuery.isFunction( opt.old ) ) {
opt.old.call( this );
}
if ( opt.queue ) {
jQuery.dequeue( this, opt.queue );
} else if ( noUnmark !== false ) {
jQuery._unmark( this );
}
};
return opt;
},
easing: {
linear: function( p ) {
return p;
},
swing: function( p ) {
return ( -Math.cos( p*Math.PI ) / 2 ) + 0.5;
}
},
timers: [],
fx: function( elem, options, prop ) {
this.options = options;
this.elem = elem;
this.prop = prop;
options.orig = options.orig || {};
}
});
jQuery.fx.prototype = {
// Simple function for setting a style value
update: function() {
if ( this.options.step ) {
this.options.step.call( this.elem, this.now, this );
}
( jQuery.fx.step[ this.prop ] || jQuery.fx.step._default )( this );
},
// Get the current size
cur: function() {
if ( this.elem[ this.prop ] != null && (!this.elem.style || this.elem.style[ this.prop ] == null) ) {
return this.elem[ this.prop ];
}
var parsed,
r = jQuery.css( this.elem, this.prop );
// Empty strings, null, undefined and "auto" are converted to 0,
// complex values such as "rotate(1rad)" are returned as is,
// simple values such as "10px" are parsed to Float.
return isNaN( parsed = parseFloat( r ) ) ? !r || r === "auto" ? 0 : r : parsed;
},
// Start an animation from one number to another
custom: function( from, to, unit ) {
var self = this,
fx = jQuery.fx;
this.startTime = fxNow || createFxNow();
this.end = to;
this.now = this.start = from;
this.pos = this.state = 0;
this.unit = unit || this.unit || ( jQuery.cssNumber[ this.prop ] ? "" : "px" );
function t( gotoEnd ) {
return self.step( gotoEnd );
}
t.queue = this.options.queue;
t.elem = this.elem;
t.saveState = function() {
if ( jQuery._data( self.elem, "fxshow" + self.prop ) === undefined ) {
if ( self.options.hide ) {
jQuery._data( self.elem, "fxshow" + self.prop, self.start );
} else if ( self.options.show ) {
jQuery._data( self.elem, "fxshow" + self.prop, self.end );
}
}
};
if ( t() && jQuery.timers.push(t) && !timerId ) {
timerId = setInterval( fx.tick, fx.interval );
}
},
// Simple 'show' function
show: function() {
var dataShow = jQuery._data( this.elem, "fxshow" + this.prop );
// Remember where we started, so that we can go back to it later
this.options.orig[ this.prop ] = dataShow || jQuery.style( this.elem, this.prop );
this.options.show = true;
// Begin the animation
// Make sure that we start at a small width/height to avoid any flash of content
if ( dataShow !== undefined ) {
// This show is picking up where a previous hide or show left off
this.custom( this.cur(), dataShow );
} else {
this.custom( this.prop === "width" || this.prop === "height" ? 1 : 0, this.cur() );
}
// Start by showing the element
jQuery( this.elem ).show();
},
// Simple 'hide' function
hide: function() {
// Remember where we started, so that we can go back to it later
this.options.orig[ this.prop ] = jQuery._data( this.elem, "fxshow" + this.prop ) || jQuery.style( this.elem, this.prop );
this.options.hide = true;
// Begin the animation
this.custom( this.cur(), 0 );
},
// Each step of an animation
step: function( gotoEnd ) {
var p, n, complete,
t = fxNow || createFxNow(),
done = true,
elem = this.elem,
options = this.options;
if ( gotoEnd || t >= options.duration + this.startTime ) {
this.now = this.end;
this.pos = this.state = 1;
this.update();
options.animatedProperties[ this.prop ] = true;
for ( p in options.animatedProperties ) {
if ( options.animatedProperties[ p ] !== true ) {
done = false;
}
}
if ( done ) {
// Reset the overflow
if ( options.overflow != null && !jQuery.support.shrinkWrapBlocks ) {
jQuery.each( [ "", "X", "Y" ], function( index, value ) {
elem.style[ "overflow" + value ] = options.overflow[ index ];
});
}
// Hide the element if the "hide" operation was done
if ( options.hide ) {
jQuery( elem ).hide();
}
// Reset the properties, if the item has been hidden or shown
if ( options.hide || options.show ) {
for ( p in options.animatedProperties ) {
jQuery.style( elem, p, options.orig[ p ] );
jQuery.removeData( elem, "fxshow" + p, true );
// Toggle data is no longer needed
jQuery.removeData( elem, "toggle" + p, true );
}
}
// Execute the complete function
// in the event that the complete function throws an exception
// we must ensure it won't be called twice. #5684
complete = options.complete;
if ( complete ) {
options.complete = false;
complete.call( elem );
}
}
return false;
} else {
// classical easing cannot be used with an Infinity duration
if ( options.duration == Infinity ) {
this.now = t;
} else {
n = t - this.startTime;
this.state = n / options.duration;
// Perform the easing function, defaults to swing
this.pos = jQuery.easing[ options.animatedProperties[this.prop] ]( this.state, n, 0, 1, options.duration );
this.now = this.start + ( (this.end - this.start) * this.pos );
}
// Perform the next step of the animation
this.update();
}
return true;
}
};
jQuery.extend( jQuery.fx, {
tick: function() {
var timer,
timers = jQuery.timers,
i = 0;
for ( ; i < timers.length; i++ ) {
timer = timers[ i ];
// Checks the timer has not already been removed
if ( !timer() && timers[ i ] === timer ) {
timers.splice( i--, 1 );
}
}
if ( !timers.length ) {
jQuery.fx.stop();
}
},
interval: 13,
stop: function() {
clearInterval( timerId );
timerId = null;
},
speeds: {
slow: 600,
fast: 200,
// Default speed
_default: 400
},
step: {
opacity: function( fx ) {
jQuery.style( fx.elem, "opacity", fx.now );
},
_default: function( fx ) {
if ( fx.elem.style && fx.elem.style[ fx.prop ] != null ) {
fx.elem.style[ fx.prop ] = fx.now + fx.unit;
} else {
fx.elem[ fx.prop ] = fx.now;
}
}
}
});
// Ensure props that can't be negative don't go there on undershoot easing
jQuery.each( fxAttrs.concat.apply( [], fxAttrs ), function( i, prop ) {
// exclude marginTop, marginLeft, marginBottom and marginRight from this list
if ( prop.indexOf( "margin" ) ) {
jQuery.fx.step[ prop ] = function( fx ) {
jQuery.style( fx.elem, prop, Math.max(0, fx.now) + fx.unit );
};
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.animated = function( elem ) {
return jQuery.grep(jQuery.timers, function( fn ) {
return elem === fn.elem;
}).length;
};
}
// Try to restore the default display value of an element
function defaultDisplay( nodeName ) {
if ( !elemdisplay[ nodeName ] ) {
var body = document.body,
elem = jQuery( "<" + nodeName + ">" ).appendTo( body ),
display = elem.css( "display" );
elem.remove();
// If the simple way fails,
// get element's real default display by attaching it to a temp iframe
if ( display === "none" || display === "" ) {
// No iframe to use yet, so create it
if ( !iframe ) {
iframe = document.createElement( "iframe" );
iframe.frameBorder = iframe.width = iframe.height = 0;
}
body.appendChild( iframe );
// Create a cacheable copy of the iframe document on first call.
// IE and Opera will allow us to reuse the iframeDoc without re-writing the fake HTML
// document to it; WebKit & Firefox won't allow reusing the iframe document.
if ( !iframeDoc || !iframe.createElement ) {
iframeDoc = ( iframe.contentWindow || iframe.contentDocument ).document;
iframeDoc.write( ( jQuery.support.boxModel ? "<!doctype html>" : "" ) + "<html><body>" );
iframeDoc.close();
}
elem = iframeDoc.createElement( nodeName );
iframeDoc.body.appendChild( elem );
display = jQuery.css( elem, "display" );
body.removeChild( iframe );
}
// Store the correct default display
elemdisplay[ nodeName ] = display;
}
return elemdisplay[ nodeName ];
}
var getOffset,
rtable = /^t(?:able|d|h)$/i,
rroot = /^(?:body|html)$/i;
if ( "getBoundingClientRect" in document.documentElement ) {
getOffset = function( elem, doc, docElem, box ) {
try {
box = elem.getBoundingClientRect();
} catch(e) {}
// 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 {
getOffset = function( elem, doc, docElem ) {
var computedStyle,
offsetParent = elem.offsetParent,
prevOffsetParent = elem,
body = doc.body,
defaultView = doc.defaultView,
prevComputedStyle = defaultView ? defaultView.getComputedStyle( elem, null ) : elem.currentStyle,
top = elem.offsetTop,
left = elem.offsetLeft;
while ( (elem = elem.parentNode) && elem !== body && elem !== docElem ) {
if ( jQuery.support.fixedPosition && prevComputedStyle.position === "fixed" ) {
break;
}
computedStyle = defaultView ? defaultView.getComputedStyle(elem, null) : elem.currentStyle;
top -= elem.scrollTop;
left -= elem.scrollLeft;
if ( elem === offsetParent ) {
top += elem.offsetTop;
left += elem.offsetLeft;
if ( jQuery.support.doesNotAddBorder && !(jQuery.support.doesAddBorderForTableAndCells && rtable.test(elem.nodeName)) ) {
top += parseFloat( computedStyle.borderTopWidth ) || 0;
left += parseFloat( computedStyle.borderLeftWidth ) || 0;
}
prevOffsetParent = offsetParent;
offsetParent = elem.offsetParent;
}
if ( jQuery.support.subtractsBorderForOverflowNotVisible && computedStyle.overflow !== "visible" ) {
top += parseFloat( computedStyle.borderTopWidth ) || 0;
left += parseFloat( computedStyle.borderLeftWidth ) || 0;
}
prevComputedStyle = computedStyle;
}
if ( prevComputedStyle.position === "relative" || prevComputedStyle.position === "static" ) {
top += body.offsetTop;
left += body.offsetLeft;
}
if ( jQuery.support.fixedPosition && prevComputedStyle.position === "fixed" ) {
top += Math.max( docElem.scrollTop, body.scrollTop );
left += Math.max( docElem.scrollLeft, body.scrollLeft );
}
return { top: top, left: left };
};
}
jQuery.fn.offset = function( options ) {
if ( arguments.length ) {
return options === undefined ?
this :
this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
var elem = this[0],
doc = elem && elem.ownerDocument;
if ( !doc ) {
return null;
}
if ( elem === doc.body ) {
return jQuery.offset.bodyOffset( elem );
}
return getOffset( elem, doc, doc.documentElement );
};
jQuery.offset = {
bodyOffset: function( body ) {
var top = body.offsetTop,
left = body.offsetLeft;
if ( jQuery.support.doesNotIncludeMarginInBodyOffset ) {
top += parseFloat( jQuery.css(body, "marginTop") ) || 0;
left += parseFloat( jQuery.css(body, "marginLeft") ) || 0;
}
return { top: top, left: left };
},
setOffset: function( elem, options, i ) {
var position = jQuery.css( elem, "position" );
// set position first, in-case top/left are set even on static elem
if ( position === "static" ) {
elem.style.position = "relative";
}
var curElem = jQuery( elem ),
curOffset = curElem.offset(),
curCSSTop = jQuery.css( elem, "top" ),
curCSSLeft = jQuery.css( elem, "left" ),
calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1,
props = {}, curPosition = {}, curTop, curLeft;
// need to be able to calculate position if either top or left is auto and position is either absolute or fixed
if ( calculatePosition ) {
curPosition = curElem.position();
curTop = curPosition.top;
curLeft = curPosition.left;
} else {
curTop = parseFloat( curCSSTop ) || 0;
curLeft = parseFloat( curCSSLeft ) || 0;
}
if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
}
if ( options.top != null ) {
props.top = ( options.top - curOffset.top ) + curTop;
}
if ( options.left != null ) {
props.left = ( options.left - curOffset.left ) + curLeft;
}
if ( "using" in options ) {
options.using.call( elem, props );
} else {
curElem.css( props );
}
}
};
jQuery.fn.extend({
position: function() {
if ( !this[0] ) {
return null;
}
var elem = this[0],
// Get *real* offsetParent
offsetParent = this.offsetParent(),
// Get correct offsets
offset = this.offset(),
parentOffset = rroot.test(offsetParent[0].nodeName) ? { top: 0, left: 0 } : offsetParent.offset();
// Subtract element margins
// note: when an element has margin: auto the offsetLeft and marginLeft
// are the same in Safari causing offset.left to incorrectly be 0
offset.top -= parseFloat( jQuery.css(elem, "marginTop") ) || 0;
offset.left -= parseFloat( jQuery.css(elem, "marginLeft") ) || 0;
// Add offsetParent borders
parentOffset.top += parseFloat( jQuery.css(offsetParent[0], "borderTopWidth") ) || 0;
parentOffset.left += parseFloat( jQuery.css(offsetParent[0], "borderLeftWidth") ) || 0;
// Subtract the two offsets
return {
top: offset.top - parentOffset.top,
left: offset.left - parentOffset.left
};
},
offsetParent: function() {
return this.map(function() {
var offsetParent = this.offsetParent || document.body;
while ( offsetParent && (!rroot.test(offsetParent.nodeName) && jQuery.css(offsetParent, "position") === "static") ) {
offsetParent = offsetParent.offsetParent;
}
return offsetParent;
});
}
});
// Create scrollLeft and scrollTop methods
jQuery.each( {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 ] :
jQuery.support.boxModel && win.document.documentElement[ method ] ||
win.document.body[ 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 width, height, innerHeight, innerWidth, outerHeight and outerWidth methods
jQuery.each( { Height: "height", Width: "width" }, function( name, type ) {
var clientProp = "client" + name,
scrollProp = "scroll" + name,
offsetProp = "offset" + name;
// innerHeight and innerWidth
jQuery.fn[ "inner" + name ] = function() {
var elem = this[0];
return elem ?
elem.style ?
parseFloat( jQuery.css( elem, type, "padding" ) ) :
this[ type ]() :
null;
};
// outerHeight and outerWidth
jQuery.fn[ "outer" + name ] = function( margin ) {
var elem = this[0];
return elem ?
elem.style ?
parseFloat( jQuery.css( elem, type, margin ? "margin" : "border" ) ) :
this[ type ]() :
null;
};
jQuery.fn[ type ] = function( value ) {
return jQuery.access( this, function( elem, type, value ) {
var doc, docElemProp, orig, ret;
if ( jQuery.isWindow( elem ) ) {
// 3rd condition allows Nokia support, as it supports the docElem prop but not CSS1Compat
doc = elem.document;
docElemProp = doc.documentElement[ clientProp ];
return jQuery.support.boxModel && docElemProp ||
doc.body && doc.body[ clientProp ] || docElemProp;
}
// Get document width or height
if ( elem.nodeType === 9 ) {
// Either scroll[Width/Height] or offset[Width/Height], whichever is greater
doc = elem.documentElement;
// when a window > document, IE6 reports a offset[Width/Height] > client[Width/Height]
// so we can't use max, as it'll choose the incorrect offset[Width/Height]
// instead we use the correct client[Width/Height]
// support:IE6
if ( doc[ clientProp ] >= doc[ scrollProp ] ) {
return doc[ clientProp ];
}
return Math.max(
elem.body[ scrollProp ], doc[ scrollProp ],
elem.body[ offsetProp ], doc[ offsetProp ]
);
}
// Get width or height on the element
if ( value === undefined ) {
orig = jQuery.css( elem, type );
ret = parseFloat( orig );
return jQuery.isNumeric( ret ) ? ret : orig;
}
// Set the width or height on the element
jQuery( elem ).css( type, value );
}, type, value, arguments.length, 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 );
|
web/public/js/jquery.min.js | sonots/haikanko | /*! jQuery v1.7.1 jquery.com | jquery.org/license */
(function(a,b){function cy(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cv(a){if(!ck[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){cl||(cl=c.createElement("iframe"),cl.frameBorder=cl.width=cl.height=0),b.appendChild(cl);if(!cm||!cl.createElement)cm=(cl.contentWindow||cl.contentDocument).document,cm.write((c.compatMode==="CSS1Compat"?"<!doctype html>":"")+"<html><body>"),cm.close();d=cm.createElement(a),cm.body.appendChild(d),e=f.css(d,"display"),b.removeChild(cl)}ck[a]=e}return ck[a]}function cu(a,b){var c={};f.each(cq.concat.apply([],cq.slice(0,b)),function(){c[this]=a});return c}function ct(){cr=b}function cs(){setTimeout(ct,0);return cr=f.now()}function cj(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ci(){try{return new a.XMLHttpRequest}catch(b){}}function cc(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var d=a.dataTypes,e={},g,h,i=d.length,j,k=d[0],l,m,n,o,p;for(g=1;g<i;g++){if(g===1)for(h in a.converters)typeof h=="string"&&(e[h.toLowerCase()]=a.converters[h]);l=k,k=d[g];if(k==="*")k=l;else if(l!=="*"&&l!==k){m=l+" "+k,n=e[m]||e["* "+k];if(!n){p=b;for(o in e){j=o.split(" ");if(j[0]===l||j[0]==="*"){p=e[j[1]+" "+k];if(p){o=e[o],o===!0?n=p:p===!0&&(n=o);break}}}}!n&&!p&&f.error("No conversion from "+m.replace(" "," to ")),n!==!0&&(c=n?n(c):p(o(c)))}}return c}function cb(a,c,d){var e=a.contents,f=a.dataTypes,g=a.responseFields,h,i,j,k;for(i in g)i in d&&(c[g[i]]=d[i]);while(f[0]==="*")f.shift(),h===b&&(h=a.mimeType||c.getResponseHeader("content-type"));if(h)for(i in e)if(e[i]&&e[i].test(h)){f.unshift(i);break}if(f[0]in d)j=f[0];else{for(i in d){if(!f[0]||a.converters[i+" "+f[0]]){j=i;break}k||(k=i)}j=j||k}if(j){j!==f[0]&&f.unshift(j);return d[j]}}function ca(a,b,c,d){if(f.isArray(b))f.each(b,function(b,e){c||bE.test(a)?d(a,e):ca(a+"["+(typeof e=="object"||f.isArray(e)?b:"")+"]",e,c,d)});else if(!c&&b!=null&&typeof b=="object")for(var e in b)ca(a+"["+e+"]",b[e],c,d);else d(a,b)}function b_(a,c){var d,e,g=f.ajaxSettings.flatOptions||{};for(d in c)c[d]!==b&&((g[d]?a:e||(e={}))[d]=c[d]);e&&f.extend(!0,a,e)}function b$(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h=a[f],i=0,j=h?h.length:0,k=a===bT,l;for(;i<j&&(k||!l);i++)l=h[i](c,d,e),typeof l=="string"&&(!k||g[l]?l=b:(c.dataTypes.unshift(l),l=b$(a,c,d,e,l,g)));(k||!l)&&!g["*"]&&(l=b$(a,c,d,e,"*",g));return l}function bZ(a){return function(b,c){typeof b!="string"&&(c=b,b="*");if(f.isFunction(c)){var d=b.toLowerCase().split(bP),e=0,g=d.length,h,i,j;for(;e<g;e++)h=d[e],j=/^\+/.test(h),j&&(h=h.substr(1)||"*"),i=a[h]=a[h]||[],i[j?"unshift":"push"](c)}}}function bC(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=b==="width"?bx:by,g=0,h=e.length;if(d>0){if(c!=="border")for(;g<h;g++)c||(d-=parseFloat(f.css(a,"padding"+e[g]))||0),c==="margin"?d+=parseFloat(f.css(a,c+e[g]))||0:d-=parseFloat(f.css(a,"border"+e[g]+"Width"))||0;return d+"px"}d=bz(a,b,b);if(d<0||d==null)d=a.style[b]||0;d=parseFloat(d)||0;if(c)for(;g<h;g++)d+=parseFloat(f.css(a,"padding"+e[g]))||0,c!=="padding"&&(d+=parseFloat(f.css(a,"border"+e[g]+"Width"))||0),c==="margin"&&(d+=parseFloat(f.css(a,c+e[g]))||0);return d+"px"}function bp(a,b){b.src?f.ajax({url:b.src,async:!1,dataType:"script"}):f.globalEval((b.text||b.textContent||b.innerHTML||"").replace(bf,"/*$0*/")),b.parentNode&&b.parentNode.removeChild(b)}function bo(a){var b=c.createElement("div");bh.appendChild(b),b.innerHTML=a.outerHTML;return b.firstChild}function bn(a){var b=(a.nodeName||"").toLowerCase();b==="input"?bm(a):b!=="script"&&typeof a.getElementsByTagName!="undefined"&&f.grep(a.getElementsByTagName("input"),bm)}function bm(a){if(a.type==="checkbox"||a.type==="radio")a.defaultChecked=a.checked}function bl(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bk(a,b){var c;if(b.nodeType===1){b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase();if(c==="object")b.outerHTML=a.outerHTML;else if(c!=="input"||a.type!=="checkbox"&&a.type!=="radio"){if(c==="option")b.selected=a.defaultSelected;else if(c==="input"||c==="textarea")b.defaultValue=a.defaultValue}else a.checked&&(b.defaultChecked=b.checked=a.checked),b.value!==a.value&&(b.value=a.value);b.removeAttribute(f.expando)}}function bj(a,b){if(b.nodeType===1&&!!f.hasData(a)){var c,d,e,g=f._data(a),h=f._data(b,g),i=g.events;if(i){delete h.handle,h.events={};for(c in i)for(d=0,e=i[c].length;d<e;d++)f.event.add(b,c+(i[c][d].namespace?".":"")+i[c][d].namespace,i[c][d],i[c][d].data)}h.data&&(h.data=f.extend({},h.data))}}function bi(a,b){return f.nodeName(a,"table")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function U(a){var b=V.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function T(a,b,c){b=b||0;if(f.isFunction(b))return f.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return f.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=f.grep(a,function(a){return a.nodeType===1});if(O.test(b))return f.filter(b,d,!c);b=f.filter(b,d)}return f.grep(a,function(a,d){return f.inArray(a,b)>=0===c})}function S(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function K(){return!0}function J(){return!1}function n(a,b,c){var d=b+"defer",e=b+"queue",g=b+"mark",h=f._data(a,d);h&&(c==="queue"||!f._data(a,e))&&(c==="mark"||!f._data(a,g))&&setTimeout(function(){!f._data(a,e)&&!f._data(a,g)&&(f.removeData(a,d,!0),h.fire())},0)}function m(a){for(var b in a){if(b==="data"&&f.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function l(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(k,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNumeric(d)?parseFloat(d):j.test(d)?f.parseJSON(d):d}catch(g){}f.data(a,c,d)}else d=b}return d}function h(a){var b=g[a]={},c,d;a=a.split(/\s+/);for(c=0,d=a.length;c<d;c++)b[a[c]]=!0;return b}var c=a.document,d=a.navigator,e=a.location,f=function(){function J(){if(!e.isReady){try{c.documentElement.doScroll("left")}catch(a){setTimeout(J,1);return}e.ready()}}var e=function(a,b){return new e.fn.init(a,b,h)},f=a.jQuery,g=a.$,h,i=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,n=/^[\],:{}\s]*$/,o=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,p=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,q=/(?:^|:|,)(?:\s*\[)+/g,r=/(webkit)[ \/]([\w.]+)/,s=/(opera)(?:.*version)?[ \/]([\w.]+)/,t=/(msie) ([\w.]+)/,u=/(mozilla)(?:.*? rv:([\w.]+))?/,v=/-([a-z]|[0-9])/ig,w=/^-ms-/,x=function(a,b){return(b+"").toUpperCase()},y=d.userAgent,z,A,B,C=Object.prototype.toString,D=Object.prototype.hasOwnProperty,E=Array.prototype.push,F=Array.prototype.slice,G=String.prototype.trim,H=Array.prototype.indexOf,I={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=m.exec(a),j?e.isPlainObject(d)?(a=[c.createElement(j[1])],e.fn.attr.call(a,d,!0)):a=[k.createElement(j[1])]:(j=e.buildFragment([g[1]],[k]),a=(j.cacheable?e.clone(j.fragment):j.fragment).childNodes);return e.merge(this,a)}h=c.getElementById(g[2]);if(h&&h.parentNode){if(h.id!==g[2])return f.find(a);this.length=1,this[0]=h}this.context=c,this.selector=a;return this}return!d||d.jquery?(d||f).find(a):this.constructor(d).find(a)}if(e.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return e.makeArray(a,this)},selector:"",jquery:"1.7.1",length:0,size:function(){return this.length},toArray:function(){return F.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=this.constructor();e.isArray(a)?E.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),A.add(a);return this},eq:function(a){a=+a;return 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(F.apply(this,arguments),"slice",F.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:E,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j<k;j++)if((a=arguments[j])!=null)for(c in a){d=i[c],f=a[c];if(i===f)continue;l&&f&&(e.isPlainObject(f)||(g=e.isArray(f)))?(g?(g=!1,h=d&&e.isArray(d)?d:[]):h=d&&e.isPlainObject(d)?d:{},i[c]=e.extend(l,h,f)):f!==b&&(i[c]=f)}return i},e.extend({noConflict:function(b){a.$===e&&(a.$=g),b&&a.jQuery===e&&(a.jQuery=f);return e},isReady:!1,readyWait:1,holdReady:function(a){a?e.readyWait++:e.ready(!0)},ready:function(a){if(a===!0&&!--e.readyWait||a!==!0&&!e.isReady){if(!c.body)return setTimeout(e.ready,1);e.isReady=!0;if(a!==!0&&--e.readyWait>0)return;A.fireWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").off("ready")}},bindReady:function(){if(!A){A=e.Callbacks("once memory");if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",B,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",B),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&J()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a&&typeof a=="object"&&"setInterval"in a},isNumeric:function(a){return!isNaN(parseFloat(a))&&isFinite(a)},type:function(a){return a==null?String(a):I[C.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;try{if(a.constructor&&!D.call(a,"constructor")&&!D.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||D.call(a,d)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw new Error(a)},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(n.test(b.replace(o,"@").replace(p,"]").replace(q,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(c){var d,f;try{a.DOMParser?(f=new DOMParser,d=f.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(g){d=b}(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&e.error("Invalid XML: "+c);return d},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(w,"ms-").replace(v,x)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g<h;)if(c.apply(a[g++],d)===!1)break}else if(i){for(f in a)if(c.call(a[f],f,a[f])===!1)break}else for(;g<h;)if(c.call(a[g],g,a[g++])===!1)break;return a},trim:G?function(a){return a==null?"":G.call(a)}:function(a){return a==null?"":(a+"").replace(k,"").replace(l,"")},makeArray:function(a,b){var c=b||[];if(a!=null){var d=e.type(a);a.length==null||d==="string"||d==="function"||d==="regexp"||e.isWindow(a)?E.call(c,a):e.merge(c,a)}return c},inArray:function(a,b,c){var d;if(b){if(H)return H.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=a.length,e=0;if(typeof c.length=="number")for(var f=c.length;e<f;e++)a[d++]=c[e];else while(c[e]!==b)a[d++]=c[e++];a.length=d;return a},grep:function(a,b,c){var d=[],e;c=!!c;for(var f=0,g=a.length;f<g;f++)e=!!b(a[f],f),c!==e&&d.push(a[f]);return d},map:function(a,c,d){var f,g,h=[],i=0,j=a.length,k=a instanceof e||j!==b&&typeof j=="number"&&(j>0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i<j;i++)f=c(a[i],i,d),f!=null&&(h[h.length]=f);else for(g in a)f=c(a[g],g,d),f!=null&&(h[h.length]=f);return h.concat.apply([],h)},guid:1,proxy:function(a,c){if(typeof c=="string"){var d=a[c];c=a,a=d}if(!e.isFunction(a))return b;var f=F.call(arguments,2),g=function(){return a.apply(c,f.concat(F.call(arguments)))};g.guid=a.guid=a.guid||g.guid||e.guid++;return g},access:function(a,c,d,f,g,h){var i=a.length;if(typeof c=="object"){for(var j in c)e.access(a,j,c[j],f,g,d);return a}if(d!==b){f=!h&&f&&e.isFunction(d);for(var k=0;k<i;k++)g(a[k],c,f?d.call(a[k],k,g(a[k],c)):d,h);return a}return i?g(a[0],c):b},now:function(){return(new Date).getTime()},uaMatch:function(a){a=a.toLowerCase();var b=r.exec(a)||s.exec(a)||t.exec(a)||a.indexOf("compatible")<0&&u.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},sub:function(){function a(b,c){return new a.fn.init(b,c)}e.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function(d,f){f&&f instanceof e&&!(f instanceof a)&&(f=a(f));return e.fn.init.call(this,d,f,b)},a.fn.init.prototype=a.fn;var b=a(c);return a},browser:{}}),e.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){I["[object "+b+"]"]=b.toLowerCase()}),z=e.uaMatch(y),z.browser&&(e.browser[z.browser]=!0,e.browser.version=z.version),e.browser.webkit&&(e.browser.safari=!0),j.test(" ")&&(k=/^[\s\xA0]+/,l=/[\s\xA0]+$/),h=e(c),c.addEventListener?B=function(){c.removeEventListener("DOMContentLoaded",B,!1),e.ready()}:c.attachEvent&&(B=function(){c.readyState==="complete"&&(c.detachEvent("onreadystatechange",B),e.ready())});return e}(),g={};f.Callbacks=function(a){a=a?g[a]||h(a):{};var c=[],d=[],e,i,j,k,l,m=function(b){var d,e,g,h,i;for(d=0,e=b.length;d<e;d++)g=b[d],h=f.type(g),h==="array"?m(g):h==="function"&&(!a.unique||!o.has(g))&&c.push(g)},n=function(b,f){f=f||[],e=!a.memory||[b,f],i=!0,l=j||0,j=0,k=c.length;for(;c&&l<k;l++)if(c[l].apply(b,f)===!1&&a.stopOnFalse){e=!0;break}i=!1,c&&(a.once?e===!0?o.disable():c=[]:d&&d.length&&(e=d.shift(),o.fireWith(e[0],e[1])))},o={add:function(){if(c){var a=c.length;m(arguments),i?k=c.length:e&&e!==!0&&(j=a,n(e[0],e[1]))}return this},remove:function(){if(c){var b=arguments,d=0,e=b.length;for(;d<e;d++)for(var f=0;f<c.length;f++)if(b[d]===c[f]){i&&f<=k&&(k--,f<=l&&l--),c.splice(f--,1);if(a.unique)break}}return this},has:function(a){if(c){var b=0,d=c.length;for(;b<d;b++)if(a===c[b])return!0}return!1},empty:function(){c=[];return this},disable:function(){c=d=e=b;return this},disabled:function(){return!c},lock:function(){d=b,(!e||e===!0)&&o.disable();return this},locked:function(){return!d},fireWith:function(b,c){d&&(i?a.once||d.push([b,c]):(!a.once||!e)&&n(b,c));return this},fire:function(){o.fireWith(this,arguments);return this},fired:function(){return!!e}};return o};var i=[].slice;f.extend({Deferred:function(a){var b=f.Callbacks("once memory"),c=f.Callbacks("once memory"),d=f.Callbacks("memory"),e="pending",g={resolve:b,reject:c,notify:d},h={done:b.add,fail:c.add,progress:d.add,state:function(){return e},isResolved:b.fired,isRejected:c.fired,then:function(a,b,c){i.done(a).fail(b).progress(c);return this},always:function(){i.done.apply(i,arguments).fail.apply(i,arguments);return this},pipe:function(a,b,c){return f.Deferred(function(d){f.each({done:[a,"resolve"],fail:[b,"reject"],progress:[c,"notify"]},function(a,b){var c=b[0],e=b[1],g;f.isFunction(c)?i[a](function(){g=c.apply(this,arguments),g&&f.isFunction(g.promise)?g.promise().then(d.resolve,d.reject,d.notify):d[e+"With"](this===i?d:this,[g])}):i[a](d[e])})}).promise()},promise:function(a){if(a==null)a=h;else for(var b in h)a[b]=h[b];return a}},i=h.promise({}),j;for(j in g)i[j]=g[j].fire,i[j+"With"]=g[j].fireWith;i.done(function(){e="resolved"},c.disable,d.lock).fail(function(){e="rejected"},b.disable,d.lock),a&&a.call(i,i);return i},when:function(a){function m(a){return function(b){e[a]=arguments.length>1?i.call(arguments,0):b,j.notifyWith(k,e)}}function l(a){return function(c){b[a]=arguments.length>1?i.call(arguments,0):c,--g||j.resolveWith(j,b)}}var b=i.call(arguments,0),c=0,d=b.length,e=Array(d),g=d,h=d,j=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred(),k=j.promise();if(d>1){for(;c<d;c++)b[c]&&b[c].promise&&f.isFunction(b[c].promise)?b[c].promise().then(l(c),j.reject,m(c)):--g;g||j.resolveWith(j,b)}else j!==a&&j.resolveWith(j,d?[a]:[]);return k}}),f.support=function(){var b,d,e,g,h,i,j,k,l,m,n,o,p,q=c.createElement("div"),r=c.documentElement;q.setAttribute("className","t"),q.innerHTML=" <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/>",d=q.getElementsByTagName("*"),e=q.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=q.getElementsByTagName("input")[0],b={leadingWhitespace:q.firstChild.nodeType===3,tbody:!q.getElementsByTagName("tbody").length,htmlSerialize:!!q.getElementsByTagName("link").length,style:/top/.test(e.getAttribute("style")),hrefNormalized:e.getAttribute("href")==="/a",opacity:/^0.55/.test(e.style.opacity),cssFloat:!!e.style.cssFloat,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:q.className!=="t",enctype:!!c.createElement("form").enctype,html5Clone:c.createElement("nav").cloneNode(!0).outerHTML!=="<:nav></:nav>",submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0},i.checked=!0,b.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,b.optDisabled=!h.disabled;try{delete q.test}catch(s){b.deleteExpando=!1}!q.addEventListener&&q.attachEvent&&q.fireEvent&&(q.attachEvent("onclick",function(){b.noCloneEvent=!1}),q.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),b.radioValue=i.value==="t",i.setAttribute("checked","checked"),q.appendChild(i),k=c.createDocumentFragment(),k.appendChild(q.lastChild),b.checkClone=k.cloneNode(!0).cloneNode(!0).lastChild.checked,b.appendChecked=i.checked,k.removeChild(i),k.appendChild(q),q.innerHTML="",a.getComputedStyle&&(j=c.createElement("div"),j.style.width="0",j.style.marginRight="0",q.style.width="2px",q.appendChild(j),b.reliableMarginRight=(parseInt((a.getComputedStyle(j,null)||{marginRight:0}).marginRight,10)||0)===0);if(q.attachEvent)for(o in{submit:1,change:1,focusin:1})n="on"+o,p=n in q,p||(q.setAttribute(n,"return;"),p=typeof q[n]=="function"),b[o+"Bubbles"]=p;k.removeChild(q),k=g=h=j=q=i=null,f(function(){var a,d,e,g,h,i,j,k,m,n,o,r=c.getElementsByTagName("body")[0];!r||(j=1,k="position:absolute;top:0;left:0;width:1px;height:1px;margin:0;",m="visibility:hidden;border:0;",n="style='"+k+"border:5px solid #000;padding:0;'",o="<div "+n+"><div></div></div>"+"<table "+n+" cellpadding='0' cellspacing='0'>"+"<tr><td></td></tr></table>",a=c.createElement("div"),a.style.cssText=m+"width:0;height:0;position:static;top:0;margin-top:"+j+"px",r.insertBefore(a,r.firstChild),q=c.createElement("div"),a.appendChild(q),q.innerHTML="<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>",l=q.getElementsByTagName("td"),p=l[0].offsetHeight===0,l[0].style.display="",l[1].style.display="none",b.reliableHiddenOffsets=p&&l[0].offsetHeight===0,q.innerHTML="",q.style.width=q.style.paddingLeft="1px",f.boxModel=b.boxModel=q.offsetWidth===2,typeof q.style.zoom!="undefined"&&(q.style.display="inline",q.style.zoom=1,b.inlineBlockNeedsLayout=q.offsetWidth===2,q.style.display="",q.innerHTML="<div style='width:4px;'></div>",b.shrinkWrapBlocks=q.offsetWidth!==2),q.style.cssText=k+m,q.innerHTML=o,d=q.firstChild,e=d.firstChild,h=d.nextSibling.firstChild.firstChild,i={doesNotAddBorder:e.offsetTop!==5,doesAddBorderForTableAndCells:h.offsetTop===5},e.style.position="fixed",e.style.top="20px",i.fixedPosition=e.offsetTop===20||e.offsetTop===15,e.style.position=e.style.top="",d.style.overflow="hidden",d.style.position="relative",i.subtractsBorderForOverflowNotVisible=e.offsetTop===-5,i.doesNotIncludeMarginInBodyOffset=r.offsetTop!==j,r.removeChild(a),q=a=null,f.extend(b,i))});return b}();var j=/^(?:\{.*\}|\[.*\])$/,k=/([A-Z])/g;f.extend({cache:{},uuid:0,expando:"jQuery"+(f.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?f.cache[a[f.expando]]:a[f.expando];return!!a&&!m(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g,h,i,j=f.expando,k=typeof c=="string",l=a.nodeType,m=l?f.cache:a,n=l?a[j]:a[j]&&j,o=c==="events";if((!n||!m[n]||!o&&!e&&!m[n].data)&&k&&d===b)return;n||(l?a[j]=n=++f.uuid:n=j),m[n]||(m[n]={},l||(m[n].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?m[n]=f.extend(m[n],c):m[n].data=f.extend(m[n].data,c);g=h=m[n],e||(h.data||(h.data={}),h=h.data),d!==b&&(h[f.camelCase(c)]=d);if(o&&!h[c])return g.events;k?(i=h[c],i==null&&(i=h[f.camelCase(c)])):i=h;return i}},removeData:function(a,b,c){if(!!f.acceptData(a)){var d,e,g,h=f.expando,i=a.nodeType,j=i?f.cache:a,k=i?a[h]:h;if(!j[k])return;if(b){d=c?j[k]:j[k].data;if(d){f.isArray(b)||(b in d?b=[b]:(b=f.camelCase(b),b in d?b=[b]:b=b.split(" ")));for(e=0,g=b.length;e<g;e++)delete d[b[e]];if(!(c?m:f.isEmptyObject)(d))return}}if(!c){delete j[k].data;if(!m(j[k]))return}f.support.deleteExpando||!j.setInterval?delete j[k]:j[k]=null,i&&(f.support.deleteExpando?delete a[h]:a.removeAttribute?a.removeAttribute(h):a[h]=null)}},_data:function(a,b,c){return f.data(a,b,c,!0)},acceptData:function(a){if(a.nodeName){var b=f.noData[a.nodeName.toLowerCase()];if(b)return b!==!0&&a.getAttribute("classid")===b}return!0}}),f.fn.extend({data:function(a,c){var d,e,g,h=null;if(typeof a=="undefined"){if(this.length){h=f.data(this[0]);if(this[0].nodeType===1&&!f._data(this[0],"parsedAttrs")){e=this[0].attributes;for(var i=0,j=e.length;i<j;i++)g=e[i].name,g.indexOf("data-")===0&&(g=f.camelCase(g.substring(5)),l(this[0],g,h[g]));f._data(this[0],"parsedAttrs",!0)}}return h}if(typeof a=="object")return this.each(function(){f.data(this,a)});d=a.split("."),d[1]=d[1]?"."+d[1]:"";if(c===b){h=this.triggerHandler("getData"+d[1]+"!",[d[0]]),h===b&&this.length&&(h=f.data(this[0],a),h=l(this[0],a,h));return h===b&&d[1]?this.data(d[0]):h}return this.each(function(){var b=f(this),e=[d[0],c];b.triggerHandler("setData"+d[1]+"!",e),f.data(this,a,c),b.triggerHandler("changeData"+d[1]+"!",e)})},removeData:function(a){return this.each(function(){f.removeData(this,a)})}}),f.extend({_mark:function(a,b){a&&(b=(b||"fx")+"mark",f._data(a,b,(f._data(a,b)||0)+1))},_unmark:function(a,b,c){a!==!0&&(c=b,b=a,a=!1);if(b){c=c||"fx";var d=c+"mark",e=a?0:(f._data(b,d)||1)-1;e?f._data(b,d,e):(f.removeData(b,d,!0),n(b,c,"mark"))}},queue:function(a,b,c){var d;if(a){b=(b||"fx")+"queue",d=f._data(a,b),c&&(!d||f.isArray(c)?d=f._data(a,b,f.makeArray(c)):d.push(c));return d||[]}},dequeue:function(a,b){b=b||"fx";var c=f.queue(a,b),d=c.shift(),e={};d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),f._data(a,b+".run",e),d.call(a,function(){f.dequeue(a,b)},e)),c.length||(f.removeData(a,b+"queue "+b+".run",!0),n(a,b,"queue"))}}),f.fn.extend({queue:function(a,c){typeof a!="string"&&(c=a,a="fx");if(c===b)return f.queue(this[0],a);return this.each(function(){var b=f.queue(this,a,c);a==="fx"&&b[0]!=="inprogress"&&f.dequeue(this,a)})},dequeue:function(a){return this.each(function(){f.dequeue(this,a)})},delay:function(a,b){a=f.fx?f.fx.speeds[a]||a:a,b=b||"fx";return 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){function m(){--h||d.resolveWith(e,[e])}typeof a!="string"&&(c=a,a=b),a=a||"fx";var d=f.Deferred(),e=this,g=e.length,h=1,i=a+"defer",j=a+"queue",k=a+"mark",l;while(g--)if(l=f.data(e[g],i,b,!0)||(f.data(e[g],j,b,!0)||f.data(e[g],k,b,!0))&&f.data(e[g],i,f.Callbacks("once memory"),!0))h++,l.add(m);m();return d.promise()}});var o=/[\n\t\r]/g,p=/\s+/,q=/\r/g,r=/^(?:button|input)$/i,s=/^(?:button|input|object|select|textarea)$/i,t=/^a(?:rea)?$/i,u=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,v=f.support.getSetAttribute,w,x,y;f.fn.extend({attr:function(a,b){return f.access(this,a,b,!0,f.attr)},removeAttr:function(a){return this.each(function(){f.removeAttr(this,a)})},prop:function(a,b){return f.access(this,a,b,!0,f.prop)},removeProp:function(a){a=f.propFix[a]||a;return this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,g,h,i;if(f.isFunction(a))return this.each(function(b){f(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(p);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{g=" "+e.className+" ";for(h=0,i=b.length;h<i;h++)~g.indexOf(" "+b[h]+" ")||(g+=b[h]+" ");e.className=f.trim(g)}}}return this},removeClass:function(a){var c,d,e,g,h,i,j;if(f.isFunction(a))return this.each(function(b){f(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(p);for(d=0,e=this.length;d<e;d++){g=this[d];if(g.nodeType===1&&g.className)if(a){h=(" "+g.className+" ").replace(o," ");for(i=0,j=c.length;i<j;i++)h=h.replace(" "+c[i]+" "," ");g.className=f.trim(h)}else g.className=""}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";if(f.isFunction(a))return this.each(function(c){f(this).toggleClass(a.call(this,c,this.className,b),b)});return this.each(function(){if(c==="string"){var e,g=0,h=f(this),i=b,j=a.split(p);while(e=j[g++])i=d?i:!h.hasClass(e),h[i?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&f._data(this,"__className__",this.className),this.className=this.className||a===!1?"":f._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,g=this[0];{if(!!arguments.length){e=f.isFunction(a);return this.each(function(d){var g=f(this),h;if(this.nodeType===1){e?h=a.call(this,d,g.val()):h=a,h==null?h="":typeof h=="number"?h+="":f.isArray(h)&&(h=f.map(h,function(a){return a==null?"":a+""})),c=f.valHooks[this.nodeName.toLowerCase()]||f.valHooks[this.type];if(!c||!("set"in c)||c.set(this,h,"value")===b)this.value=h}})}if(g){c=f.valHooks[g.nodeName.toLowerCase()]||f.valHooks[g.type];if(c&&"get"in c&&(d=c.get(g,"value"))!==b)return d;d=g.value;return typeof d=="string"?d.replace(q,""):d==null?"":d}}}}),f.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,g=a.selectedIndex,h=[],i=a.options,j=a.type==="select-one";if(g<0)return null;c=j?g:0,d=j?g+1:i.length;for(;c<d;c++){e=i[c];if(e.selected&&(f.support.optDisabled?!e.disabled:e.getAttribute("disabled")===null)&&(!e.parentNode.disabled||!f.nodeName(e.parentNode,"optgroup"))){b=f(e).val();if(j)return b;h.push(b)}}if(j&&!h.length&&i.length)return f(i[g]).val();return h},set:function(a,b){var c=f.makeArray(b);f(a).find("option").each(function(){this.selected=f.inArray(f(this).val(),c)>=0}),c.length||(a.selectedIndex=-1);return c}}},attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,d,e){var g,h,i,j=a.nodeType;if(!!a&&j!==3&&j!==8&&j!==2){if(e&&c in f.attrFn)return f(a)[c](d);if(typeof a.getAttribute=="undefined")return f.prop(a,c,d);i=j!==1||!f.isXMLDoc(a),i&&(c=c.toLowerCase(),h=f.attrHooks[c]||(u.test(c)?x:w));if(d!==b){if(d===null){f.removeAttr(a,c);return}if(h&&"set"in h&&i&&(g=h.set(a,d,c))!==b)return g;a.setAttribute(c,""+d);return d}if(h&&"get"in h&&i&&(g=h.get(a,c))!==null)return g;g=a.getAttribute(c);return g===null?b:g}},removeAttr:function(a,b){var c,d,e,g,h=0;if(b&&a.nodeType===1){d=b.toLowerCase().split(p),g=d.length;for(;h<g;h++)e=d[h],e&&(c=f.propFix[e]||e,f.attr(a,e,""),a.removeAttribute(v?e:c),u.test(e)&&c in a&&(a[c]=!1))}},attrHooks:{type:{set:function(a,b){if(r.test(a.nodeName)&&a.parentNode)f.error("type property can't be changed");else if(!f.support.radioValue&&b==="radio"&&f.nodeName(a,"input")){var c=a.value;a.setAttribute("type",b),c&&(a.value=c);return b}}},value:{get:function(a,b){if(w&&f.nodeName(a,"button"))return w.get(a,b);return b in a?a.value:null},set:function(a,b,c){if(w&&f.nodeName(a,"button"))return w.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,g,h,i=a.nodeType;if(!!a&&i!==3&&i!==8&&i!==2){h=i!==1||!f.isXMLDoc(a),h&&(c=f.propFix[c]||c,g=f.propHooks[c]);return d!==b?g&&"set"in g&&(e=g.set(a,d,c))!==b?e:a[c]=d:g&&"get"in g&&(e=g.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):s.test(a.nodeName)||t.test(a.nodeName)&&a.href?0:b}}}}),f.attrHooks.tabindex=f.propHooks.tabIndex,x={get:function(a,c){var d,e=f.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;b===!1?f.removeAttr(a,c):(d=f.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase()));return c}},v||(y={name:!0,id:!0},w=f.valHooks.button={get:function(a,c){var d;d=a.getAttributeNode(c);return d&&(y[c]?d.nodeValue!=="":d.specified)?d.nodeValue:b},set:function(a,b,d){var e=a.getAttributeNode(d);e||(e=c.createAttribute(d),a.setAttributeNode(e));return e.nodeValue=b+""}},f.attrHooks.tabindex.set=w.set,f.each(["width","height"],function(a,b){f.attrHooks[b]=f.extend(f.attrHooks[b],{set:function(a,c){if(c===""){a.setAttribute(b,"auto");return c}}})}),f.attrHooks.contenteditable={get:w.get,set:function(a,b,c){b===""&&(b="false"),w.set(a,b,c)}}),f.support.hrefNormalized||f.each(["href","src","width","height"],function(a,c){f.attrHooks[c]=f.extend(f.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),f.support.style||(f.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=""+b}}),f.support.optSelected||(f.propHooks.selected=f.extend(f.propHooks.selected,{get:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex);return null}})),f.support.enctype||(f.propFix.enctype="encoding"),f.support.checkOn||f.each(["radio","checkbox"],function(){f.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),f.each(["radio","checkbox"],function(){f.valHooks[this]=f.extend(f.valHooks[this],{set:function(a,b){if(f.isArray(b))return a.checked=f.inArray(f(a).val(),b)>=0}})});var z=/^(?:textarea|input|select)$/i,A=/^([^\.]*)?(?:\.(.+))?$/,B=/\bhover(\.\S+)?\b/,C=/^key/,D=/^(?:mouse|contextmenu)|click/,E=/^(?:focusinfocus|focusoutblur)$/,F=/^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,G=function(a){var b=F.exec(a);b&&(b[1]=(b[1]||"").toLowerCase(),b[3]=b[3]&&new RegExp("(?:^|\\s)"+b[3]+"(?:\\s|$)"));return b},H=function(a,b){var c=a.attributes||{};return(!b[1]||a.nodeName.toLowerCase()===b[1])&&(!b[2]||(c.id||{}).value===b[2])&&(!b[3]||b[3].test((c["class"]||{}).value))},I=function(a){return f.event.special.hover?a:a.replace(B,"mouseenter$1 mouseleave$1")};
f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3||a.nodeType===8||!c||!d||!(h=f._data(a)))){d.handler&&(p=d,d=p.handler),d.guid||(d.guid=f.guid++),j=h.events,j||(h.events=j={}),i=h.handle,i||(h.handle=i=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.dispatch.apply(i.elem,arguments):b},i.elem=a),c=f.trim(I(c)).split(" ");for(k=0;k<c.length;k++){l=A.exec(c[k])||[],m=l[1],n=(l[2]||"").split(".").sort(),s=f.event.special[m]||{},m=(g?s.delegateType:s.bindType)||m,s=f.event.special[m]||{},o=f.extend({type:m,origType:l[1],data:e,handler:d,guid:d.guid,selector:g,quick:G(g),namespace:n.join(".")},p),r=j[m];if(!r){r=j[m]=[],r.delegateCount=0;if(!s.setup||s.setup.call(a,e,n,i)===!1)a.addEventListener?a.addEventListener(m,i,!1):a.attachEvent&&a.attachEvent("on"+m,i)}s.add&&(s.add.call(a,o),o.handler.guid||(o.handler.guid=d.guid)),g?r.splice(r.delegateCount++,0,o):r.push(o),f.event.global[m]=!0}a=null}},global:{},remove:function(a,b,c,d,e){var g=f.hasData(a)&&f._data(a),h,i,j,k,l,m,n,o,p,q,r,s;if(!!g&&!!(o=g.events)){b=f.trim(I(b||"")).split(" ");for(h=0;h<b.length;h++){i=A.exec(b[h])||[],j=k=i[1],l=i[2];if(!j){for(j in o)f.event.remove(a,j+b[h],c,d,!0);continue}p=f.event.special[j]||{},j=(d?p.delegateType:p.bindType)||j,r=o[j]||[],m=r.length,l=l?new RegExp("(^|\\.)"+l.split(".").sort().join("\\.(?:.*\\.)?")+"(\\.|$)"):null;for(n=0;n<r.length;n++)s=r[n],(e||k===s.origType)&&(!c||c.guid===s.guid)&&(!l||l.test(s.namespace))&&(!d||d===s.selector||d==="**"&&s.selector)&&(r.splice(n--,1),s.selector&&r.delegateCount--,p.remove&&p.remove.call(a,s));r.length===0&&m!==r.length&&((!p.teardown||p.teardown.call(a,l)===!1)&&f.removeEvent(a,j,g.handle),delete o[j])}f.isEmptyObject(o)&&(q=g.handle,q&&(q.elem=null),f.removeData(a,["events","handle"],!0))}},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,e,g){if(!e||e.nodeType!==3&&e.nodeType!==8){var h=c.type||c,i=[],j,k,l,m,n,o,p,q,r,s;if(E.test(h+f.event.triggered))return;h.indexOf("!")>=0&&(h=h.slice(0,-1),k=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i.shift(),i.sort());if((!e||f.event.customEvent[h])&&!f.event.global[h])return;c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.isTrigger=!0,c.exclusive=k,c.namespace=i.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)"):null,o=h.indexOf(":")<0?"on"+h:"";if(!e){j=f.cache;for(l in j)j[l].events&&j[l].events[h]&&f.event.trigger(c,d,j[l].handle.elem,!0);return}c.result=b,c.target||(c.target=e),d=d!=null?f.makeArray(d):[],d.unshift(c),p=f.event.special[h]||{};if(p.trigger&&p.trigger.apply(e,d)===!1)return;r=[[e,p.bindType||h]];if(!g&&!p.noBubble&&!f.isWindow(e)){s=p.delegateType||h,m=E.test(s+h)?e:e.parentNode,n=null;for(;m;m=m.parentNode)r.push([m,s]),n=m;n&&n===e.ownerDocument&&r.push([n.defaultView||n.parentWindow||a,s])}for(l=0;l<r.length&&!c.isPropagationStopped();l++)m=r[l][0],c.type=r[l][1],q=(f._data(m,"events")||{})[c.type]&&f._data(m,"handle"),q&&q.apply(m,d),q=o&&m[o],q&&f.acceptData(m)&&q.apply(m,d)===!1&&c.preventDefault();c.type=h,!g&&!c.isDefaultPrevented()&&(!p._default||p._default.apply(e.ownerDocument,d)===!1)&&(h!=="click"||!f.nodeName(e,"a"))&&f.acceptData(e)&&o&&e[h]&&(h!=="focus"&&h!=="blur"||c.target.offsetWidth!==0)&&!f.isWindow(e)&&(n=e[o],n&&(e[o]=null),f.event.triggered=h,e[h](),f.event.triggered=b,n&&(e[o]=n));return c.result}},dispatch:function(c){c=f.event.fix(c||a.event);var d=(f._data(this,"events")||{})[c.type]||[],e=d.delegateCount,g=[].slice.call(arguments,0),h=!c.exclusive&&!c.namespace,i=[],j,k,l,m,n,o,p,q,r,s,t;g[0]=c,c.delegateTarget=this;if(e&&!c.target.disabled&&(!c.button||c.type!=="click")){m=f(this),m.context=this.ownerDocument||this;for(l=c.target;l!=this;l=l.parentNode||this){o={},q=[],m[0]=l;for(j=0;j<e;j++)r=d[j],s=r.selector,o[s]===b&&(o[s]=r.quick?H(l,r.quick):m.is(s)),o[s]&&q.push(r);q.length&&i.push({elem:l,matches:q})}}d.length>e&&i.push({elem:this,matches:d.slice(e)});for(j=0;j<i.length&&!c.isPropagationStopped();j++){p=i[j],c.currentTarget=p.elem;for(k=0;k<p.matches.length&&!c.isImmediatePropagationStopped();k++){r=p.matches[k];if(h||!c.namespace&&!r.namespace||c.namespace_re&&c.namespace_re.test(r.namespace))c.data=r.data,c.handleObj=r,n=((f.event.special[r.origType]||{}).handle||r.handler).apply(p.elem,g),n!==b&&(c.result=n,n===!1&&(c.preventDefault(),c.stopPropagation()))}}return 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){a.which==null&&(a.which=b.charCode!=null?b.charCode:b.keyCode);return a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,d){var e,f,g,h=d.button,i=d.fromElement;a.pageX==null&&d.clientX!=null&&(e=a.target.ownerDocument||c,f=e.documentElement,g=e.body,a.pageX=d.clientX+(f&&f.scrollLeft||g&&g.scrollLeft||0)-(f&&f.clientLeft||g&&g.clientLeft||0),a.pageY=d.clientY+(f&&f.scrollTop||g&&g.scrollTop||0)-(f&&f.clientTop||g&&g.clientTop||0)),!a.relatedTarget&&i&&(a.relatedTarget=i===a.target?d.toElement:i),!a.which&&h!==b&&(a.which=h&1?1:h&2?3:h&4?2:0);return a}},fix:function(a){if(a[f.expando])return a;var d,e,g=a,h=f.event.fixHooks[a.type]||{},i=h.props?this.props.concat(h.props):this.props;a=f.Event(g);for(d=i.length;d;)e=i[--d],a[e]=g[e];a.target||(a.target=g.srcElement||c),a.target.nodeType===3&&(a.target=a.target.parentNode),a.metaKey===b&&(a.metaKey=a.ctrlKey);return h.filter?h.filter(a,g):a},special:{ready:{setup:f.bindReady},load:{noBubble:!0},focus:{delegateType:"focusin"},blur:{delegateType:"focusout"},beforeunload:{setup:function(a,b,c){f.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}},simulate:function(a,b,c,d){var e=f.extend(new f.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?f.event.trigger(e,null,b):f.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},f.event.handle=f.event.dispatch,f.removeEvent=c.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){a.detachEvent&&a.detachEvent("on"+b,c)},f.Event=function(a,b){if(!(this instanceof f.Event))return new f.Event(a,b);a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?K:J):this.type=a,b&&f.extend(this,b),this.timeStamp=a&&a.timeStamp||f.now(),this[f.expando]=!0},f.Event.prototype={preventDefault:function(){this.isDefaultPrevented=K;var a=this.originalEvent;!a||(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=K;var a=this.originalEvent;!a||(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=K,this.stopPropagation()},isDefaultPrevented:J,isPropagationStopped:J,isImmediatePropagationStopped:J},f.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){f.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c=this,d=a.relatedTarget,e=a.handleObj,g=e.selector,h;if(!d||d!==c&&!f.contains(c,d))a.type=e.origType,h=e.handler.apply(this,arguments),a.type=b;return h}}}),f.support.submitBubbles||(f.event.special.submit={setup:function(){if(f.nodeName(this,"form"))return!1;f.event.add(this,"click._submit keypress._submit",function(a){var c=a.target,d=f.nodeName(c,"input")||f.nodeName(c,"button")?c.form:b;d&&!d._submit_attached&&(f.event.add(d,"submit._submit",function(a){this.parentNode&&!a.isTrigger&&f.event.simulate("submit",this.parentNode,a,!0)}),d._submit_attached=!0)})},teardown:function(){if(f.nodeName(this,"form"))return!1;f.event.remove(this,"._submit")}}),f.support.changeBubbles||(f.event.special.change={setup:function(){if(z.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")f.event.add(this,"propertychange._change",function(a){a.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),f.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1,f.event.simulate("change",this,a,!0))});return!1}f.event.add(this,"beforeactivate._change",function(a){var b=a.target;z.test(b.nodeName)&&!b._change_attached&&(f.event.add(b,"change._change",function(a){this.parentNode&&!a.isSimulated&&!a.isTrigger&&f.event.simulate("change",this.parentNode,a,!0)}),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(){f.event.remove(this,"._change");return z.test(this.nodeName)}}),f.support.focusinBubbles||f.each({focus:"focusin",blur:"focusout"},function(a,b){var d=0,e=function(a){f.event.simulate(b,a.target,f.event.fix(a),!0)};f.event.special[b]={setup:function(){d++===0&&c.addEventListener(a,e,!0)},teardown:function(){--d===0&&c.removeEventListener(a,e,!0)}}}),f.fn.extend({on:function(a,c,d,e,g){var h,i;if(typeof a=="object"){typeof c!="string"&&(d=c,c=b);for(i in a)this.on(i,c,d,a[i],g);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=J;else if(!e)return this;g===1&&(h=e,e=function(a){f().off(a);return h.apply(this,arguments)},e.guid=h.guid||(h.guid=f.guid++));return this.each(function(){f.event.add(this,a,e,d,c)})},one:function(a,b,c,d){return this.on.call(this,a,b,c,d,1)},off:function(a,c,d){if(a&&a.preventDefault&&a.handleObj){var e=a.handleObj;f(a.delegateTarget).off(e.namespace?e.type+"."+e.namespace:e.type,e.selector,e.handler);return this}if(typeof a=="object"){for(var g in a)this.off(g,c,a[g]);return this}if(c===!1||typeof c=="function")d=c,c=b;d===!1&&(d=J);return this.each(function(){f.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){f(this.context).on(a,this.selector,b,c);return this},die:function(a,b){f(this.context).off(a,this.selector||"**",b);return 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(){f.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return f.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||f.guid++,d=0,e=function(c){var e=(f._data(this,"lastToggle"+a.guid)||0)%d;f._data(this,"lastToggle"+a.guid,e+1),c.preventDefault();return 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)}}),f.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){f.fn[b]=function(a,c){c==null&&(c=a,a=null);return arguments.length>0?this.on(b,null,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0),C.test(b)&&(f.event.fixHooks[b]=f.event.keyHooks),D.test(b)&&(f.event.fixHooks[b]=f.event.mouseHooks)}),function(){function x(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}if(j.nodeType===1){g||(j[d]=c,j.sizset=h);if(typeof b!="string"){if(j===b){k=!0;break}}else if(m.filter(b,[j]).length>0){k=j;break}}j=j[a]}e[h]=k}}}function w(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}j.nodeType===1&&!g&&(j[d]=c,j.sizset=h);if(j.nodeName.toLowerCase()===b){k=j;break}j=j[a]}e[h]=k}}}var a=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d="sizcache"+(Math.random()+"").replace(".",""),e=0,g=Object.prototype.toString,h=!1,i=!0,j=/\\/g,k=/\r\n/g,l=/\W/;[0,0].sort(function(){i=!1;return 0});var m=function(b,d,e,f){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return e;var i,j,k,l,n,q,r,t,u=!0,v=m.isXML(d),w=[],x=b;do{a.exec(""),i=a.exec(x);if(i){x=i[3],w.push(i[1]);if(i[2]){l=i[3];break}}}while(i);if(w.length>1&&p.exec(b))if(w.length===2&&o.relative[w[0]])j=y(w[0]+w[1],d,f);else{j=o.relative[w[0]]?[d]:m(w.shift(),d);while(w.length)b=w.shift(),o.relative[b]&&(b+=w.shift()),j=y(b,j,f)}else{!f&&w.length>1&&d.nodeType===9&&!v&&o.match.ID.test(w[0])&&!o.match.ID.test(w[w.length-1])&&(n=m.find(w.shift(),d,v),d=n.expr?m.filter(n.expr,n.set)[0]:n.set[0]);if(d){n=f?{expr:w.pop(),set:s(f)}:m.find(w.pop(),w.length===1&&(w[0]==="~"||w[0]==="+")&&d.parentNode?d.parentNode:d,v),j=n.expr?m.filter(n.expr,n.set):n.set,w.length>0?k=s(j):u=!1;while(w.length)q=w.pop(),r=q,o.relative[q]?r=w.pop():q="",r==null&&(r=d),o.relative[q](k,r,v)}else k=w=[]}k||(k=j),k||m.error(q||b);if(g.call(k)==="[object Array]")if(!u)e.push.apply(e,k);else if(d&&d.nodeType===1)for(t=0;k[t]!=null;t++)k[t]&&(k[t]===!0||k[t].nodeType===1&&m.contains(d,k[t]))&&e.push(j[t]);else for(t=0;k[t]!=null;t++)k[t]&&k[t].nodeType===1&&e.push(j[t]);else s(k,e);l&&(m(l,h,e,f),m.uniqueSort(e));return e};m.uniqueSort=function(a){if(u){h=i,a.sort(u);if(h)for(var b=1;b<a.length;b++)a[b]===a[b-1]&&a.splice(b--,1)}return a},m.matches=function(a,b){return m(a,null,null,b)},m.matchesSelector=function(a,b){return m(b,null,null,[a]).length>0},m.find=function(a,b,c){var d,e,f,g,h,i;if(!a)return[];for(e=0,f=o.order.length;e<f;e++){h=o.order[e];if(g=o.leftMatch[h].exec(a)){i=g[1],g.splice(1,1);if(i.substr(i.length-1)!=="\\"){g[1]=(g[1]||"").replace(j,""),d=o.find[h](g,b,c);if(d!=null){a=a.replace(o.match[h],"");break}}}}d||(d=typeof b.getElementsByTagName!="undefined"?b.getElementsByTagName("*"):[]);return{set:d,expr:a}},m.filter=function(a,c,d,e){var f,g,h,i,j,k,l,n,p,q=a,r=[],s=c,t=c&&c[0]&&m.isXML(c[0]);while(a&&c.length){for(h in o.filter)if((f=o.leftMatch[h].exec(a))!=null&&f[2]){k=o.filter[h],l=f[1],g=!1,f.splice(1,1);if(l.substr(l.length-1)==="\\")continue;s===r&&(r=[]);if(o.preFilter[h]){f=o.preFilter[h](f,s,d,r,e,t);if(!f)g=i=!0;else if(f===!0)continue}if(f)for(n=0;(j=s[n])!=null;n++)j&&(i=k(j,f,n,s),p=e^i,d&&i!=null?p?g=!0:s[n]=!1:p&&(r.push(j),g=!0));if(i!==b){d||(s=r),a=a.replace(o.match[h],"");if(!g)return[];break}}if(a===q)if(g==null)m.error(a);else break;q=a}return s},m.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)};var n=m.getText=function(a){var b,c,d=a.nodeType,e="";if(d){if(d===1||d===9){if(typeof a.textContent=="string")return a.textContent;if(typeof a.innerText=="string")return a.innerText.replace(k,"");for(a=a.firstChild;a;a=a.nextSibling)e+=n(a)}else if(d===3||d===4)return a.nodeValue}else for(b=0;c=a[b];b++)c.nodeType!==8&&(e+=n(c));return e},o=m.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(a){return a.getAttribute("href")},type:function(a){return a.getAttribute("type")}},relative:{"+":function(a,b){var c=typeof b=="string",d=c&&!l.test(b),e=c&&!d;d&&(b=b.toLowerCase());for(var f=0,g=a.length,h;f<g;f++)if(h=a[f]){while((h=h.previousSibling)&&h.nodeType!==1);a[f]=e||h&&h.nodeName.toLowerCase()===b?h||!1:h===b}e&&m.filter(b,a,!0)},">":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!l.test(b)){b=b.toLowerCase();for(;e<f;e++){c=a[e];if(c){var g=c.parentNode;a[e]=g.nodeName.toLowerCase()===b?g:!1}}}else{for(;e<f;e++)c=a[e],c&&(a[e]=d?c.parentNode:c.parentNode===b);d&&m.filter(b,a,!0)}},"":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("parentNode",b,f,a,d,c)},"~":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("previousSibling",b,f,a,d,c)}},find:{ID:function(a,b,c){if(typeof b.getElementById!="undefined"&&!c){var d=b.getElementById(a[1]);return d&&d.parentNode?[d]:[]}},NAME:function(a,b){if(typeof b.getElementsByName!="undefined"){var c=[],d=b.getElementsByName(a[1]);for(var e=0,f=d.length;e<f;e++)d[e].getAttribute("name")===a[1]&&c.push(d[e]);return c.length===0?null:c}},TAG:function(a,b){if(typeof b.getElementsByTagName!="undefined")return b.getElementsByTagName(a[1])}},preFilter:{CLASS:function(a,b,c,d,e,f){a=" "+a[1].replace(j,"")+" ";if(f)return a;for(var g=0,h;(h=b[g])!=null;g++)h&&(e^(h.className&&(" "+h.className+" ").replace(/[\t\n\r]/g," ").indexOf(a)>=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(j,"")},TAG:function(a,b){return a[1].replace(j,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||m.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&m.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(j,"");!f&&o.attrMap[g]&&(a[1]=o.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(j,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=m(b[3],null,null,c);else{var g=m.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(o.match.POS.test(b[0])||o.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!m(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return a.nodeName.toLowerCase()==="input"&&"text"===c&&(b===c||b===null)},radio:function(a){return a.nodeName.toLowerCase()==="input"&&"radio"===a.type},checkbox:function(a){return a.nodeName.toLowerCase()==="input"&&"checkbox"===a.type},file:function(a){return a.nodeName.toLowerCase()==="input"&&"file"===a.type},password:function(a){return a.nodeName.toLowerCase()==="input"&&"password"===a.type},submit:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"submit"===a.type},image:function(a){return a.nodeName.toLowerCase()==="input"&&"image"===a.type},reset:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"reset"===a.type},button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&"button"===a.type||b==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)},focus:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return b<c[3]-0},gt:function(a,b,c){return b>c[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=o.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||n([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h<i;h++)if(g[h]===a)return!1;return!0}m.error(e)},CHILD:function(a,b){var c,e,f,g,h,i,j,k=b[1],l=a;switch(k){case"only":case"first":while(l=l.previousSibling)if(l.nodeType===1)return!1;if(k==="first")return!0;l=a;case"last":while(l=l.nextSibling)if(l.nodeType===1)return!1;return!0;case"nth":c=b[2],e=b[3];if(c===1&&e===0)return!0;f=b[0],g=a.parentNode;if(g&&(g[d]!==f||!a.nodeIndex)){i=0;for(l=g.firstChild;l;l=l.nextSibling)l.nodeType===1&&(l.nodeIndex=++i);g[d]=f}j=a.nodeIndex-e;return c===0?j===0:j%c===0&&j/c>=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||!!a.nodeName&&a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=m.attr?m.attr(a,c):o.attrHandle[c]?o.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":!f&&m.attr?d!=null:f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=o.setFilters[e];if(f)return f(a,c,b,d)}}},p=o.match.POS,q=function(a,b){return"\\"+(b-0+1)};for(var r in o.match)o.match[r]=new RegExp(o.match[r].source+/(?![^\[]*\])(?![^\(]*\))/.source),o.leftMatch[r]=new RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[r].source.replace(/\\(\d+)/g,q));var s=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(t){s=function(a,b){var c=0,d=b||[];if(g.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var e=a.length;c<e;c++)d.push(a[c]);else for(;a[c];c++)d.push(a[c]);return d}}var u,v;c.documentElement.compareDocumentPosition?u=function(a,b){if(a===b){h=!0;return 0}if(!a.compareDocumentPosition||!b.compareDocumentPosition)return a.compareDocumentPosition?-1:1;return a.compareDocumentPosition(b)&4?-1:1}:(u=function(a,b){if(a===b){h=!0;return 0}if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],f=[],g=a.parentNode,i=b.parentNode,j=g;if(g===i)return v(a,b);if(!g)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)f.unshift(j),j=j.parentNode;c=e.length,d=f.length;for(var k=0;k<c&&k<d;k++)if(e[k]!==f[k])return v(e[k],f[k]);return k===c?v(a,f[k],-1):v(e[k],b,1)},v=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}),function(){var a=c.createElement("div"),d="script"+(new Date).getTime(),e=c.documentElement;a.innerHTML="<a name='"+d+"'/>",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(o.find.ID=function(a,c,d){if(typeof c.getElementById!="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},o.filter.ID=function(a,b){var c=typeof a.getAttributeNode!="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(o.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(o.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=m,b=c.createElement("div"),d="__sizzle__";b.innerHTML="<p class='TEST'></p>";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){m=function(b,e,f,g){e=e||c;if(!g&&!m.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return s(e.getElementsByTagName(b),f);if(h[2]&&o.find.CLASS&&e.getElementsByClassName)return s(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return s([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return s([],f);if(i.id===h[3])return s([i],f)}try{return s(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var k=e,l=e.getAttribute("id"),n=l||d,p=e.parentNode,q=/^\s*[+~]/.test(b);l?n=n.replace(/'/g,"\\$&"):e.setAttribute("id",n),q&&p&&(e=e.parentNode);try{if(!q||p)return s(e.querySelectorAll("[id='"+n+"'] "+b),f)}catch(r){}finally{l||k.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)m[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}m.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!m.isXML(a))try{if(e||!o.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return m(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="<div class='test e'></div><div class='test'></div>";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;o.order.splice(1,0,"CLASS"),o.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?m.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?m.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:m.contains=function(){return!1},m.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var y=function(a,b,c){var d,e=[],f="",g=b.nodeType?[b]:b;while(d=o.match.PSEUDO.exec(a))f+=d[0],a=a.replace(o.match.PSEUDO,"");a=o.relative[a]?a+"*":a;for(var h=0,i=g.length;h<i;h++)m(a,g[h],e,c);return m.filter(f,e)};m.attr=f.attr,m.selectors.attrMap={},f.find=m,f.expr=m.selectors,f.expr[":"]=f.expr.filters,f.unique=m.uniqueSort,f.text=m.getText,f.isXMLDoc=m.isXML,f.contains=m.contains}();var L=/Until$/,M=/^(?:parents|prevUntil|prevAll)/,N=/,/,O=/^.[^:#\[\.,]*$/,P=Array.prototype.slice,Q=f.expr.match.POS,R={children:!0,contents:!0,next:!0,prev:!0};f.fn.extend({find:function(a){var b=this,c,d;if(typeof a!="string")return f(a).filter(function(){for(c=0,d=b.length;c<d;c++)if(f.contains(b[c],this))return!0});var e=this.pushStack("","find",a),g,h,i;for(c=0,d=this.length;c<d;c++){g=e.length,f.find(a,this[c],e);if(c>0)for(h=g;h<e.length;h++)for(i=0;i<g;i++)if(e[i]===e[h]){e.splice(h--,1);break}}return e},has:function(a){var b=f(a);return this.filter(function(){for(var a=0,c=b.length;a<c;a++)if(f.contains(this,b[a]))return!0})},not:function(a){return this.pushStack(T(this,a,!1),"not",a)},filter:function(a){return this.pushStack(T(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?Q.test(a)?f(a,this.context).index(this[0])>=0:f.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c=[],d,e,g=this[0];if(f.isArray(a)){var h=1;while(g&&g.ownerDocument&&g!==b){for(d=0;d<a.length;d++)f(g).is(a[d])&&c.push({selector:a[d],elem:g,level:h});g=g.parentNode,h++}return c}var i=Q.test(a)||typeof a!="string"?f(a,b||this.context):0;for(d=0,e=this.length;d<e;d++){g=this[d];while(g){if(i?i.index(g)>-1:f.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b||g.nodeType===11)break}}c=c.length>1?f.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a)return this[0]&&this[0].parentNode?this.prevAll().length:-1;if(typeof a=="string")return f.inArray(this[0],f(a));return f.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?f(a,b):f.makeArray(a&&a.nodeType?[a]:a),d=f.merge(this.get(),c);return this.pushStack(S(c[0])||S(d[0])?d:f.unique(d))},andSelf:function(){return this.add(this.prevObject)}}),f.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return f.dir(a,"parentNode")},parentsUntil:function(a,b,c){return f.dir(a,"parentNode",c)},next:function(a){return f.nth(a,2,"nextSibling")},prev:function(a){return f.nth(a,2,"previousSibling")},nextAll:function(a){return f.dir(a,"nextSibling")},prevAll:function(a){return f.dir(a,"previousSibling")},nextUntil:function(a,b,c){return f.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return f.dir(a,"previousSibling",c)},siblings:function(a){return f.sibling(a.parentNode.firstChild,a)},children:function(a){return f.sibling(a.firstChild)},contents:function(a){return f.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:f.makeArray(a.childNodes)}},function(a,b){f.fn[a]=function(c,d){var e=f.map(this,b,c);L.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!R[a]?f.unique(e):e,(this.length>1||N.test(d))&&M.test(a)&&(e=e.reverse());return this.pushStack(e,a,P.call(arguments).join(","))}}),f.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?f.find.matchesSelector(b[0],a)?[b[0]]:[]:f.find.matches(a,b)},dir:function(a,c,d){var e=[],g=a[c];while(g&&g.nodeType!==9&&(d===b||g.nodeType!==1||!f(g).is(d)))g.nodeType===1&&e.push(g),g=g[c];return e},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var V="abbr|article|aside|audio|canvas|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",W=/ jQuery\d+="(?:\d+|null)"/g,X=/^\s+/,Y=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,Z=/<([\w:]+)/,$=/<tbody/i,_=/<|&#?\w+;/,ba=/<(?:script|style)/i,bb=/<(?:script|object|embed|option|style)/i,bc=new RegExp("<(?:"+V+")","i"),bd=/checked\s*(?:[^=]|=\s*.checked.)/i,be=/\/(java|ecma)script/i,bf=/^\s*<!(?:\[CDATA\[|\-\-)/,bg={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,"",""]},bh=U(c);bg.optgroup=bg.option,bg.tbody=bg.tfoot=bg.colgroup=bg.caption=bg.thead,bg.th=bg.td,f.support.htmlSerialize||(bg._default=[1,"div<div>","</div>"]),f.fn.extend({text:function(a){if(f.isFunction(a))return this.each(function(b){var c=f(this);c.text(a.call(this,b,c.text()))});if(typeof a!="object"&&a!==b)return this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a));return f.text(this)},wrapAll:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapAll(a.call(this,b))});if(this[0]){var b=f(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){if(f.isFunction(a))return this.each(function(b){f(this).wrapInner(a.call(this,b))});return this.each(function(){var b=f(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=f.isFunction(a);return this.each(function(c){f(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){f.nodeName(this,"body")||f(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=f.clean(arguments);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after",arguments);a.push.apply(a,f.clean(arguments));return a}},remove:function(a,b){for(var c=0,d;(d=this[c])!=null;c++)if(!a||f.filter(a,[d]).length)!b&&d.nodeType===1&&(f.cleanData(d.getElementsByTagName("*")),f.cleanData([d])),d.parentNode&&d.parentNode.removeChild(d);return this},empty:function()
{for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&f.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return f.clone(this,a,b)})},html:function(a){if(a===b)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(W,""):null;if(typeof a=="string"&&!ba.test(a)&&(f.support.leadingWhitespace||!X.test(a))&&!bg[(Z.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(Y,"<$1></$2>");try{for(var c=0,d=this.length;c<d;c++)this[c].nodeType===1&&(f.cleanData(this[c].getElementsByTagName("*")),this[c].innerHTML=a)}catch(e){this.empty().append(a)}}else f.isFunction(a)?this.each(function(b){var c=f(this);c.html(a.call(this,b,c.html()))}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(f.isFunction(a))return this.each(function(b){var c=f(this),d=c.html();c.replaceWith(a.call(this,b,d))});typeof a!="string"&&(a=f(a).detach());return this.each(function(){var b=this.nextSibling,c=this.parentNode;f(this).remove(),b?f(b).before(a):f(c).append(a)})}return this.length?this.pushStack(f(f.isFunction(a)?a():a),"replaceWith",a):this},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){var e,g,h,i,j=a[0],k=[];if(!f.support.checkClone&&arguments.length===3&&typeof j=="string"&&bd.test(j))return this.each(function(){f(this).domManip(a,c,d,!0)});if(f.isFunction(j))return this.each(function(e){var g=f(this);a[0]=j.call(this,e,c?g.html():b),g.domManip(a,c,d)});if(this[0]){i=j&&j.parentNode,f.support.parentNode&&i&&i.nodeType===11&&i.childNodes.length===this.length?e={fragment:i}:e=f.buildFragment(a,this,k),h=e.fragment,h.childNodes.length===1?g=h=h.firstChild:g=h.firstChild;if(g){c=c&&f.nodeName(g,"tr");for(var l=0,m=this.length,n=m-1;l<m;l++)d.call(c?bi(this[l],g):this[l],e.cacheable||m>1&&l<n?f.clone(h,!0,!0):h)}k.length&&f.each(k,bp)}return this}}),f.buildFragment=function(a,b,d){var e,g,h,i,j=a[0];b&&b[0]&&(i=b[0].ownerDocument||b[0]),i.createDocumentFragment||(i=c),a.length===1&&typeof j=="string"&&j.length<512&&i===c&&j.charAt(0)==="<"&&!bb.test(j)&&(f.support.checkClone||!bd.test(j))&&(f.support.html5Clone||!bc.test(j))&&(g=!0,h=f.fragments[j],h&&h!==1&&(e=h)),e||(e=i.createDocumentFragment(),f.clean(a,i,e,d)),g&&(f.fragments[j]=h?e:1);return{fragment:e,cacheable:g}},f.fragments={},f.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){f.fn[a]=function(c){var d=[],e=f(c),g=this.length===1&&this[0].parentNode;if(g&&g.nodeType===11&&g.childNodes.length===1&&e.length===1){e[b](this[0]);return this}for(var h=0,i=e.length;h<i;h++){var j=(h>0?this.clone(!0):this).get();f(e[h])[b](j),d=d.concat(j)}return this.pushStack(d,a,e.selector)}}),f.extend({clone:function(a,b,c){var d,e,g,h=f.support.html5Clone||!bc.test("<"+a.nodeName)?a.cloneNode(!0):bo(a);if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bk(a,h),d=bl(a),e=bl(h);for(g=0;d[g];++g)e[g]&&bk(d[g],e[g])}if(b){bj(a,h);if(c){d=bl(a),e=bl(h);for(g=0;d[g];++g)bj(d[g],e[g])}}d=e=null;return h},clean:function(a,b,d,e){var g;b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);var h=[],i;for(var j=0,k;(k=a[j])!=null;j++){typeof k=="number"&&(k+="");if(!k)continue;if(typeof k=="string")if(!_.test(k))k=b.createTextNode(k);else{k=k.replace(Y,"<$1></$2>");var l=(Z.exec(k)||["",""])[1].toLowerCase(),m=bg[l]||bg._default,n=m[0],o=b.createElement("div");b===c?bh.appendChild(o):U(b).appendChild(o),o.innerHTML=m[1]+k+m[2];while(n--)o=o.lastChild;if(!f.support.tbody){var p=$.test(k),q=l==="table"&&!p?o.firstChild&&o.firstChild.childNodes:m[1]==="<table>"&&!p?o.childNodes:[];for(i=q.length-1;i>=0;--i)f.nodeName(q[i],"tbody")&&!q[i].childNodes.length&&q[i].parentNode.removeChild(q[i])}!f.support.leadingWhitespace&&X.test(k)&&o.insertBefore(b.createTextNode(X.exec(k)[0]),o.firstChild),k=o.childNodes}var r;if(!f.support.appendChecked)if(k[0]&&typeof (r=k.length)=="number")for(i=0;i<r;i++)bn(k[i]);else bn(k);k.nodeType?h.push(k):h=f.merge(h,k)}if(d){g=function(a){return!a.type||be.test(a.type)};for(j=0;h[j];j++)if(e&&f.nodeName(h[j],"script")&&(!h[j].type||h[j].type.toLowerCase()==="text/javascript"))e.push(h[j].parentNode?h[j].parentNode.removeChild(h[j]):h[j]);else{if(h[j].nodeType===1){var s=f.grep(h[j].getElementsByTagName("script"),g);h.splice.apply(h,[j+1,0].concat(s))}d.appendChild(h[j])}}return h},cleanData:function(a){var b,c,d=f.cache,e=f.event.special,g=f.support.deleteExpando;for(var h=0,i;(i=a[h])!=null;h++){if(i.nodeName&&f.noData[i.nodeName.toLowerCase()])continue;c=i[f.expando];if(c){b=d[c];if(b&&b.events){for(var j in b.events)e[j]?f.event.remove(i,j):f.removeEvent(i,j,b.handle);b.handle&&(b.handle.elem=null)}g?delete i[f.expando]:i.removeAttribute&&i.removeAttribute(f.expando),delete d[c]}}}});var bq=/alpha\([^)]*\)/i,br=/opacity=([^)]*)/,bs=/([A-Z]|^ms)/g,bt=/^-?\d+(?:px)?$/i,bu=/^-?\d/,bv=/^([\-+])=([\-+.\de]+)/,bw={position:"absolute",visibility:"hidden",display:"block"},bx=["Left","Right"],by=["Top","Bottom"],bz,bA,bB;f.fn.css=function(a,c){if(arguments.length===2&&c===b)return this;return f.access(this,a,c,!0,function(a,c,d){return d!==b?f.style(a,c,d):f.css(a,c)})},f.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bz(a,"opacity","opacity");return c===""?"1":c}return a.style.opacity}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":f.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!!a&&a.nodeType!==3&&a.nodeType!==8&&!!a.style){var g,h,i=f.camelCase(c),j=a.style,k=f.cssHooks[i];c=f.cssProps[i]||i;if(d===b){if(k&&"get"in k&&(g=k.get(a,!1,e))!==b)return g;return j[c]}h=typeof d,h==="string"&&(g=bv.exec(d))&&(d=+(g[1]+1)*+g[2]+parseFloat(f.css(a,c)),h="number");if(d==null||h==="number"&&isNaN(d))return;h==="number"&&!f.cssNumber[i]&&(d+="px");if(!k||!("set"in k)||(d=k.set(a,d))!==b)try{j[c]=d}catch(l){}}},css:function(a,c,d){var e,g;c=f.camelCase(c),g=f.cssHooks[c],c=f.cssProps[c]||c,c==="cssFloat"&&(c="float");if(g&&"get"in g&&(e=g.get(a,!0,d))!==b)return e;if(bz)return bz(a,c)},swap:function(a,b,c){var d={};for(var e in b)d[e]=a.style[e],a.style[e]=b[e];c.call(a);for(e in b)a.style[e]=d[e]}}),f.curCSS=f.css,f.each(["height","width"],function(a,b){f.cssHooks[b]={get:function(a,c,d){var e;if(c){if(a.offsetWidth!==0)return bC(a,b,d);f.swap(a,bw,function(){e=bC(a,b,d)});return e}},set:function(a,b){if(!bt.test(b))return b;b=parseFloat(b);if(b>=0)return b+"px"}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return br.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=f.isNumeric(b)?"alpha(opacity="+b*100+")":"",g=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&f.trim(g.replace(bq,""))===""){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bq.test(g)?g.replace(bq,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){var c;f.swap(a,{display:"inline-block"},function(){b?c=bz(a,"margin-right","marginRight"):c=a.style.marginRight});return c}})}),c.defaultView&&c.defaultView.getComputedStyle&&(bA=function(a,b){var c,d,e;b=b.replace(bs,"-$1").toLowerCase(),(d=a.ownerDocument.defaultView)&&(e=d.getComputedStyle(a,null))&&(c=e.getPropertyValue(b),c===""&&!f.contains(a.ownerDocument.documentElement,a)&&(c=f.style(a,b)));return c}),c.documentElement.currentStyle&&(bB=function(a,b){var c,d,e,f=a.currentStyle&&a.currentStyle[b],g=a.style;f===null&&g&&(e=g[b])&&(f=e),!bt.test(f)&&bu.test(f)&&(c=g.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),g.left=b==="fontSize"?"1em":f||0,f=g.pixelLeft+"px",g.left=c,d&&(a.runtimeStyle.left=d));return f===""?"auto":f}),bz=bA||bB,f.expr&&f.expr.filters&&(f.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!f.support.reliableHiddenOffsets&&(a.style&&a.style.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)});var bD=/%20/g,bE=/\[\]$/,bF=/\r?\n/g,bG=/#.*$/,bH=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bI=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bJ=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,bK=/^(?:GET|HEAD)$/,bL=/^\/\//,bM=/\?/,bN=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bO=/^(?:select|textarea)/i,bP=/\s+/,bQ=/([?&])_=[^&]*/,bR=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bS=f.fn.load,bT={},bU={},bV,bW,bX=["*/"]+["*"];try{bV=e.href}catch(bY){bV=c.createElement("a"),bV.href="",bV=bV.href}bW=bR.exec(bV.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bS)return bS.apply(this,arguments);if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var g=a.slice(e,a.length);a=a.slice(0,e)}var h="GET";c&&(f.isFunction(c)?(d=c,c=b):typeof c=="object"&&(c=f.param(c,f.ajaxSettings.traditional),h="POST"));var i=this;f.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?f("<div>").append(c.replace(bN,"")).find(g):c)),d&&i.each(d,[c,b,a])}});return this},serialize:function(){return f.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?f.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bO.test(this.nodeName)||bI.test(this.type))}).map(function(a,b){var c=f(this).val();return c==null?null:f.isArray(c)?f.map(c,function(a,c){return{name:b.name,value:a.replace(bF,"\r\n")}}):{name:b.name,value:c.replace(bF,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.on(b,a)}}),f.each(["get","post"],function(a,c){f[c]=function(a,d,e,g){f.isFunction(d)&&(g=g||e,e=d,d=b);return f.ajax({type:c,url:a,data:d,success:e,dataType:g})}}),f.extend({getScript:function(a,c){return f.get(a,b,c,"script")},getJSON:function(a,b,c){return f.get(a,b,c,"json")},ajaxSetup:function(a,b){b?b_(a,f.ajaxSettings):(b=a,a=f.ajaxSettings),b_(a,b);return a},ajaxSettings:{url:bV,isLocal:bJ.test(bW[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":bX},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":f.parseJSON,"text xml":f.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:bZ(bT),ajaxTransport:bZ(bU),ajax:function(a,c){function w(a,c,l,m){if(s!==2){s=2,q&&clearTimeout(q),p=b,n=m||"",v.readyState=a>0?4:0;var o,r,u,w=c,x=l?cb(d,v,l):b,y,z;if(a>=200&&a<300||a===304){if(d.ifModified){if(y=v.getResponseHeader("Last-Modified"))f.lastModified[k]=y;if(z=v.getResponseHeader("Etag"))f.etag[k]=z}if(a===304)w="notmodified",o=!0;else try{r=cc(d,x),w="success",o=!0}catch(A){w="parsererror",u=A}}else{u=w;if(!w||a)w="error",a<0&&(a=0)}v.status=a,v.statusText=""+(c||w),o?h.resolveWith(e,[r,w,v]):h.rejectWith(e,[v,w,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.fireWith(e,[v,w]),t&&(g.trigger("ajaxComplete",[v,d]),--f.active||f.event.trigger("ajaxStop"))}}typeof a=="object"&&(c=a,a=b),c=c||{};var d=f.ajaxSetup({},c),e=d.context||d,g=e!==d&&(e.nodeType||e instanceof f)?f(e):f.event,h=f.Deferred(),i=f.Callbacks("once memory"),j=d.statusCode||{},k,l={},m={},n,o,p,q,r,s=0,t,u,v={readyState:0,setRequestHeader:function(a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this},getAllResponseHeaders:function(){return s===2?n:null},getResponseHeader:function(a){var c;if(s===2){if(!o){o={};while(c=bH.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){s||(d.mimeType=a);return this},abort:function(a){a=a||"abort",p&&p.abort(a),w(0,a);return this}};h.promise(v),v.success=v.done,v.error=v.fail,v.complete=i.add,v.statusCode=function(a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this},d.url=((a||d.url)+"").replace(bG,"").replace(bL,bW[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bP),d.crossDomain==null&&(r=bR.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bW[1]&&r[2]==bW[2]&&(r[3]||(r[1]==="http:"?80:443))==(bW[3]||(bW[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),b$(bT,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bK.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bM.test(d.url)?"&":"?")+d.data,delete d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bQ,"$1_="+x);d.url=y+(y===d.url?(bM.test(d.url)?"&":"?")+"_="+x:"")}}(d.data&&d.hasContent&&d.contentType!==!1||c.contentType)&&v.setRequestHeader("Content-Type",d.contentType),d.ifModified&&(k=k||d.url,f.lastModified[k]&&v.setRequestHeader("If-Modified-Since",f.lastModified[k]),f.etag[k]&&v.setRequestHeader("If-None-Match",f.etag[k])),v.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+(d.dataTypes[0]!=="*"?", "+bX+"; q=0.01":""):d.accepts["*"]);for(u in d.headers)v.setRequestHeader(u,d.headers[u]);if(d.beforeSend&&(d.beforeSend.call(e,v,d)===!1||s===2)){v.abort();return!1}for(u in{success:1,error:1,complete:1})v[u](d[u]);p=b$(bU,d,c,v);if(!p)w(-1,"No Transport");else{v.readyState=1,t&&g.trigger("ajaxSend",[v,d]),d.async&&d.timeout>0&&(q=setTimeout(function(){v.abort("timeout")},d.timeout));try{s=1,p.send(l,w)}catch(z){if(s<2)w(-1,z);else throw z}}return v},param:function(a,c){var d=[],e=function(a,b){b=f.isFunction(b)?b():b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=f.ajaxSettings.traditional);if(f.isArray(a)||a.jquery&&!f.isPlainObject(a))f.each(a,function(){e(this.name,this.value)});else for(var g in a)ca(g,a[g],c,e);return d.join("&").replace(bD,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var cd=f.now(),ce=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+cd++}}),f.ajaxPrefilter("json jsonp",function(b,c,d){var e=b.contentType==="application/x-www-form-urlencoded"&&typeof b.data=="string";if(b.dataTypes[0]==="jsonp"||b.jsonp!==!1&&(ce.test(b.url)||e&&ce.test(b.data))){var g,h=b.jsonpCallback=f.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2";b.jsonp!==!1&&(j=j.replace(ce,l),b.url===j&&(e&&(k=k.replace(ce,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},d.always(function(){a[h]=i,g&&f.isFunction(i)&&a[h](g[0])}),b.converters["script json"]=function(){g||f.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),f.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){f.globalEval(a);return a}}}),f.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),f.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(c||!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var cf=a.ActiveXObject?function(){for(var a in ch)ch[a](0,1)}:!1,cg=0,ch;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ci()||cj()}:ci,function(a){f.extend(f.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(f.ajaxSettings.xhr()),f.support.ajax&&f.ajaxTransport(function(c){if(!c.crossDomain||f.support.cors){var d;return{send:function(e,g){var h=c.xhr(),i,j;c.username?h.open(c.type,c.url,c.async,c.username,c.password):h.open(c.type,c.url,c.async);if(c.xhrFields)for(j in c.xhrFields)h[j]=c.xhrFields[j];c.mimeType&&h.overrideMimeType&&h.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(j in e)h.setRequestHeader(j,e[j])}catch(k){}h.send(c.hasContent&&c.data||null),d=function(a,e){var j,k,l,m,n;try{if(d&&(e||h.readyState===4)){d=b,i&&(h.onreadystatechange=f.noop,cf&&delete ch[i]);if(e)h.readyState!==4&&h.abort();else{j=h.status,l=h.getAllResponseHeaders(),m={},n=h.responseXML,n&&n.documentElement&&(m.xml=n),m.text=h.responseText;try{k=h.statusText}catch(o){k=""}!j&&c.isLocal&&!c.crossDomain?j=m.text?200:404:j===1223&&(j=204)}}}catch(p){e||g(-1,p)}m&&g(j,k,m,l)},!c.async||h.readyState===4?d():(i=++cg,cf&&(ch||(ch={},f(a).unload(cf)),ch[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var ck={},cl,cm,cn=/^(?:toggle|show|hide)$/,co=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,cp,cq=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],cr;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(cu("show",3),a,b,c);for(var g=0,h=this.length;g<h;g++)d=this[g],d.style&&(e=d.style.display,!f._data(d,"olddisplay")&&e==="none"&&(e=d.style.display=""),e===""&&f.css(d,"display")==="none"&&f._data(d,"olddisplay",cv(d.nodeName)));for(g=0;g<h;g++){d=this[g];if(d.style){e=d.style.display;if(e===""||e==="none")d.style.display=f._data(d,"olddisplay")||""}}return this},hide:function(a,b,c){if(a||a===0)return this.animate(cu("hide",3),a,b,c);var d,e,g=0,h=this.length;for(;g<h;g++)d=this[g],d.style&&(e=f.css(d,"display"),e!=="none"&&!f._data(d,"olddisplay")&&f._data(d,"olddisplay",e));for(g=0;g<h;g++)this[g].style&&(this[g].style.display="none");return this},_toggle:f.fn.toggle,toggle:function(a,b,c){var d=typeof a=="boolean";f.isFunction(a)&&f.isFunction(b)?this._toggle.apply(this,arguments):a==null||d?this.each(function(){var b=d?a:f(this).is(":hidden");f(this)[b?"show":"hide"]()}):this.animate(cu("toggle",3),a,b,c);return this},fadeTo:function(a,b,c,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){function g(){e.queue===!1&&f._mark(this);var b=f.extend({},e),c=this.nodeType===1,d=c&&f(this).is(":hidden"),g,h,i,j,k,l,m,n,o;b.animatedProperties={};for(i in a){g=f.camelCase(i),i!==g&&(a[g]=a[i],delete a[i]),h=a[g],f.isArray(h)?(b.animatedProperties[g]=h[1],h=a[g]=h[0]):b.animatedProperties[g]=b.specialEasing&&b.specialEasing[g]||b.easing||"swing";if(h==="hide"&&d||h==="show"&&!d)return b.complete.call(this);c&&(g==="height"||g==="width")&&(b.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY],f.css(this,"display")==="inline"&&f.css(this,"float")==="none"&&(!f.support.inlineBlockNeedsLayout||cv(this.nodeName)==="inline"?this.style.display="inline-block":this.style.zoom=1))}b.overflow!=null&&(this.style.overflow="hidden");for(i in a)j=new f.fx(this,b,i),h=a[i],cn.test(h)?(o=f._data(this,"toggle"+i)||(h==="toggle"?d?"show":"hide":0),o?(f._data(this,"toggle"+i,o==="show"?"hide":"show"),j[o]()):j[h]()):(k=co.exec(h),l=j.cur(),k?(m=parseFloat(k[2]),n=k[3]||(f.cssNumber[i]?"":"px"),n!=="px"&&(f.style(this,i,(m||1)+n),l=(m||1)/j.cur()*l,f.style(this,i,l+n)),k[1]&&(m=(k[1]==="-="?-1:1)*m+l),j.custom(l,m,n)):j.custom(l,h,""));return!0}var e=f.speed(b,c,d);if(f.isEmptyObject(a))return this.each(e.complete,[!1]);a=f.extend({},a);return e.queue===!1?this.each(g):this.queue(e.queue,g)},stop:function(a,c,d){typeof a!="string"&&(d=c,c=a,a=b),c&&a!==!1&&this.queue(a||"fx",[]);return this.each(function(){function h(a,b,c){var e=b[c];f.removeData(a,c,!0),e.stop(d)}var b,c=!1,e=f.timers,g=f._data(this);d||f._unmark(!0,this);if(a==null)for(b in g)g[b]&&g[b].stop&&b.indexOf(".run")===b.length-4&&h(this,g,b);else g[b=a+".run"]&&g[b].stop&&h(this,g,b);for(b=e.length;b--;)e[b].elem===this&&(a==null||e[b].queue===a)&&(d?e[b](!0):e[b].saveState(),c=!0,e.splice(b,1));(!d||!c)&&f.dequeue(this,a)})}}),f.each({slideDown:cu("show",1),slideUp:cu("hide",1),slideToggle:cu("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){f.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),f.extend({speed:function(a,b,c){var d=a&&typeof a=="object"?f.extend({},a):{complete:c||!c&&b||f.isFunction(a)&&a,duration:a,easing:c&&b||b&&!f.isFunction(b)&&b};d.duration=f.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in f.fx.speeds?f.fx.speeds[d.duration]:f.fx.speeds._default;if(d.queue==null||d.queue===!0)d.queue="fx";d.old=d.complete,d.complete=function(a){f.isFunction(d.old)&&d.old.call(this),d.queue?f.dequeue(this,d.queue):a!==!1&&f._unmark(this)};return d},easing:{linear:function(a,b,c,d){return c+d*a},swing:function(a,b,c,d){return(-Math.cos(a*Math.PI)/2+.5)*d+c}},timers:[],fx:function(a,b,c){this.options=b,this.elem=a,this.prop=c,b.orig=b.orig||{}}}),f.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this),(f.fx.step[this.prop]||f.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];var a,b=f.css(this.elem,this.prop);return isNaN(a=parseFloat(b))?!b||b==="auto"?0:b:a},custom:function(a,c,d){function h(a){return e.step(a)}var e=this,g=f.fx;this.startTime=cr||cs(),this.end=c,this.now=this.start=a,this.pos=this.state=0,this.unit=d||this.unit||(f.cssNumber[this.prop]?"":"px"),h.queue=this.options.queue,h.elem=this.elem,h.saveState=function(){e.options.hide&&f._data(e.elem,"fxshow"+e.prop)===b&&f._data(e.elem,"fxshow"+e.prop,e.start)},h()&&f.timers.push(h)&&!cp&&(cp=setInterval(g.tick,g.interval))},show:function(){var a=f._data(this.elem,"fxshow"+this.prop);this.options.orig[this.prop]=a||f.style(this.elem,this.prop),this.options.show=!0,a!==b?this.custom(this.cur(),a):this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur()),f(this.elem).show()},hide:function(){this.options.orig[this.prop]=f._data(this.elem,"fxshow"+this.prop)||f.style(this.elem,this.prop),this.options.hide=!0,this.custom(this.cur(),0)},step:function(a){var b,c,d,e=cr||cs(),g=!0,h=this.elem,i=this.options;if(a||e>=i.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),i.animatedProperties[this.prop]=!0;for(b in i.animatedProperties)i.animatedProperties[b]!==!0&&(g=!1);if(g){i.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){h.style["overflow"+b]=i.overflow[a]}),i.hide&&f(h).hide();if(i.hide||i.show)for(b in i.animatedProperties)f.style(h,b,i.orig[b]),f.removeData(h,"fxshow"+b,!0),f.removeData(h,"toggle"+b,!0);d=i.complete,d&&(i.complete=!1,d.call(h))}return!1}i.duration==Infinity?this.now=e:(c=e-this.startTime,this.state=c/i.duration,this.pos=f.easing[i.animatedProperties[this.prop]](this.state,c,0,1,i.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){var a,b=f.timers,c=0;for(;c<b.length;c++)a=b[c],!a()&&b[c]===a&&b.splice(c--,1);b.length||f.fx.stop()},interval:13,stop:function(){clearInterval(cp),cp=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){f.style(a.elem,"opacity",a.now)},_default:function(a){a.elem.style&&a.elem.style[a.prop]!=null?a.elem.style[a.prop]=a.now+a.unit:a.elem[a.prop]=a.now}}}),f.each(["width","height"],function(a,b){f.fx.step[b]=function(a){f.style(a.elem,b,Math.max(0,a.now)+a.unit)}}),f.expr&&f.expr.filters&&(f.expr.filters.animated=function(a){return f.grep(f.timers,function(b){return a===b.elem}).length});var cw=/^t(?:able|d|h)$/i,cx=/^(?:body|html)$/i;"getBoundingClientRect"in c.documentElement?f.fn.offset=function(a){var b=this[0],c;if(a)return this.each(function(b){f.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return f.offset.bodyOffset(b);try{c=b.getBoundingClientRect()}catch(d){}var e=b.ownerDocument,g=e.documentElement;if(!c||!f.contains(g,b))return c?{top:c.top,left:c.left}:{top:0,left:0};var h=e.body,i=cy(e),j=g.clientTop||h.clientTop||0,k=g.clientLeft||h.clientLeft||0,l=i.pageYOffset||f.support.boxModel&&g.scrollTop||h.scrollTop,m=i.pageXOffset||f.support.boxModel&&g.scrollLeft||h.scrollLeft,n=c.top+l-j,o=c.left+m-k;return{top:n,left:o}}:f.fn.offset=function(a){var b=this[0];if(a)return this.each(function(b){f.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return f.offset.bodyOffset(b);var c,d=b.offsetParent,e=b,g=b.ownerDocument,h=g.documentElement,i=g.body,j=g.defaultView,k=j?j.getComputedStyle(b,null):b.currentStyle,l=b.offsetTop,m=b.offsetLeft;while((b=b.parentNode)&&b!==i&&b!==h){if(f.support.fixedPosition&&k.position==="fixed")break;c=j?j.getComputedStyle(b,null):b.currentStyle,l-=b.scrollTop,m-=b.scrollLeft,b===d&&(l+=b.offsetTop,m+=b.offsetLeft,f.support.doesNotAddBorder&&(!f.support.doesAddBorderForTableAndCells||!cw.test(b.nodeName))&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),e=d,d=b.offsetParent),f.support.subtractsBorderForOverflowNotVisible&&c.overflow!=="visible"&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),k=c}if(k.position==="relative"||k.position==="static")l+=i.offsetTop,m+=i.offsetLeft;f.support.fixedPosition&&k.position==="fixed"&&(l+=Math.max(h.scrollTop,i.scrollTop),m+=Math.max(h.scrollLeft,i.scrollLeft));return{top:l,left:m}},f.offset={bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;f.support.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(f.css(a,"marginTop"))||0,c+=parseFloat(f.css(a,"marginLeft"))||0);return{top:b,left:c}},setOffset:function(a,b,c){var d=f.css(a,"position");d==="static"&&(a.style.position="relative");var e=f(a),g=e.offset(),h=f.css(a,"top"),i=f.css(a,"left"),j=(d==="absolute"||d==="fixed")&&f.inArray("auto",[h,i])>-1,k={},l={},m,n;j?(l=e.position(),m=l.top,n=l.left):(m=parseFloat(h)||0,n=parseFloat(i)||0),f.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):e.css(k)}},f.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),d=cx.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(f.css(a,"marginTop"))||0,c.left-=parseFloat(f.css(a,"marginLeft"))||0,d.top+=parseFloat(f.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(f.css(b[0],"borderLeftWidth"))||0;return{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&!cx.test(a.nodeName)&&f.css(a,"position")==="static")a=a.offsetParent;return a})}}),f.each(["Left","Top"],function(a,c){var d="scroll"+c;f.fn[d]=function(c){var e,g;if(c===b){e=this[0];if(!e)return null;g=cy(e);return g?"pageXOffset"in g?g[a?"pageYOffset":"pageXOffset"]:f.support.boxModel&&g.document.documentElement[d]||g.document.body[d]:e[d]}return this.each(function(){g=cy(this),g?g.scrollTo(a?f(g).scrollLeft():c,a?c:f(g).scrollTop()):this[d]=c})}}),f.each(["Height","Width"],function(a,c){var d=c.toLowerCase();f.fn["inner"+c]=function(){var a=this[0];return a?a.style?parseFloat(f.css(a,d,"padding")):this[d]():null},f.fn["outer"+c]=function(a){var b=this[0];return b?b.style?parseFloat(f.css(b,d,a?"margin":"border")):this[d]():null},f.fn[d]=function(a){var e=this[0];if(!e)return a==null?null:this;if(f.isFunction(a))return this.each(function(b){var c=f(this);c[d](a.call(this,b,c[d]()))});if(f.isWindow(e)){var g=e.document.documentElement["client"+c],h=e.document.body;return e.document.compatMode==="CSS1Compat"&&g||h&&h["client"+c]||g}if(e.nodeType===9)return Math.max(e.documentElement["client"+c],e.body["scroll"+c],e.documentElement["scroll"+c],e.body["offset"+c],e.documentElement["offset"+c]);if(a===b){var i=f.css(e,d),j=parseFloat(i);return f.isNumeric(j)?j:i}return this.css(d,typeof a=="string"?a:a+"px")}}),a.jQuery=a.$=f,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return f})})(window); |
app/javascript/mastodon/features/follow_requests/index.js | theoria24/mastodon | import React from 'react';
import { connect } from 'react-redux';
import { defineMessages, injectIntl, FormattedMessage } from 'react-intl';
import ImmutablePureComponent from 'react-immutable-pure-component';
import PropTypes from 'prop-types';
import ImmutablePropTypes from 'react-immutable-proptypes';
import { debounce } from 'lodash';
import LoadingIndicator from '../../components/loading_indicator';
import Column from '../ui/components/column';
import ColumnBackButtonSlim from '../../components/column_back_button_slim';
import AccountAuthorizeContainer from './containers/account_authorize_container';
import { fetchFollowRequests, expandFollowRequests } from '../../actions/accounts';
import ScrollableList from '../../components/scrollable_list';
import { me } from '../../initial_state';
const messages = defineMessages({
heading: { id: 'column.follow_requests', defaultMessage: 'Follow requests' },
});
const mapStateToProps = state => ({
accountIds: state.getIn(['user_lists', 'follow_requests', 'items']),
isLoading: state.getIn(['user_lists', 'follow_requests', 'isLoading'], true),
hasMore: !!state.getIn(['user_lists', 'follow_requests', 'next']),
locked: !!state.getIn(['accounts', me, 'locked']),
domain: state.getIn(['meta', 'domain']),
});
export default @connect(mapStateToProps)
@injectIntl
class FollowRequests extends ImmutablePureComponent {
static propTypes = {
params: PropTypes.object.isRequired,
dispatch: PropTypes.func.isRequired,
hasMore: PropTypes.bool,
isLoading: PropTypes.bool,
accountIds: ImmutablePropTypes.list,
locked: PropTypes.bool,
domain: PropTypes.string,
intl: PropTypes.object.isRequired,
multiColumn: PropTypes.bool,
};
componentWillMount () {
this.props.dispatch(fetchFollowRequests());
}
handleLoadMore = debounce(() => {
this.props.dispatch(expandFollowRequests());
}, 300, { leading: true });
render () {
const { intl, accountIds, hasMore, multiColumn, locked, domain, isLoading } = this.props;
if (!accountIds) {
return (
<Column>
<LoadingIndicator />
</Column>
);
}
const emptyMessage = <FormattedMessage id='empty_column.follow_requests' defaultMessage="You don't have any follow requests yet. When you receive one, it will show up here." />;
const unlockedPrependMessage = locked ? null : (
<div className='follow_requests-unlocked_explanation'>
<FormattedMessage
id='follow_requests.unlocked_explanation'
defaultMessage='Even though your account is not locked, the {domain} staff thought you might want to review follow requests from these accounts manually.'
values={{ domain: domain }}
/>
</div>
);
return (
<Column bindToDocument={!multiColumn} icon='user-plus' heading={intl.formatMessage(messages.heading)}>
<ColumnBackButtonSlim />
<ScrollableList
scrollKey='follow_requests'
onLoadMore={this.handleLoadMore}
hasMore={hasMore}
isLoading={isLoading}
emptyMessage={emptyMessage}
bindToDocument={!multiColumn}
prepend={unlockedPrependMessage}
>
{accountIds.map(id =>
<AccountAuthorizeContainer key={id} id={id} />,
)}
</ScrollableList>
</Column>
);
}
}
|
docs/app/Examples/elements/Container/Types/ContainerExampleText.js | aabustamante/Semantic-UI-React | /* eslint-disable max-len */
import React from 'react'
import { Container, Header } from 'semantic-ui-react'
const ContainerExampleText = () => (
<Container text>
<Header as='h2'>Header</Header>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa strong. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede link mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi.</p>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa strong. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a, venenatis vitae, justo. Nullam dictum felis eu pede link mollis pretium. Integer tincidunt. Cras dapibus. Vivamus elementum semper nisi. Aenean vulputate eleifend tellus. Aenean leo ligula, porttitor eu, consequat vitae, eleifend ac, enim. Aliquam lorem ante, dapibus in, viverra quis, feugiat a, tellus. Phasellus viverra nulla ut metus varius laoreet. Quisque rutrum. Aenean imperdiet. Etiam ultricies nisi vel augue. Curabitur ullamcorper ultricies nisi.</p>
</Container>
)
export default ContainerExampleText
|
ajax/libs/intl-tel-input/3.8.5/js/intlTelInput.js | BenjaminVanRyseghem/cdnjs | /*
International Telephone Input v3.8.5
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: false,
// 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,
// make the dropdown the same width as the input
responsiveDropdown: 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;
}
// auto enable responsiveDropdown mode on small screens (dropdown is currently set to 430px in CSS)
if (window.innerWidth < 500) {
this.options.responsiveDropdown = true;
}
// 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": "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");
// and set the width
if (this.options.responsiveDropdown) {
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='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", "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(".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 E164
getCleanNumber: function() {
if (window.intlTelInputUtils) {
return intlTelInputUtils.formatNumberE164(this.telInput.val(), this.selectedCountryData.iso2);
}
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;
};
// set the country data object
$.fn[pluginName].setCountryData = function(obj) {
allCountries = obj;
};
// 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", "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
};
}
}); |
examples/exoskeleton/node_modules/exoskeleton/exoskeleton.js | nitish1125/todomvc | /*!
* Exoskeleton.js 0.7.0
* (c) 2013 Paul Miller <http://paulmillr.com>
* Based on Backbone.js
* (c) 2010-2013 Jeremy Ashkenas, DocumentCloud
* Exoskeleton may be freely distributed under the MIT license.
* For all details and documentation: <http://exosjs.com>
*/
(function(root, factory) {
// Set up Backbone appropriately for the environment.
if (typeof define === 'function' && define.amd) {
define(['underscore', 'jquery', 'exports'], function(_, $, exports) {
root.Backbone = root.Exoskeleton = factory(root, exports, _, $);
});
} else if (typeof exports !== 'undefined') {
var _, $;
try { _ = require('underscore'); } catch(e) { }
try { $ = require('jquery'); } catch(e) { }
factory(root, exports, _, $);
} else {
root.Backbone = root.Exoskeleton = factory(root, {}, root._, (root.jQuery || root.Zepto || root.ender || root.$));
}
})(this, function(root, Backbone, _, $) {
'use strict';
// Initial Setup
// -------------
// Save the previous value of the `Backbone` variable, so that it can be
// restored later on, if `noConflict` is used.
var previousBackbone = root.Backbone;
var previousExoskeleton = root.Exoskeleton;
// Underscore replacement.
var utils = Backbone.utils = _ = (_ || {});
// Hold onto a local reference to `$`. Can be changed at any point.
Backbone.$ = $;
// Create local references to array methods we'll want to use later.
var array = [];
var push = array.push;
var slice = array.slice;
var toString = ({}).toString;
// Current version of the library. Keep in sync with `package.json`.
// Backbone.VERSION = '1.0.0';
// Runs Backbone.js in *noConflict* mode, returning the `Backbone` variable
// to its previous owner. Returns a reference to this Backbone object.
Backbone.noConflict = function() {
root.Backbone = previousBackbone;
root.Exoskeleton = previousExoskeleton;
return this;
};
// Helpers
// -------
// Helper function to correctly set up the prototype chain, for subclasses.
// Similar to `goog.inherits`, but uses a hash of prototype properties and
// class properties to be extended.
Backbone.extend = function(protoProps, staticProps) {
var parent = this;
var child;
// The constructor function for the new subclass is either defined by you
// (the "constructor" property in your `extend` definition), or defaulted
// by us to simply call the parent's constructor.
if (protoProps && _.has(protoProps, 'constructor')) {
child = protoProps.constructor;
} else {
child = function(){ return parent.apply(this, arguments); };
}
// Add static properties to the constructor function, if supplied.
_.extend(child, parent, staticProps);
// Set the prototype chain to inherit from `parent`, without calling
// `parent`'s constructor function.
var Surrogate = function(){ this.constructor = child; };
Surrogate.prototype = parent.prototype;
child.prototype = new Surrogate;
// Add prototype properties (instance properties) to the subclass,
// if supplied.
if (protoProps) _.extend(child.prototype, protoProps);
// Set a convenience property in case the parent's prototype is needed
// later.
child.__super__ = parent.prototype;
return child;
};
// Throw an error when a URL is needed, and none is supplied.
var urlError = function() {
throw new Error('A "url" property or function must be specified');
};
// Wrap an optional error callback with a fallback error event.
var wrapError = function(model, options) {
var error = options.error;
options.error = function(resp) {
if (error) error(model, resp, options);
model.trigger('error', model, resp, options);
};
};
// Checker for utility methods. Useful for custom builds.
var utilExists = function(method) {
return typeof _[method] === 'function';
};
utils.result = function result(object, property) {
var value = object ? object[property] : undefined;
return typeof value === 'function' ? object[property]() : value;
};
utils.defaults = function defaults(obj) {
slice.call(arguments, 1).forEach(function(item) {
for (var key in item) if (obj[key] === undefined)
obj[key] = item[key];
});
return obj;
};
utils.extend = function extend(obj) {
slice.call(arguments, 1).forEach(function(item) {
for (var key in item) obj[key] = item[key];
});
return obj;
};
var htmlEscapes = {
'&': '&',
'<': '<',
'>': '>',
'"': '"',
"'": '''
};
utils.escape = function escape(string) {
return string == null ? '' : String(string).replace(/[&<>"']/g, function(match) {
return htmlEscapes[match];
});
};
utils.sortBy = function(obj, value, context) {
var iterator = typeof value === 'function' ? value : function(obj){ return obj[value]; };
return obj
.map(function(value, index, list) {
return {
value: value,
index: index,
criteria: iterator.call(context, value, index, list)
};
})
.sort(function(left, right) {
var a = left.criteria;
var b = right.criteria;
if (a !== b) {
if (a > b || a === void 0) return 1;
if (a < b || b === void 0) return -1;
}
return left.index - right.index;
})
.map(function(item) {
return item.value;
});
};
/** Used to generate unique IDs */
var idCounter = 0;
utils.uniqueId = function uniqueId(prefix) {
var id = ++idCounter + '';
return prefix ? prefix + id : id;
};
utils.has = function(obj, key) {
return Object.hasOwnProperty.call(obj, key);
};
var eq = function(a, b, aStack, bStack) {
// Identical objects are equal. `0 === -0`, but they aren't identical.
// See the [Harmony `egal` proposal](http://wiki.ecmascript.org/doku.php?id=harmony:egal).
if (a === b) return a !== 0 || 1 / a == 1 / b;
// A strict comparison is necessary because `null == undefined`.
if (a == null || b == null) return a === b;
// Unwrap any wrapped objects.
//if (a instanceof _) a = a._wrapped;
//if (b instanceof _) b = b._wrapped;
// Compare `[[Class]]` names.
var className = toString.call(a);
if (className != toString.call(b)) return false;
switch (className) {
// Strings, numbers, dates, and booleans are compared by value.
case '[object String]':
// Primitives and their corresponding object wrappers are equivalent; thus, `"5"` is
// equivalent to `new String("5")`.
return a == String(b);
case '[object Number]':
// `NaN`s are equivalent, but non-reflexive. An `egal` comparison is performed for
// other numeric values.
return a !== +a ? b !== +b : (a === 0 ? 1 / a === 1 / b : a === +b);
case '[object Date]':
case '[object Boolean]':
// Coerce dates and booleans to numeric primitive values. Dates are compared by their
// millisecond representations. Note that invalid dates with millisecond representations
// of `NaN` are not equivalent.
return +a == +b;
// RegExps are compared by their source patterns and flags.
case '[object RegExp]':
return a.source == b.source &&
a.global == b.global &&
a.multiline == b.multiline &&
a.ignoreCase == b.ignoreCase;
}
if (typeof a != 'object' || typeof b != 'object') return false;
// Assume equality for cyclic structures. The algorithm for detecting cyclic
// structures is adapted from ES 5.1 section 15.12.3, abstract operation `JO`.
var length = aStack.length;
while (length--) {
// Linear search. Performance is inversely proportional to the number of
// unique nested structures.
if (aStack[length] == a) return bStack[length] == b;
}
// Objects with different constructors are not equivalent, but `Object`s
// from different frames are.
var aCtor = a.constructor, bCtor = b.constructor;
if (aCtor !== bCtor && !(typeof aCtor === 'function' && (aCtor instanceof aCtor) &&
typeof bCtor === 'function' && (bCtor instanceof bCtor))) {
return false;
}
// Add the first object to the stack of traversed objects.
aStack.push(a);
bStack.push(b);
var size = 0, result = true;
// Recursively compare objects and arrays.
if (className === '[object Array]') {
// Compare array lengths to determine if a deep comparison is necessary.
size = a.length;
result = size === b.length;
if (result) {
// Deep compare the contents, ignoring non-numeric properties.
while (size--) {
if (!(result = eq(a[size], b[size], aStack, bStack))) break;
}
}
} else {
// Deep compare objects.
for (var key in a) {
if (_.has(a, key)) {
// Count the expected number of properties.
size++;
// Deep compare each member.
if (!(result = _.has(b, key) && eq(a[key], b[key], aStack, bStack))) break;
}
}
// Ensure that both objects contain the same number of properties.
if (result) {
for (key in b) {
if (_.has(b, key) && !(size--)) break;
}
result = !size;
}
}
// Remove the first object from the stack of traversed objects.
aStack.pop();
bStack.pop();
return result;
};
// Perform a deep comparison to check if two objects are equal.
utils.isEqual = function(a, b) {
return eq(a, b, [], []);
};
// Backbone.Events
// ---------------
// A module that can be mixed in to *any object* in order to provide it with
// custom events. You may bind with `on` or remove with `off` callback
// functions to an event; `trigger`-ing an event fires all callbacks in
// succession.
//
// var object = {};
// _.extend(object, Backbone.Events);
// object.on('expand', function(){ alert('expanded'); });
// object.trigger('expand');
//
var Events = Backbone.Events = {
// Bind an event to a `callback` function. Passing `"all"` will bind
// the callback to all events fired.
on: function(name, callback, context) {
if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this;
this._events || (this._events = {});
var events = this._events[name] || (this._events[name] = []);
events.push({callback: callback, context: context, ctx: context || this});
return this;
},
// Bind an event to only be triggered a single time. After the first time
// the callback is invoked, it will be removed.
once: function(name, callback, context) {
if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this;
var self = this;
var ran;
var once = function() {
if (ran) return;
ran = true;
self.off(name, once);
callback.apply(this, arguments);
};
once._callback = callback;
return this.on(name, once, context);
},
// Remove one or many callbacks. If `context` is null, removes all
// callbacks with that function. If `callback` is null, removes all
// callbacks for the event. If `name` is null, removes all bound
// callbacks for all events.
off: function(name, callback, context) {
var retain, ev, events, names, i, l, j, k;
if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this;
if (!name && !callback && !context) {
this._events = void 0;
return this;
}
names = name ? [name] : Object.keys(this._events);
for (i = 0, l = names.length; i < l; i++) {
name = names[i];
if (events = this._events[name]) {
this._events[name] = retain = [];
if (callback || context) {
for (j = 0, k = events.length; j < k; j++) {
ev = events[j];
if ((callback && callback !== ev.callback && callback !== ev.callback._callback) ||
(context && context !== ev.context)) {
retain.push(ev);
}
}
}
if (!retain.length) delete this._events[name];
}
}
return this;
},
// Trigger one or many events, firing all bound callbacks. Callbacks are
// passed the same arguments as `trigger` is, apart from the event name
// (unless you're listening on `"all"`, which will cause your callback to
// receive the true name of the event as the first argument).
trigger: function(name) {
if (!this._events) return this;
var args = slice.call(arguments, 1);
if (!eventsApi(this, 'trigger', name, args)) return this;
var events = this._events[name];
var allEvents = this._events.all;
if (events) triggerEvents(events, args);
if (allEvents) triggerEvents(allEvents, arguments);
return this;
},
// Tell this object to stop listening to either specific events ... or
// to every object it's currently listening to.
stopListening: function(obj, name, callback) {
var listeningTo = this._listeningTo;
if (!listeningTo) return this;
var remove = !name && !callback;
if (!callback && typeof name === 'object') callback = this;
if (obj) (listeningTo = {})[obj._listenId] = obj;
for (var id in listeningTo) {
obj = listeningTo[id];
obj.off(name, callback, this);
if (remove || !Object.keys(obj._events).length) delete this._listeningTo[id];
}
return this;
}
};
// Regular expression used to split event strings.
var eventSplitter = /\s+/;
// Implement fancy features of the Events API such as multiple event
// names `"change blur"` and jQuery-style event maps `{change: action}`
// in terms of the existing API.
var eventsApi = function(obj, action, name, rest) {
if (!name) return true;
// Handle event maps.
if (typeof name === 'object') {
for (var key in name) {
obj[action].apply(obj, [key, name[key]].concat(rest));
}
return false;
}
// Handle space separated event names.
if (eventSplitter.test(name)) {
var names = name.split(eventSplitter);
for (var i = 0, l = names.length; i < l; i++) {
obj[action].apply(obj, [names[i]].concat(rest));
}
return false;
}
return true;
};
// A difficult-to-believe, but optimized internal dispatch function for
// triggering events. Tries to keep the usual cases speedy (most internal
// Backbone events have 3 arguments).
var triggerEvents = function(events, args) {
var ev, i = -1, l = events.length, a1 = args[0], a2 = args[1], a3 = args[2];
switch (args.length) {
case 0: while (++i < l) (ev = events[i]).callback.call(ev.ctx); return;
case 1: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1); return;
case 2: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2); return;
case 3: while (++i < l) (ev = events[i]).callback.call(ev.ctx, a1, a2, a3); return;
default: while (++i < l) (ev = events[i]).callback.apply(ev.ctx, args); return;
}
};
var listenMethods = {listenTo: 'on', listenToOnce: 'once'};
// Inversion-of-control versions of `on` and `once`. Tell *this* object to
// listen to an event in another object ... keeping track of what it's
// listening to.
Object.keys(listenMethods).forEach(function(method) {
var implementation = listenMethods[method];
Events[method] = function(obj, name, callback) {
var listeningTo = this._listeningTo || (this._listeningTo = {});
var id = obj._listenId || (obj._listenId = _.uniqueId('l'));
listeningTo[id] = obj;
if (!callback && typeof name === 'object') callback = this;
obj[implementation](name, callback, this);
return this;
};
});
// Aliases for backwards compatibility.
Events.bind = Events.on;
Events.unbind = Events.off;
// Allow the `Backbone` object to serve as a global event bus, for folks who
// want global "pubsub" in a convenient place.
_.extend(Backbone, Events);
// Backbone.Model
// --------------
// Backbone **Models** are the basic data object in the framework --
// frequently representing a row in a table in a database on your server.
// A discrete chunk of data and a bunch of useful, related methods for
// performing computations and transformations on that data.
// Create a new model with the specified attributes. A client id (`cid`)
// is automatically generated and assigned for you.
var Model = Backbone.Model = function(attributes, options) {
var attrs = attributes || {};
options || (options = {});
this.cid = _.uniqueId('c');
this.attributes = Object.create(null);
if (options.collection) this.collection = options.collection;
if (options.parse) attrs = this.parse(attrs, options) || {};
attrs = _.defaults({}, attrs, _.result(this, 'defaults'));
this.set(attrs, options);
this.changed = Object.create(null);
this.initialize.apply(this, arguments);
};
// Attach all inheritable methods to the Model prototype.
_.extend(Model.prototype, Events, {
// A hash of attributes whose current and previous value differ.
changed: null,
// The value returned during the last failed validation.
validationError: null,
// The default name for the JSON `id` attribute is `"id"`. MongoDB and
// CouchDB users may want to set this to `"_id"`.
idAttribute: 'id',
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize: function(){},
// Return a copy of the model's `attributes` object.
toJSON: function(options) {
return _.extend({}, this.attributes);
},
// Proxy `Backbone.sync` by default -- but override this if you need
// custom syncing semantics for *this* particular model.
sync: function() {
return Backbone.sync.apply(this, arguments);
},
// Get the value of an attribute.
get: function(attr) {
return this.attributes[attr];
},
// Get the HTML-escaped value of an attribute.
escape: function(attr) {
return _.escape(this.get(attr));
},
// Returns `true` if the attribute contains a value that is not null
// or undefined.
has: function(attr) {
return this.get(attr) != null;
},
// Set a hash of model attributes on the object, firing `"change"`. This is
// the core primitive operation of a model, updating the data and notifying
// anyone who needs to know about the change in state. The heart of the beast.
set: function(key, val, options) {
var attr, attrs, unset, changes, silent, changing, prev, current;
if (key == null) return this;
// Handle both `"key", value` and `{key: value}` -style arguments.
if (typeof key === 'object') {
attrs = key;
options = val;
} else {
(attrs = {})[key] = val;
}
options || (options = {});
// Run validation.
if (!this._validate(attrs, options)) return false;
// Extract attributes and options.
unset = options.unset;
silent = options.silent;
changes = [];
changing = this._changing;
this._changing = true;
if (!changing) {
this._previousAttributes = _.extend(Object.create(null), this.attributes);
this.changed = {};
}
current = this.attributes, prev = this._previousAttributes;
// Check for changes of `id`.
if (this.idAttribute in attrs) this.id = attrs[this.idAttribute];
// For each `set` attribute, update or delete the current value.
for (attr in attrs) {
val = attrs[attr];
if (!_.isEqual(current[attr], val)) changes.push(attr);
if (!_.isEqual(prev[attr], val)) {
this.changed[attr] = val;
} else {
delete this.changed[attr];
}
unset ? delete current[attr] : current[attr] = val;
}
// Trigger all relevant attribute changes.
if (!silent) {
if (changes.length) this._pending = options;
for (var i = 0, l = changes.length; i < l; i++) {
this.trigger('change:' + changes[i], this, current[changes[i]], options);
}
}
// You might be wondering why there's a `while` loop here. Changes can
// be recursively nested within `"change"` events.
if (changing) return this;
if (!silent) {
while (this._pending) {
options = this._pending;
this._pending = false;
this.trigger('change', this, options);
}
}
this._pending = false;
this._changing = false;
return this;
},
// Remove an attribute from the model, firing `"change"`. `unset` is a noop
// if the attribute doesn't exist.
unset: function(attr, options) {
return this.set(attr, void 0, _.extend({}, options, {unset: true}));
},
// Clear all attributes on the model, firing `"change"`.
clear: function(options) {
var attrs = {};
for (var key in this.attributes) attrs[key] = void 0;
return this.set(attrs, _.extend({}, options, {unset: true}));
},
// Determine if the model has changed since the last `"change"` event.
// If you specify an attribute name, determine if that attribute has changed.
hasChanged: function(attr) {
if (attr == null) return !!Object.keys(this.changed).length;
return _.has(this.changed, attr);
},
// Return an object containing all the attributes that have changed, or
// false if there are no changed attributes. Useful for determining what
// parts of a view need to be updated and/or what attributes need to be
// persisted to the server. Unset attributes will be set to undefined.
// You can also pass an attributes object to diff against the model,
// determining if there *would be* a change.
changedAttributes: function(diff) {
if (!diff) return this.hasChanged() ? _.extend(Object.create(null), this.changed) : false;
var val, changed = false;
var old = this._changing ? this._previousAttributes : this.attributes;
for (var attr in diff) {
if (_.isEqual(old[attr], (val = diff[attr]))) continue;
(changed || (changed = {}))[attr] = val;
}
return changed;
},
// Get the previous value of an attribute, recorded at the time the last
// `"change"` event was fired.
previous: function(attr) {
if (attr == null || !this._previousAttributes) return null;
return this._previousAttributes[attr];
},
// Get all of the attributes of the model at the time of the previous
// `"change"` event.
previousAttributes: function() {
return _.extend(Object.create(null), this._previousAttributes);
},
// Fetch the model from the server. If the server's representation of the
// model differs from its current attributes, they will be overridden,
// triggering a `"change"` event.
fetch: function(options) {
options = options ? _.extend({}, options) : {};
if (options.parse === void 0) options.parse = true;
var model = this;
var success = options.success;
options.success = function(resp) {
if (!model.set(model.parse(resp, options), options)) return false;
if (success) success(model, resp, options);
model.trigger('sync', model, resp, options);
};
wrapError(this, options);
return this.sync('read', this, options);
},
// Set a hash of model attributes, and sync the model to the server.
// If the server returns an attributes hash that differs, the model's
// state will be `set` again.
save: function(key, val, options) {
var attrs, method, xhr, attributes = this.attributes;
// Handle both `"key", value` and `{key: value}` -style arguments.
if (key == null || typeof key === 'object') {
attrs = key;
options = val;
} else {
(attrs = {})[key] = val;
}
options = _.extend({validate: true}, options);
// If we're not waiting and attributes exist, save acts as
// `set(attr).save(null, opts)` with validation. Otherwise, check if
// the model will be valid when the attributes, if any, are set.
if (attrs && !options.wait) {
if (!this.set(attrs, options)) return false;
} else {
if (!this._validate(attrs, options)) return false;
}
// Set temporary attributes if `{wait: true}`.
if (attrs && options.wait) {
this.attributes = _.extend(Object.create(null), attributes, attrs);
}
// After a successful server-side save, the client is (optionally)
// updated with the server-side state.
if (options.parse === void 0) options.parse = true;
var model = this;
var success = options.success;
options.success = function(resp) {
// Ensure attributes are restored during synchronous saves.
model.attributes = attributes;
var serverAttrs = model.parse(resp, options);
if (options.wait) serverAttrs = _.extend(attrs || {}, serverAttrs);
if (serverAttrs && typeof serverAttrs === 'object' && !model.set(serverAttrs, options)) {
return false;
}
if (success) success(model, resp, options);
model.trigger('sync', model, resp, options);
};
wrapError(this, options);
method = this.isNew() ? 'create' : (options.patch ? 'patch' : 'update');
if (method === 'patch') options.attrs = attrs;
xhr = this.sync(method, this, options);
// Restore attributes.
if (attrs && options.wait) this.attributes = attributes;
return xhr;
},
// Destroy this model on the server if it was already persisted.
// Optimistically removes the model from its collection, if it has one.
// If `wait: true` is passed, waits for the server to respond before removal.
destroy: function(options) {
options = options ? _.extend({}, options) : {};
var model = this;
var success = options.success;
var destroy = function() {
model.trigger('destroy', model, model.collection, options);
};
options.success = function(resp) {
if (options.wait || model.isNew()) destroy();
if (success) success(model, resp, options);
if (!model.isNew()) model.trigger('sync', model, resp, options);
};
if (this.isNew()) {
options.success();
return false;
}
wrapError(this, options);
var xhr = this.sync('delete', this, options);
if (!options.wait) destroy();
return xhr;
},
// Default URL for the model's representation on the server -- if you're
// using Backbone's restful methods, override this to change the endpoint
// that will be called.
url: function() {
var base =
_.result(this, 'urlRoot') ||
_.result(this.collection, 'url') ||
urlError();
if (this.isNew()) return base;
return base.replace(/([^\/])$/, '$1/') + encodeURIComponent(this.id);
},
// **parse** converts a response into the hash of attributes to be `set` on
// the model. The default implementation is just to pass the response along.
parse: function(resp, options) {
return resp;
},
// Create a new model with identical attributes to this one.
clone: function() {
return new this.constructor(this.attributes);
},
// A model is new if it has never been saved to the server, and lacks an id.
isNew: function() {
return !this.has(this.idAttribute);
},
// Check if the model is currently in a valid state.
isValid: function(options) {
return this._validate({}, _.extend(options || {}, { validate: true }));
},
// Run validation against the next complete set of model attributes,
// returning `true` if all is well. Otherwise, fire an `"invalid"` event.
_validate: function(attrs, options) {
if (!options.validate || !this.validate) return true;
attrs = _.extend(Object.create(null), this.attributes, attrs);
var error = this.validationError = this.validate(attrs, options) || null;
if (!error) return true;
this.trigger('invalid', this, error, _.extend(options, {validationError: error}));
return false;
}
});
if (_.keys) {
// Underscore methods that we want to implement on the Model.
var modelMethods = ['keys', 'values', 'pairs', 'invert', 'pick', 'omit'];
// Mix in each Underscore method as a proxy to `Model#attributes`.
modelMethods.filter(utilExists).forEach(function(method) {
Model.prototype[method] = function() {
var args = slice.call(arguments);
args.unshift(this.attributes);
return _[method].apply(_, args);
};
});
}
// Backbone.Collection
// -------------------
// If models tend to represent a single row of data, a Backbone Collection is
// more analagous to a table full of data ... or a small slice or page of that
// table, or a collection of rows that belong together for a particular reason
// -- all of the messages in this particular folder, all of the documents
// belonging to this particular author, and so on. Collections maintain
// indexes of their models, both in order, and for lookup by `id`.
// Create a new **Collection**, perhaps to contain a specific type of `model`.
// If a `comparator` is specified, the Collection will maintain
// its models in sort order, as they're added and removed.
var Collection = Backbone.Collection = function(models, options) {
options || (options = {});
if (options.model) this.model = options.model;
if (options.comparator !== void 0) this.comparator = options.comparator;
this._reset();
this.initialize.apply(this, arguments);
if (models) this.reset(models, _.extend({silent: true}, options));
};
// Default options for `Collection#set`.
var setOptions = {add: true, remove: true, merge: true};
var addOptions = {add: true, remove: false};
// Define the Collection's inheritable methods.
_.extend(Collection.prototype, Events, {
// The default model for a collection is just a **Backbone.Model**.
// This should be overridden in most cases.
model: typeof Model === 'undefined' ? null : Model,
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize: function(){},
// The JSON representation of a Collection is an array of the
// models' attributes.
toJSON: function(options) {
return this.map(function(model){ return model.toJSON(options); });
},
// Proxy `Backbone.sync` by default.
sync: function() {
return Backbone.sync.apply(this, arguments);
},
// Add a model, or list of models to the set.
add: function(models, options) {
return this.set(models, _.extend({merge: false}, options, addOptions));
},
// Remove a model, or a list of models from the set.
remove: function(models, options) {
var singular = !Array.isArray(models);
models = singular ? [models] : models.slice();
options || (options = {});
var i, l, index, model;
for (i = 0, l = models.length; i < l; i++) {
model = models[i] = this.get(models[i]);
if (!model) continue;
delete this._byId[model.id];
delete this._byId[model.cid];
index = this.indexOf(model);
this.models.splice(index, 1);
this.length--;
if (!options.silent) {
options.index = index;
model.trigger('remove', model, this, options);
}
this._removeReference(model, options);
}
return singular ? models[0] : models;
},
// Update a collection by `set`-ing a new list of models, adding new ones,
// removing models that are no longer present, and merging models that
// already exist in the collection, as necessary. Similar to **Model#set**,
// the core operation for updating the data contained by the collection.
set: function(models, options) {
options = _.defaults({}, options, setOptions);
if (options.parse) models = this.parse(models, options);
var singular = !Array.isArray(models);
models = singular ? (models ? [models] : []) : models.slice();
var i, l, id, model, attrs, existing, sort;
var at = options.at;
var targetModel = this.model;
var sortable = this.comparator && (at == null) && options.sort !== false;
var sortAttr = typeof this.comparator === 'string' ? this.comparator : null;
var toAdd = [], toRemove = [], modelMap = {};
var add = options.add, merge = options.merge, remove = options.remove;
var order = !sortable && add && remove ? [] : false;
// Turn bare objects into model references, and prevent invalid models
// from being added.
for (i = 0, l = models.length; i < l; i++) {
attrs = models[i] || {};
if (attrs instanceof Model) {
id = model = attrs;
} else {
id = attrs[targetModel.prototype.idAttribute || 'id'];
}
// If a duplicate is found, prevent it from being added and
// optionally merge it into the existing model.
if (existing = this.get(id)) {
if (remove) modelMap[existing.cid] = true;
if (merge) {
attrs = attrs === model ? model.attributes : attrs;
if (options.parse) attrs = existing.parse(attrs, options);
existing.set(attrs, options);
if (sortable && !sort && existing.hasChanged(sortAttr)) sort = true;
}
models[i] = existing;
// If this is a new, valid model, push it to the `toAdd` list.
} else if (add) {
model = models[i] = this._prepareModel(attrs, options);
if (!model) continue;
toAdd.push(model);
this._addReference(model, options);
}
// Do not add multiple models with the same `id`.
model = existing || model;
if (order && (model.isNew() || !modelMap[model.id])) order.push(model);
modelMap[model.id] = true;
}
// Remove nonexistent models if appropriate.
if (remove) {
for (i = 0, l = this.length; i < l; ++i) {
if (!modelMap[(model = this.models[i]).cid]) toRemove.push(model);
}
if (toRemove.length) this.remove(toRemove, options);
}
// See if sorting is needed, update `length` and splice in new models.
if (toAdd.length || (order && order.length)) {
if (sortable) sort = true;
this.length += toAdd.length;
if (at != null) {
for (i = 0, l = toAdd.length; i < l; i++) {
this.models.splice(at + i, 0, toAdd[i]);
}
} else {
if (order) this.models.length = 0;
var orderedModels = order || toAdd;
for (i = 0, l = orderedModels.length; i < l; i++) {
this.models.push(orderedModels[i]);
}
}
}
// Silently sort the collection if appropriate.
if (sort) this.sort({silent: true});
// Unless silenced, it's time to fire all appropriate add/sort events.
if (!options.silent) {
for (i = 0, l = toAdd.length; i < l; i++) {
(model = toAdd[i]).trigger('add', model, this, options);
}
if (sort || (order && order.length)) this.trigger('sort', this, options);
}
// Return the added (or merged) model (or models).
return singular ? models[0] : models;
},
// When you have more items than you want to add or remove individually,
// you can reset the entire set with a new list of models, without firing
// any granular `add` or `remove` events. Fires `reset` when finished.
// Useful for bulk operations and optimizations.
reset: function(models, options) {
options || (options = {});
for (var i = 0, l = this.models.length; i < l; i++) {
this._removeReference(this.models[i], options);
}
options.previousModels = this.models;
this._reset();
models = this.add(models, _.extend({silent: true}, options));
if (!options.silent) this.trigger('reset', this, options);
return models;
},
// Add a model to the end of the collection.
push: function(model, options) {
return this.add(model, _.extend({at: this.length}, options));
},
// Remove a model from the end of the collection.
pop: function(options) {
var model = this.at(this.length - 1);
this.remove(model, options);
return model;
},
// Add a model to the beginning of the collection.
unshift: function(model, options) {
return this.add(model, _.extend({at: 0}, options));
},
// Remove a model from the beginning of the collection.
shift: function(options) {
var model = this.at(0);
this.remove(model, options);
return model;
},
// Slice out a sub-array of models from the collection.
slice: function() {
return slice.apply(this.models, arguments);
},
// Get a model from the set by id.
get: function(obj) {
if (obj == null) return void 0;
return this._byId[obj] || this._byId[obj.id] || this._byId[obj.cid];
},
// Get the model at the given index.
at: function(index) {
return this.models[index];
},
// Return models with matching attributes. Useful for simple cases of
// `filter`.
where: function(attrs, first) {
if (!attrs || !Object.keys(attrs).length) return first ? void 0 : [];
return this[first ? 'find' : 'filter'](function(model) {
for (var key in attrs) {
if (attrs[key] !== model.get(key)) return false;
}
return true;
});
},
// Return the first model with matching attributes. Useful for simple cases
// of `find`.
findWhere: function(attrs) {
return this.where(attrs, true);
},
// Force the collection to re-sort itself. You don't need to call this under
// normal circumstances, as the set will maintain sort order as each item
// is added.
sort: function(options) {
if (!this.comparator) throw new Error('Cannot sort a set without a comparator');
options || (options = {});
// Run sort based on type of `comparator`.
if (typeof this.comparator === 'string' || this.comparator.length === 1) {
this.models = this.sortBy(this.comparator, this);
} else {
this.models.sort(this.comparator.bind(this));
}
if (!options.silent) this.trigger('sort', this, options);
return this;
},
// Pluck an attribute from each model in the collection.
pluck: function(attr) {
return this.models.map(function(model) {
return model.get(attr);
});
},
// Fetch the default set of models for this collection, resetting the
// collection when they arrive. If `reset: true` is passed, the response
// data will be passed through the `reset` method instead of `set`.
fetch: function(options) {
options = options ? _.extend({}, options) : {};
if (options.parse === void 0) options.parse = true;
var success = options.success;
var collection = this;
options.success = function(resp) {
var method = options.reset ? 'reset' : 'set';
collection[method](resp, options);
if (success) success(collection, resp, options);
collection.trigger('sync', collection, resp, options);
};
wrapError(this, options);
return this.sync('read', this, options);
},
// Create a new instance of a model in this collection. Add the model to the
// collection immediately, unless `wait: true` is passed, in which case we
// wait for the server to agree.
create: function(model, options) {
options = options ? _.extend({}, options) : {};
if (!(model = this._prepareModel(model, options))) return false;
if (!options.wait) this.add(model, options);
var collection = this;
var success = options.success;
options.success = function(model, resp) {
if (options.wait) collection.add(model, options);
if (success) success(model, resp, options);
};
model.save(null, options);
return model;
},
// **parse** converts a response into a list of models to be added to the
// collection. The default implementation is just to pass it through.
parse: function(resp, options) {
return resp;
},
// Create a new collection with an identical list of models as this one.
clone: function() {
return new this.constructor(this.models);
},
// Private method to reset all internal state. Called when the collection
// is first initialized or reset.
_reset: function() {
this.length = 0;
this.models = [];
this._byId = Object.create(null);
},
// Prepare a hash of attributes (or other model) to be added to this
// collection.
_prepareModel: function(attrs, options) {
if (attrs instanceof Model) return attrs;
options = _.extend({}, options);
options.collection = this;
var model = new this.model(attrs, options);
if (!model.validationError) return model;
this.trigger('invalid', this, model.validationError, options);
return false;
},
// Internal method to create a model's ties to a collection.
_addReference: function(model, options) {
this._byId[model.cid] = model;
if (model.id != null) this._byId[model.id] = model;
if (!model.collection) model.collection = this;
model.on('all', this._onModelEvent, this);
},
// Internal method to sever a model's ties to a collection.
_removeReference: function(model, options) {
if (this === model.collection) delete model.collection;
model.off('all', this._onModelEvent, this);
},
// Internal method called every time a model in the set fires an event.
// Sets need to update their indexes when models change ids. All other
// events simply proxy through. "add" and "remove" events that originate
// in other collections are ignored.
_onModelEvent: function(event, model, collection, options) {
if ((event === 'add' || event === 'remove') && collection !== this) return;
if (event === 'destroy') this.remove(model, options);
if (model && event === 'change:' + model.idAttribute) {
delete this._byId[model.previous(model.idAttribute)];
if (model.id != null) this._byId[model.id] = model;
}
this.trigger.apply(this, arguments);
}
});
if (utilExists('each')) {
// Underscore methods that we want to implement on the Collection.
// 90% of the core usefulness of Backbone Collections is actually implemented
// right here:
var methods = ['forEach', 'each', 'map', 'collect', 'reduce', 'foldl',
'inject', 'reduceRight', 'foldr', 'find', 'detect', 'filter', 'select',
'reject', 'every', 'all', 'some', 'any', 'include', 'contains', 'invoke',
'max', 'min', 'toArray', 'size', 'first', 'head', 'take', 'initial', 'rest',
'tail', 'drop', 'last', 'without', 'difference', 'indexOf', 'shuffle',
'lastIndexOf', 'isEmpty', 'chain'];
// Mix in each Underscore method as a proxy to `Collection#models`.
methods.filter(utilExists).forEach(function(method) {
Collection.prototype[method] = function() {
var args = slice.call(arguments);
args.unshift(this.models);
return _[method].apply(_, args);
};
});
// Underscore methods that take a property name as an argument.
var attributeMethods = ['groupBy', 'countBy', 'sortBy'];
// Use attributes instead of properties.
attributeMethods.filter(utilExists).forEach(function(method) {
Collection.prototype[method] = function(value, context) {
var iterator = typeof value === 'function' ? value : function(model) {
return model.get(value);
};
return _[method](this.models, iterator, context);
};
});
} else {
['forEach', 'map', 'filter', 'some', 'every', 'reduce', 'reduceRight',
'indexOf', 'lastIndexOf'].forEach(function(method) {
Collection.prototype[method] = function(arg, context) {
return this.models[method](arg, context);
};
});
// Exoskeleton-specific:
Collection.prototype.find = function(iterator, context) {
var result;
this.some(function(value, index, list) {
if (iterator.call(context, value, index, list)) {
result = value;
return true;
}
});
return result;
};
// Underscore methods that take a property name as an argument.
['sortBy'].forEach(function(method) {
Collection.prototype[method] = function(value, context) {
var iterator = typeof value === 'function' ? value : function(model) {
return model.get(value);
};
return _[method](this.models, iterator, context);
};
});
}
// Backbone.View
// -------------
// Backbone Views are almost more convention than they are actual code. A View
// is simply a JavaScript object that represents a logical chunk of UI in the
// DOM. This might be a single item, an entire list, a sidebar or panel, or
// even the surrounding frame which wraps your whole app. Defining a chunk of
// UI as a **View** allows you to define your DOM events declaratively, without
// having to worry about render order ... and makes it easy for the view to
// react to specific changes in the state of your models.
// Creating a Backbone.View creates its initial element outside of the DOM,
// if an existing element is not provided...
var View = Backbone.View = function(options) {
this.cid = _.uniqueId('view');
if (options) Object.keys(options).forEach(function(key) {
if (viewOptions.indexOf(key) !== -1) this[key] = options[key];
}, this);
this._ensureElement();
this.initialize.apply(this, arguments);
};
// Cached regex to split keys for `delegate`.
var delegateEventSplitter = /^(\S+)\s*(.*)$/;
// List of view options to be merged as properties.
var viewOptions = ['model', 'collection', 'el', 'id', 'attributes', 'className', 'tagName', 'events'];
// Set up all inheritable **Backbone.View** properties and methods.
_.extend(View.prototype, Events, {
// The default `tagName` of a View's element is `"div"`.
tagName: 'div',
// jQuery delegate for element lookup, scoped to DOM elements within the
// current view. This should be preferred to global lookups where possible.
$: function(selector) {
return this.$el.find(selector);
},
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize: function(){},
// **render** is the core function that your view should override, in order
// to populate its element (`this.el`), with the appropriate HTML. The
// convention is for **render** to always return `this`.
render: function() {
return this;
},
// Remove this view by taking the element out of the DOM, and removing any
// applicable Backbone.Events listeners.
remove: function() {
this._removeElement();
this.stopListening();
return this;
},
// Remove this view's element from the document and all event listeners
// attached to it. Exposed for subclasses using an alternative DOM
// manipulation API.
_removeElement: function() {
this.$el.remove();
},
// Change the view's element (`this.el` property) and re-delegate the
// view's events on the new element.
setElement: function(element) {
this.undelegateEvents();
this._setElement(element);
this.delegateEvents();
return this;
},
// Creates the `this.el` and `this.$el` references for this view using the
// given `el` and a hash of `attributes`. `el` can be a CSS selector or an
// HTML string, a jQuery context or an element. Subclasses can override
// this to utilize an alternative DOM manipulation API and are only required
// to set the `this.el` property.
_setElement: function(el) {
if (!Backbone.$) throw new Error('You must either include jQuery or override Backbone.View.prototype methods (Google Backbone.NativeView)');
this.$el = el instanceof Backbone.$ ? el : Backbone.$(el);
this.el = this.$el[0];
},
// Set callbacks, where `this.events` is a hash of
//
// *{"event selector": "callback"}*
//
// {
// 'mousedown .title': 'edit',
// 'click .button': 'save',
// 'click .open': function(e) { ... }
// }
//
// pairs. Callbacks will be bound to the view, with `this` set properly.
// Uses event delegation for efficiency.
// Omitting the selector binds the event to `this.el`.
delegateEvents: function(events) {
if (!(events || (events = _.result(this, 'events')))) return this;
this.undelegateEvents();
for (var key in events) {
var method = events[key];
if (typeof method !== 'function') method = this[events[key]];
// if (!method) continue;
var match = key.match(delegateEventSplitter);
this.delegate(match[1], match[2], method.bind(this));
}
return this;
},
// Add a single event listener to the view's element (or a child element
// using `selector`). This only works for delegate-able events: not `focus`,
// `blur`, and not `change`, `submit`, and `reset` in Internet Explorer.
delegate: function(eventName, selector, listener) {
this.$el.on(eventName + '.delegateEvents' + this.cid, selector, listener);
},
// Clears all callbacks previously bound to the view by `delegateEvents`.
// You usually don't need to use this, but may wish to if you have multiple
// Backbone views attached to the same DOM element.
undelegateEvents: function() {
if (this.$el) this.$el.off('.delegateEvents' + this.cid);
return this;
},
// A finer-grained `undelegateEvents` for removing a single delegated event.
// `selector` and `listener` are both optional.
undelegate: function(eventName, selector, listener) {
this.$el.off(eventName + '.delegateEvents' + this.cid, selector, listener);
},
// Produces a DOM element to be assigned to your view. Exposed for
// subclasses using an alternative DOM manipulation API.
_createElement: function(tagName) {
return document.createElement(tagName);
},
// Ensure that the View has a DOM element to render into.
// If `this.el` is a string, pass it through `$()`, take the first
// matching element, and re-assign it to `el`. Otherwise, create
// an element from the `id`, `className` and `tagName` properties.
_ensureElement: function() {
if (!this.el) {
var attrs = _.extend({}, _.result(this, 'attributes'));
if (this.id) attrs.id = _.result(this, 'id');
if (this.className) attrs['class'] = _.result(this, 'className');
this.setElement(this._createElement(_.result(this, 'tagName')));
this._setAttributes(attrs);
} else {
this.setElement(_.result(this, 'el'));
}
},
// Set attributes from a hash on this view's element. Exposed for
// subclasses using an alternative DOM manipulation API.
_setAttributes: function(attributes) {
this.$el.attr(attributes);
}
});
// Backbone.sync
// -------------
// Override this function to change the manner in which Backbone persists
// models to the server. You will be passed the type of request, and the
// model in question. By default, makes a RESTful Ajax request
// to the model's `url()`. Some possible customizations could be:
//
// * Use `setTimeout` to batch rapid-fire updates into a single request.
// * Send up the models as XML instead of JSON.
// * Persist models via WebSockets instead of Ajax.
Backbone.sync = function(method, model, options) {
options || (options = {})
var type = methodMap[method];
// Default JSON-request options.
var params = {type: type, dataType: 'json'};
// Ensure that we have a URL.
if (!options.url) {
params.url = _.result(model, 'url') || urlError();
}
// Ensure that we have the appropriate request data.
if (options.data == null && model && (method === 'create' || method === 'update' || method === 'patch')) {
params.contentType = 'application/json';
params.data = JSON.stringify(options.attrs || model.toJSON(options));
}
// Don't process data on a non-GET request.
if (params.type !== 'GET') {
params.processData = false;
}
// Make the request, allowing the user to override any Ajax options.
var xhr = options.xhr = Backbone.ajax(_.extend(params, options));
model.trigger('request', model, xhr, options);
return xhr;
};
// Map from CRUD to HTTP for our default `Backbone.sync` implementation.
var methodMap = {
'create': 'POST',
'update': 'PUT',
'patch': 'PATCH',
'delete': 'DELETE',
'read': 'GET'
};
// Set the default implementation of `Backbone.ajax` to proxy through to `$`.
// Override this if you'd like to use a different library.
Backbone.ajax = function() {
if (!Backbone.$) throw new Error('You must either include jQuery or override Backbone.ajax (Google Backbone.NativeAjax)');
return Backbone.$.ajax.apply(Backbone.$, arguments);
};
// Backbone.Router
// ---------------
// Routers map faux-URLs to actions, and fire events when routes are
// matched. Creating a new one sets its `routes` hash, if not set statically.
var Router = Backbone.Router = function(options) {
options || (options = {});
if (options.routes) this.routes = options.routes;
this._bindRoutes();
this.initialize.apply(this, arguments);
};
// Cached regular expressions for matching named param parts and splatted
// parts of route strings.
var optionalParam = /\((.*?)\)/g;
var namedParam = /(\(\?)?:\w+/g;
var splatParam = /\*\w+/g;
var escapeRegExp = /[\-{}\[\]+?.,\\\^$|#\s]/g;
var isRegExp = function(value) {
return value ? (typeof value === 'object' && toString.call(value) === '[object RegExp]') : false;
};
// Set up all inheritable **Backbone.Router** properties and methods.
_.extend(Router.prototype, Events, {
// Initialize is an empty function by default. Override it with your own
// initialization logic.
initialize: function(){},
// Manually bind a single named route to a callback. For example:
//
// this.route('search/:query/p:num', 'search', function(query, num) {
// ...
// });
//
route: function(route, name, callback) {
if (!isRegExp(route)) route = this._routeToRegExp(route);
if (typeof name === 'function') {
callback = name;
name = '';
}
if (!callback) callback = this[name];
var router = this;
Backbone.history.route(route, function(fragment) {
var args = router._extractParameters(route, fragment);
router.execute(callback, args);
router.trigger.apply(router, ['route:' + name].concat(args));
router.trigger('route', name, args);
Backbone.history.trigger('route', router, name, args);
});
return this;
},
// Execute a route handler with the provided parameters. This is an
// excellent place to do pre-route setup or post-route cleanup.
execute: function(callback, args) {
if (callback) callback.apply(this, args);
},
// Simple proxy to `Backbone.history` to save a fragment into the history.
navigate: function(fragment, options) {
Backbone.history.navigate(fragment, options);
return this;
},
// Bind all defined routes to `Backbone.history`. We have to reverse the
// order of the routes here to support behavior where the most general
// routes can be defined at the bottom of the route map.
_bindRoutes: function() {
if (!this.routes) return;
this.routes = _.result(this, 'routes');
var route, routes = Object.keys(this.routes);
while ((route = routes.pop()) != null) {
this.route(route, this.routes[route]);
}
},
// Convert a route string into a regular expression, suitable for matching
// against the current location hash.
_routeToRegExp: function(route) {
route = route.replace(escapeRegExp, '\\$&')
.replace(optionalParam, '(?:$1)?')
.replace(namedParam, function(match, optional) {
return optional ? match : '([^/?]+)';
})
.replace(splatParam, '([^?]*?)');
return new RegExp('^' + route + '(?:\\?([\\s\\S]*))?$');
},
// Given a route, and a URL fragment that it matches, return the array of
// extracted decoded parameters. Empty or unmatched parameters will be
// treated as `null` to normalize cross-browser behavior.
_extractParameters: function(route, fragment) {
var params = route.exec(fragment).slice(1);
return params.map(function(param, i) {
// Don't decode the search params.
if (i === params.length - 1) return param || null;
return param ? decodeURIComponent(param) : null;
});
}
});
// Backbone.History
// ----------------
// Handles cross-browser history management, based on either
// [pushState](http://diveintohtml5.info/history.html) and real URLs, or
// [onhashchange](https://developer.mozilla.org/en-US/docs/DOM/window.onhashchange)
// and URL fragments.
var History = Backbone.History = function() {
this.handlers = [];
this.checkUrl = this.checkUrl.bind(this);
// Ensure that `History` can be used outside of the browser.
if (typeof window !== 'undefined') {
this.location = window.location;
this.history = window.history;
}
};
// Cached regex for stripping a leading hash/slash and trailing space.
var routeStripper = /^[#\/]|\s+$/g;
// Cached regex for stripping leading and trailing slashes.
var rootStripper = /^\/+|\/+$/g;
// Cached regex for removing a trailing slash.
var trailingSlash = /\/$/;
// Cached regex for stripping urls of hash and query.
var pathStripper = /[#].*$/;
// Has the history handling already been started?
History.started = false;
// Set up all inheritable **Backbone.History** properties and methods.
_.extend(History.prototype, Events, {
// Are we at the app root?
atRoot: function() {
return this.location.pathname.replace(/[^\/]$/, '$&/') === this.root;
},
// Gets the true hash value. Cannot use location.hash directly due to bug
// in Firefox where location.hash will always be decoded.
getHash: function(window) {
var match = (window || this).location.href.match(/#(.*)$/);
return match ? match[1] : '';
},
// Get the cross-browser normalized URL fragment, either from the URL,
// the hash, or the override.
getFragment: function(fragment, forcePushState) {
if (fragment == null) {
if (this._wantsPushState || !this._wantsHashChange) {
fragment = decodeURI(this.location.pathname + this.location.search);
var root = this.root.replace(trailingSlash, '');
if (!fragment.indexOf(root)) fragment = fragment.slice(root.length);
} else {
fragment = this.getHash();
}
}
return fragment.replace(routeStripper, '');
},
// Start the hash change handling, returning `true` if the current URL matches
// an existing route, and `false` otherwise.
start: function(options) {
if (History.started) throw new Error("Backbone.history has already been started");
History.started = true;
// Figure out the initial configuration.
// Is pushState desired or should we use hashchange only?
this.options = _.extend({root: '/'}, this.options, options);
this.root = this.options.root;
this._wantsHashChange = this.options.hashChange !== false;
this._wantsPushState = !!this.options.pushState;
var fragment = this.getFragment();
// Normalize root to always include a leading and trailing slash.
this.root = ('/' + this.root + '/').replace(rootStripper, '/');
// Depending on whether we're using pushState or hashes, determine how we
// check the URL state.
if (this._wantsPushState) {
window.addEventListener('popstate', this.checkUrl, false);
} else if (this._wantsHashChange) {
window.addEventListener('hashchange', this.checkUrl, false);
}
// Determine if we need to change the base url, for a pushState link
// opened by a non-pushState browser.
this.fragment = fragment;
var loc = this.location;
// Transition from hashChange to pushState or vice versa if both are
// requested.
if (this._wantsHashChange && this._wantsPushState) {
// If we've started out with a hash-based route, but we're currently
// in a browser where it could be `pushState`-based instead...
if (this.atRoot() && loc.hash) {
this.fragment = this.getHash().replace(routeStripper, '');
this.history.replaceState({}, document.title, this.root + this.fragment);
}
}
if (!this.options.silent) return this.loadUrl();
},
// Disable Backbone.history, perhaps temporarily. Not useful in a real app,
// but possibly useful for unit testing Routers.
stop: function() {
window.removeEventListener('popstate', this.checkUrl);
window.removeEventListener('hashchange', this.checkUrl);
History.started = false;
},
// Add a route to be tested when the fragment changes. Routes added later
// may override previous routes.
route: function(route, callback) {
this.handlers.unshift({route: route, callback: callback});
},
// Checks the current URL to see if it has changed, and if it has,
// calls `loadUrl`.
checkUrl: function() {
var current = this.getFragment();
if (current === this.fragment) return false;
this.loadUrl();
},
// Attempt to load the current URL fragment. If a route succeeds with a
// match, returns `true`. If no defined routes matches the fragment,
// returns `false`.
loadUrl: function(fragment) {
fragment = this.fragment = this.getFragment(fragment);
return this.handlers.some(function(handler) {
if (handler.route.test(fragment)) {
handler.callback(fragment);
return true;
}
});
},
// Save a fragment into the hash history, or replace the URL state if the
// 'replace' option is passed. You are responsible for properly URL-encoding
// the fragment in advance.
//
// The options object can contain `trigger: true` if you wish to have the
// route callback be fired (not usually desirable), or `replace: true`, if
// you wish to modify the current URL without adding an entry to the history.
navigate: function(fragment, options) {
if (!History.started) return false;
if (!options || options === true) options = {trigger: !!options};
var url = this.root + (fragment = this.getFragment(fragment || ''));
// Strip the hash for matching.
fragment = fragment.replace(pathStripper, '');
if (this.fragment === fragment) return;
this.fragment = fragment;
// Don't include a trailing slash on the root.
if (fragment === '' && url !== '/') url = url.slice(0, -1);
// If we're using pushState we use it to set the fragment as a real URL.
if (this._wantsPushState) {
this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url);
// If hash changes haven't been explicitly disabled, update the hash
// fragment to store history.
} else if (this._wantsHashChange) {
this._updateHash(this.location, fragment, options.replace);
// If you've told us that you explicitly don't want fallback hashchange-
// based history, then `navigate` becomes a page refresh.
} else {
return this.location.assign(url);
}
if (options.trigger) return this.loadUrl(fragment);
},
// Update the hash location, either replacing the current entry, or adding
// a new one to the browser history.
_updateHash: function(location, fragment, replace) {
if (replace) {
var href = location.href.replace(/(javascript:|#).*$/, '');
location.replace(href + '#' + fragment);
} else {
// Some browsers require that `hash` contains a leading #.
location.hash = '#' + fragment;
}
}
});
// !!!
// Init.
['Model', 'Collection', 'Router', 'View', 'History'].forEach(function(name) {
var item = Backbone[name];
if (item) item.extend = Backbone.extend;
});
// Allow the `Backbone` object to serve as a global event bus, for folks who
// want global "pubsub" in a convenient place.
_.extend(Backbone, Events);
// Create the default Backbone.history if the History module is included.
if (History) Backbone.history = new History();
return Backbone;
});
|
app/javascript/mastodon/features/generic_not_found/index.js | nonoz/mastodon | import React from 'react';
import Column from '../ui/components/column';
import MissingIndicator from '../../components/missing_indicator';
const GenericNotFound = () => (
<Column>
<MissingIndicator />
</Column>
);
export default GenericNotFound;
|
app/jsx/due_dates/DueDateAddRowButton.js | djbender/canvas-lms | /*
* Copyright (C) 2015 - present Instructure, Inc.
*
* This file is part of Canvas.
*
* Canvas is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License as published by the Free
* Software Foundation, version 3 of the License.
*
* Canvas is distributed in the hope that it will be useful, but WITHOUT ANY
* WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
* A PARTICULAR PURPOSE. See the GNU Affero General Public License for more
* details.
*
* You should have received a copy of the GNU Affero General Public License along
* with this program. If not, see <http://www.gnu.org/licenses/>.
*/
import React from 'react'
import PropTypes from 'prop-types'
import I18n from 'i18n!assignDueDateAddRowButtonments'
class DueDateAddRowButton extends React.Component {
static propTypes = {
display: PropTypes.bool.isRequired
}
render() {
if (!this.props.display) {
return null
}
return (
<button
id="add_due_date"
ref="addButton"
className="Button Button--add-row"
onClick={this.props.handleAdd}
type="button"
>
<i className="icon-plus" role="presentation" />
<span className="screenreader-only">{I18n.t('Add new set of due dates')}</span>
<span aria-hidden="true"> {I18n.t('Add')}</span>
</button>
)
}
}
export default DueDateAddRowButton
|
ajax/libs/material-ui/4.9.3/esm/NativeSelect/NativeSelect.js | cdnjs/cdnjs | import _extends from "@babel/runtime/helpers/esm/extends";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
import React from 'react';
import PropTypes from 'prop-types';
import NativeSelectInput from './NativeSelectInput';
import withStyles from '../styles/withStyles';
import formControlState from '../FormControl/formControlState';
import useFormControl from '../FormControl/useFormControl';
import ArrowDropDownIcon from '../internal/svg-icons/ArrowDropDown';
import Input from '../Input';
export var styles = function styles(theme) {
return {
/* Styles applied to the select component `root` class. */
root: {},
/* Styles applied to the select component `select` class. */
select: {
'-moz-appearance': 'none',
// Reset
'-webkit-appearance': 'none',
// Reset
// When interacting quickly, the text can end up selected.
// Native select can't be selected either.
userSelect: 'none',
borderRadius: 0,
// Reset
minWidth: 16,
// So it doesn't collapse.
cursor: 'pointer',
'&:focus': {
// Show that it's not an text input
backgroundColor: theme.palette.type === 'light' ? 'rgba(0, 0, 0, 0.05)' : 'rgba(255, 255, 255, 0.05)',
borderRadius: 0 // Reset Chrome style
},
// Remove IE 11 arrow
'&::-ms-expand': {
display: 'none'
},
'&$disabled': {
cursor: 'default'
},
'&[multiple]': {
height: 'auto'
},
'&:not([multiple]) option, &:not([multiple]) optgroup': {
backgroundColor: theme.palette.background.paper
},
'&&': {
paddingRight: 24
}
},
/* Styles applied to the select component if `variant="filled"`. */
filled: {
'&&': {
paddingRight: 32
}
},
/* Styles applied to the select component if `variant="outlined"`. */
outlined: {
borderRadius: theme.shape.borderRadius,
'&&': {
paddingRight: 32
}
},
/* Styles applied to the select component `selectMenu` class. */
selectMenu: {
height: 'auto',
// Reset
textOverflow: 'ellipsis',
whiteSpace: 'nowrap',
overflow: 'hidden'
},
/* Pseudo-class applied to the select component `disabled` class. */
disabled: {},
/* Styles applied to the icon component. */
icon: {
// We use a position absolute over a flexbox in order to forward the pointer events
// to the input and to support wrapping tags..
position: 'absolute',
right: 0,
top: 'calc(50% - 12px)',
// Center vertically
color: theme.palette.action.active,
pointerEvents: 'none' // Don't block pointer events on the select under the icon.
},
/* Styles applied to the icon component if the popup is open. */
iconOpen: {
transform: 'rotate(180deg)'
},
/* Styles applied to the icon component if `variant="filled"`. */
iconFilled: {
right: 7
},
/* Styles applied to the icon component if `variant="outlined"`. */
iconOutlined: {
right: 7
}
};
};
var defaultInput = React.createElement(Input, null);
/**
* An alternative to `<Select native />` with a much smaller bundle size footprint.
*/
var NativeSelect = React.forwardRef(function NativeSelect(props, ref) {
var children = props.children,
classes = props.classes,
_props$IconComponent = props.IconComponent,
IconComponent = _props$IconComponent === void 0 ? ArrowDropDownIcon : _props$IconComponent,
_props$input = props.input,
input = _props$input === void 0 ? defaultInput : _props$input,
inputProps = props.inputProps,
variant = props.variant,
other = _objectWithoutProperties(props, ["children", "classes", "IconComponent", "input", "inputProps", "variant"]);
var muiFormControl = useFormControl();
var fcs = formControlState({
props: props,
muiFormControl: muiFormControl,
states: ['variant']
});
return React.cloneElement(input, _extends({
// Most of the logic is implemented in `NativeSelectInput`.
// The `Select` component is a simple API wrapper to expose something better to play with.
inputComponent: NativeSelectInput,
inputProps: _extends({
children: children,
classes: classes,
IconComponent: IconComponent,
variant: fcs.variant,
type: undefined
}, inputProps, {}, input ? input.props.inputProps : {}),
ref: ref
}, other));
});
process.env.NODE_ENV !== "production" ? NativeSelect.propTypes = {
/**
* The option elements to populate the select with.
* Can be some `<option>` elements.
*/
children: PropTypes.node,
/**
* Override or extend the styles applied to the component.
* See [CSS API](#css) below for more details.
*/
classes: PropTypes.object.isRequired,
/**
* The icon that displays the arrow.
*/
IconComponent: PropTypes.elementType,
/**
* An `Input` element; does not have to be a material-ui specific `Input`.
*/
input: PropTypes.element,
/**
* Attributes applied to the `select` element.
*/
inputProps: PropTypes.object,
/**
* Callback function fired when a menu item is selected.
*
* @param {object} event The event source of the callback.
* You can pull out the new value by accessing `event.target.value` (string).
*/
onChange: PropTypes.func,
/**
* The input value. The DOM API casts this to a string.
*/
value: PropTypes.any,
/**
* The variant to use.
*/
variant: PropTypes.oneOf(['standard', 'outlined', 'filled'])
} : void 0;
NativeSelect.muiName = 'Select';
export default withStyles(styles, {
name: 'MuiNativeSelect'
})(NativeSelect); |
packages/material-ui-icons/src/DoneOutline.js | Kagami/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><path d="M19.77 5.03l1.4 1.4L8.43 19.17l-5.6-5.6 1.4-1.4 4.2 4.2L19.77 5.03m0-2.83L8.43 13.54l-4.2-4.2L0 13.57 8.43 22 24 6.43 19.77 2.2z" /></React.Fragment>
, 'DoneOutline');
|
packages/material-ui-icons/src/TabletMacSharp.js | allanalexandre/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><path fill="none" d="M0 0h24v24H0V0z" /><g><path d="M21 0H2v24h19V0zm-9.5 23c-.83 0-1.5-.67-1.5-1.5s.67-1.5 1.5-1.5 1.5.67 1.5 1.5-.67 1.5-1.5 1.5zm7.5-4H4V3h15v16z" /></g></React.Fragment>
, 'TabletMacSharp');
|
ajax/libs/6to5/2.4.1/browser.js | jackdoyle/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 start=storeCurrentPos();var node=startNode();next();node.object={type:"ThisExpression"};node.property=parseSubscripts(parseIdent(),start);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")&&(tokType!=_comma&&tokType!=_braceR)){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)checkLVal(node.superClass);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.transformers=this.getTransformers();this.uids={};this.ast={}}File.declarations=["inherits","prototype-properties","apply-constructor","tagged-template-literal","interop-require","to-array","sliced-to-array","object-without-properties","has-own","slice","define-property","async-to-generator"];File.excludeDeclarationsFromRuntime=["async-to-generator"];File.normaliseOptions=function(opts){opts=_.cloneDeep(opts||{});_.defaults(opts,{experimental:false,playground:false,whitespace:true,moduleIds:opts.amdModuleIds||false,blacklist:[],whitelist:[],sourceMap:false,optional:[],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);transform._ensureTransformerNames("optional",opts.optional);return opts};File.prototype.getTransformers=function(){var file=this;var transformers=[];_.each(transform.transformers,function(transformer){if(transformer.canRun(file)){transformers.push(transformer);if(transformer.manipulateOptions){transformer.manipulateOptions(file.opts,file)}}});return transformers};File.prototype.toArray=function(node,i){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{var declarationName="to-array";var args=[node];if(i){args.push(t.literal(i));declarationName="sliced-to-array"}return t.callExpression(this.addDeclaration(declarationName),args)}};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.addImport=function(id,source){var specifiers=[t.importSpecifier(t.identifier("default"),id)];var declar=t.importDeclaration(specifiers,t.literal(source));this.ast.program.body.unshift(declar)};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&&!_.contains(File.excludeDeclarationsFromRuntime,name)){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){var self=this;this.ast=ast;this.scope=new Scope(ast.program);this.moduleFormatter=this.getModuleFormatter(this.opts.modules);var astRun=function(key){_.each(self.transformers,function(transformer){transformer.astRun(self,key)})};astRun("enter");_.each(this.transformers,function(transformer){transformer.transform(self)});astRun("exit")};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":73,"./types":76,"./util":78,lodash:126}],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":78,lodash:126}],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]){var needsCommentParens=t.isExpression(node)&&node.leadingComments&&node.leadingComments.length;var needsParens=needsCommentParens||n.needsParens(node,parent);if(needsParens)this.push("(");if(needsCommentParens)this.indent();this.printLeadingComments(node,parent);newline(true);if(opts.before)opts.before();this.map.mark(node,"start");this[node.type](node,this.buildPrint(node),parent);if(needsCommentParens){this.newline();this.dedent()}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 of type "+JSON.stringify(node.type)+" with constructor "+JSON.stringify(node&&node.constructor.name))}};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":76,"../util":78,"./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:126}],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":76,"../../util":78}],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":76,lodash:126}],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":76}],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":76,lodash:126}],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:126}],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.newline();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":76}],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:126}],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:126}],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":76,"./parentheses":19,"./whitespace":20,lodash:126}],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":76,lodash:126}],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,ArrayExpression:{after:1},ObjectExpression:{after: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":76,lodash:126}],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:126}],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":76,"source-map":168}],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:126}],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":76,"ast-types":92,estraverse:120,lodash:126}],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 name=node.name;return t.isIdentifier(node)&&localExports[name]&&localExports[name]===scope.get(name,true)};traverse(this.file.ast,{enter:function(node,parent,scope){if(t.isUpdateExpression(node)&&isLocalReference(node.argument,scope)){this.stop();var assign=t.assignmentExpression(node.operator[0]+"=",node.argument,t.literal(1));var remapped=self.remapExportAssignment(assign);if(t.isExpressionStatement(parent)||node.prefix){return remapped}var nodes=[];nodes.push(remapped);var operator;if(node.operator==="--"){operator="+"}else{operator="-"}nodes.push(t.binaryExpression(operator,node.argument,t.literal(1)));return t.sequenceExpression(nodes)}if(t.isAssignmentExpression(node)&&isLocalReference(node.left,scope)){this.stop();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,priority){if(t.isFunctionDeclaration(declar)){assign._blockHoist=priority||2}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(),node))}else{nodes.push(this._exportsAssign(t.getSpecifierName(specifier),t.memberExpression(getRef(),specifier.id),node))}}else{nodes.push(this._exportsAssign(t.getSpecifierName(specifier),specifier.id,node))}};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;var id=declar.id;if(node.default){id=t.identifier("default")}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,node).expression;var newDeclar=t.variableDeclaration(declar.kind,[decl]);if(i==="0")t.inherits(newDeclar,declar);nodes.push(newDeclar)}}else{var ref=declar;if(t.isFunctionDeclaration(declar)||t.isClassDeclaration(declar)){ref=declar.id;nodes.push(declar)}assign=this._exportsAssign(id,ref,node);nodes.push(assign);this._hoistExport(declar,assign)}}},{"../../traverse":72,"../../types":76,"../../util":78,lodash:126}],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(){DefaultFormatter.apply(this,arguments);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.moduleIds){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)&&!this.noInteropRequire){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":76,"../../util":78,"./_default":25,lodash:126}],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 assign;var templateName="exports-default-module";if(this.hasNonDefaultExports)templateName="exports-default-module-override";if(t.isFunction(declar)||!this.hasNonDefaultExports){assign=util.template(templateName,{VALUE:this._pushStatement(declar,nodes)},true);nodes.push(this._hoistExport(declar,assign,3));return}else{assign=util.template("common-export-default-assign",true);assign._blockHoist=0;nodes.push(assign)}}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":72,"../../types":76,"../../util":78,"./_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":76}],29:[function(require,module,exports){module.exports=SystemFormatter;var AMDFormatter=require("./amd");var traverse=require("../../traverse");var util=require("../../util");var t=require("../../types");var _=require("lodash");function SystemFormatter(file){this.exportIdentifier=file.generateUidIdentifier("export");this.noInteropRequire=true;AMDFormatter.apply(this,arguments)}util.inherits(SystemFormatter,AMDFormatter);SystemFormatter.prototype._addImportSource=function(node,exportNode){node._importSource=exportNode.source&&exportNode.source.value;return node};SystemFormatter.prototype._exportsWildcard=function(objectIdentifier,node){var leftIdentifier=this.file.generateUidIdentifier("key");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 this._addImportSource(t.forInStatement(left,right,block),node)};SystemFormatter.prototype._exportsAssign=function(id,init,node){var call=this.buildExportCall(t.literal(id.name),init,true);return this._addImportSource(call,node)};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.importSpecifier=function(specifier,node,nodes){AMDFormatter.prototype.importSpecifier.apply(this,arguments);this._addImportSource(_.last(nodes),node)};SystemFormatter.prototype.buildRunnerSetters=function(block,hoistDeclarators){return t.arrayExpression(_.map(this.ids,function(uid,source){var nodes=[];traverse(block,{enter:function(node){if(node._importSource===source){if(t.isVariableDeclaration(node)){_.each(node.declarations,function(declar){hoistDeclarators.push(t.variableDeclarator(declar.id));nodes.push(t.expressionStatement(t.assignmentExpression("=",declar.id,declar.init)))})}else{nodes.push(node)}this.remove()}}});return t.functionExpression(null,[uid],t.blockStatement(nodes))}))};SystemFormatter.prototype.transform=function(ast){var program=ast.program;var hoistDeclarators=[];var moduleName=this.getModuleName();var moduleNameLiteral=t.literal(moduleName);var block=t.blockStatement(program.body);var runner=util.template("system",{MODULE_NAME:moduleNameLiteral,MODULE_DEPENDENCIES:t.arrayExpression(this.buildDependencyLiterals()),EXPORT_IDENTIFIER:this.exportIdentifier,SETTERS:this.buildRunnerSetters(block,hoistDeclarators),EXECUTE:t.functionExpression(null,[],block)},true);var handlerBody=runner.expression.arguments[2].body.body;if(!moduleName)runner.expression.arguments.shift();var returnStatement=handlerBody.pop();traverse(block,{enter:function(node,parent,scope){if(t.isFunction(node)){return this.stop()}if(t.isVariableDeclaration(node)){if(node.kind!=="var"&&!t.isProgram(parent)){return}var nodes=[];_.each(node.declarations,function(declar){hoistDeclarators.push(t.variableDeclarator(declar.id));if(declar.init){var assign=t.expressionStatement(t.assignmentExpression("=",declar.id,declar.init));nodes.push(assign)}});if(t.isFor(parent)){if(parent.left===node){return node.declarations[0].id}if(parent.init===node){return t.toSequenceExpression(nodes,scope)}}return nodes}}});if(hoistDeclarators.length){var hoistDeclar=t.variableDeclaration("var",hoistDeclarators);hoistDeclar._blockHoist=true;handlerBody.unshift(hoistDeclar)}traverse(block,{enter:function(node){if(t.isFunction(node))this.stop();if(t.isFunctionDeclaration(node)||node._blockHoist){handlerBody.push(node);this.remove()}}});handlerBody.push(returnStatement);program.body=[runner]}},{"../../traverse":72,"../../types":76,"../../util":78,"./amd":26,lodash:126}],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":76,"../../util":78,"./amd":26,lodash:126}],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"),asyncToGenerator:require("./transformers/optional-async-to-generator"),bluebirdCoroutines:require("./transformers/optional-bluebird-coroutines"),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"),coreAliasing:require("./transformers/optional-core-aliasing"),undefinedToVoid:require("./transformers/optional-undefined-to-void"),_aliasFunctions:require("./transformers/_alias-functions"),_moduleFormatter:require("./transformers/_module-formatter"),useStrict:require("./transformers/use-strict"),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":78,"./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/optional-async-to-generator":58,"./transformers/optional-bluebird-coroutines":59,"./transformers/optional-core-aliasing":60,"./transformers/optional-undefined-to-void":61,"./transformers/playground-memoization-operator":62,"./transformers/playground-method-binding":63,"./transformers/playground-object-getter-memoization":64,"./transformers/react":65,"./transformers/spec-block-hoist-functions":66,"./transformers/spec-member-expression-literals":67,"./transformers/spec-no-duplicate-properties":68,"./transformers/spec-no-for-in-of-assignment":69,"./transformers/spec-property-literals":70,"./transformers/use-strict":71,lodash:126}],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.manipulateOptions=transformer.manipulateOptions;this.experimental=!!transformer.experimental;this.transformer=Transformer.normalise(transformer);this.optional=!!transformer.optional;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};if(!_.isObject(fns))return;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){var transformer=this.transformer;var ast=file.ast;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)}};this.astRun(file,"before");traverse(ast,{enter:build(),exit:build(true)});this.astRun(file,"after")};Transformer.prototype.canRun=function(file){var opts=file.opts;var key=this.key;if(key[0]==="_")return true;var blacklist=opts.blacklist;if(blacklist.length&&_.contains(blacklist,key))return false;var whitelist=opts.whitelist;if(whitelist.length&&!_.contains(whitelist,key))return false;if(this.optional&&!_.contains(opts.optional,key))return false;if(this.experimental&&!opts.experimental)return false;return true}},{"../traverse":72,"../types":76,lodash:126}],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 this.stop()}else{return}}traverse(node,{enter:function(node,parent){if(t.isFunction(node)&&!node._aliasFunction){return this.stop()}if(node._ignoreAliasFunctions)return this.stop();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 this.stop()}});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":72,"../../types":76}],34:[function(require,module,exports){var _=require("lodash");exports.BlockStatement=exports.Program={exit:function(node){var hasChange=false;for(var i in node.body){var bodyNode=node.body[i];if(bodyNode&&bodyNode._blockHoist!=null)hasChange=true}if(!hasChange)return;var nodePriorities=_.groupBy(node.body,function(bodyNode){var priority=bodyNode._blockHoist;if(priority==null)priority=1;if(priority===true)priority=2;return priority});node.body=_.flatten(_.values(nodePriorities).reverse())}}},{lodash:126}],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":76}],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;if(node.properties.length){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)})})}else{return util.template("object-define-properties",{OBJECT:node,PROPS:util.buildDefineProperties(mutatorMap)})}}},{"../../util":78}],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":76}],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 factory=new Class(node,file,scope,closure);var newNode=factory.run();if(factory.closure){if(closure){scope.push({kind:"var",key:node.id.key,id:node.id});return t.assignmentExpression("=",node.id,newNode)}else{return t.variableDeclaration("let",[t.variableDeclarator(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){this.closure=true;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;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&&!t.isFalsyExpression(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":72,"../../types":76,"../../util":78}],40:[function(require,module,exports){var util=require("../../util");var t=require("../../types");exports.ObjectExpression=function(node,parent,file){var hasComputed=false;var prop;var key;var i;for(i in node.properties){hasComputed=t.isProperty(node.properties[i],{computed:true});if(hasComputed)break}if(!hasComputed)return;var objId=util.getUid(parent,file);var body=[];var container=t.functionExpression(null,[],t.blockStatement(body));container._aliasFunction=true;var props=node.properties;for(i in props){prop=props[i];key=prop.key;if(!prop.computed&&t.isIdentifier(key)){prop.key=t.literal(key.name)}}var initProps=[];var broken=false;for(i in props){prop=props[i];if(prop.computed){broken=true}if(!broken||t.isLiteral(prop.key,{value:"__proto__"})){initProps.push(prop);props[i]=null}}for(i in props){prop=props[i];if(!prop)continue;key=prop.key;var bodyNode;if(prop.computed&&t.isMemberExpression(key)&&t.isIdentifier(key.object,{name:"Symbol"})){bodyNode=t.assignmentExpression("=",t.memberExpression(objId,key,true),prop.value)}else{bodyNode=t.callExpression(file.addDeclaration("define-property"),[objId,key,prop.value])}body.push(t.expressionStatement(bodyNode))}if(body.length===1){var first=body[0].expression;if(t.isCallExpression(first)){first.arguments[0]=t.objectExpression([]);return first}}body.unshift(t.variableDeclaration("var",[t.variableDeclarator(objId,t.objectExpression(initProps))]));body.push(t.returnStatement(objId));return t.callExpression(container,[])}},{"../../types":76,"../../util":78}],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":72,"../../types":76,lodash:126}],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":72,"../../types":76,"../../util":78,lodash:126}],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){if(!pattern.elements)return;var i;var hasSpreadElement=false;for(i in pattern.elements){if(t.isSpreadElement(pattern.elements[i])){hasSpreadElement=true;break}}var toArray=opts.file.toArray(parentId,!hasSpreadElement&&pattern.elements.length);var _parentId=opts.file.generateUidIdentifier("ref",opts.scope);nodes.push(t.variableDeclaration("var",[t.variableDeclarator(_parentId,toArray)]));parentId=_parentId;for(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)){declar=null;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":76}],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.inheritsComments(node2,node);t.ensureBlock(node);var block=node2.body;block.body.push(declar);block.body=block.body.concat(node.body.body);return node2}},{"../../types":76,"../../util":78}],45:[function(require,module,exports){exports.ast={before:require("regenerator").transform}},{regenerator:134}],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 this.stop()}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 this.stop()}}})};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 this.stop()}else if(t.isLoop(node)){return this.stop()}}});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":72,"../../types":76,"../../util":78,lodash:126}],47:[function(require,module,exports){var t=require("../../types");exports.ImportDeclaration=function(node,parent,file){var nodes=[];if(node.specifiers.length){for(var i in node.specifiers){file.moduleFormatter.importSpecifier(node.specifiers[i],node,nodes,parent)}}else{file.moduleFormatter.importDeclaration(node,nodes,parent)}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")}file.moduleFormatter.exportDeclaration(node,nodes,parent)}else{for(var i in node.specifiers){file.moduleFormatter.exportSpecifier(node.specifiers[i],node,nodes,parent)}}return nodes}},{"../../types":76}],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":76,lodash:126}],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":76}],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":76}],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":76}],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:126,"regexpu/rewrite-pattern":167}],53:[function(require,module,exports){var util=require("../../util");var t=require("../../types");exports.experimental=true;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":76,"../../util":78}],54:[function(require,module,exports){var traverse=require("../../traverse");var util=require("../../util");var t=require("../../types");exports.experimental=true;var build=function(node,file){var uid=file.generateUidIdentifier("arr");var container=util.template("array-comprehension-container",{KEY:uid});container.callee._aliasFunction=true;var block=container.callee.body;var body=block.body;if(traverse.hasType(node,"YieldExpression",t.FUNCTION_TYPES)){container.callee.generator=true;container=t.yieldExpression(container,true)}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;return build(node,file)}},{"../../traverse":72,"../../types":76,"../../util":78}],55:[function(require,module,exports){exports.experimental=true;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":76}],56:[function(require,module,exports){var arrayComprehension=require("./es7-array-comprehension");var t=require("../../types");exports.experimental=true;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":76,"./es7-array-comprehension":54}],57:[function(require,module,exports){var t=require("../../types");exports.experimental=true;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":76}],58:[function(require,module,exports){var bluebirdCoroutines=require("./optional-bluebird-coroutines");var t=require("../../types");exports.optional=true;exports.manipulateOptions=bluebirdCoroutines.manipulateOptions;exports.Function=function(node,parent,file){if(!node.async||node.generator)return;bluebirdCoroutines._Function(node);return t.callExpression(file.addDeclaration("async-to-generator"),[node])}},{"../../types":76,"./optional-bluebird-coroutines":59}],59:[function(require,module,exports){var traverse=require("../../traverse");var t=require("../../types");exports.manipulateOptions=function(opts){opts.experimental=true;opts.blacklist.push("generators")};exports.optional=true;exports._Function=function(node){node.async=false;node.generator=true;traverse(node,{enter:function(node){if(t.isFunction(node))this.stop();if(t.isAwaitExpression(node)){node.type="YieldExpression"}}})};exports.Function=function(node,parent,file){if(!node.async||node.generator)return;exports._Function(node);var id=t.identifier("Bluebird");file.addImport(id,"bluebird");return t.callExpression(t.memberExpression(id,t.identifier("coroutine")),[node])}},{"../../traverse":72,"../../types":76}],60:[function(require,module,exports){var traverse=require("../../traverse");var util=require("../../util");var core=require("core-js/library");var t=require("../../types");var _=require("lodash");exports.optional=true;exports.ast={enter:function(ast,file){file._coreId=file.generateUidIdentifier("core");file.addImport(file._coreId,"core-js/library")},exit:function(ast,file){traverse(ast,{enter:function(node,parent){var prop;if(t.isMemberExpression(node)&&t.isReferenced(node,parent)){var obj=node.object;prop=node.property;if(!t.isReferenced(obj,node))return;var coreHasObject=obj.name!=="_"&&_.has(core,obj.name);if(coreHasObject&&_.has(core[obj.name],prop.name)){this.stop();return t.memberExpression(file._coreId,node)}}else if(t.isCallExpression(node)){if(node.arguments.length)return;var callee=node.callee;if(!t.isMemberExpression(callee))return;if(!callee.computed)return;prop=callee.property;if(!t.isIdentifier(prop.object,{name:"Symbol"}))return;if(!t.isIdentifier(prop.property,{name:"iterator"}))return;return util.template("corejs-iterator",{CORE_ID:file._coreId,VALUE:callee.object})}}})}}},{"../../traverse":72,"../../types":76,"../../util":78,"core-js/library":119,lodash:126}],61:[function(require,module,exports){var t=require("../../types");exports.optional=true;exports.Identifier=function(node,parent){if(node.name==="undefined"&&t.isReferenced(node,parent)){return t.unaryExpression("void",t.literal(0),true)}}},{"../../types":76}],62:[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":76}],63:[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":76,lodash:126}],64:[function(require,module,exports){var traverse=require("../../traverse");var t=require("../../types");exports.Property=exports.MethodDefinition=function(node,parent,file){if(node.kind!=="memo")return;node.kind="get";var value=node.value;t.ensureBlock(value);var key=node.key;if(t.isIdentifier(key)&&!node.computed){key=t.literal(key.name)}traverse(value,{enter:function(node){if(t.isFunction(node))return;if(t.isReturnStatement(node)&&node.argument){node.argument=t.memberExpression(t.callExpression(file.addDeclaration("define-property"),[t.thisExpression(),key,node.argument]),key,true)}}})}},{"../../traverse":72,"../../types":76}],65:[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":76,esutils:124}],66:[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":76}],67:[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":76,esutils:124}],68:[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":76}],69:[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":76}],70:[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":76,esutils:124}],71:[function(require,module,exports){var t=require("../../types");exports.ast={exit: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":76}],72:[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)return;var isArray=_.isArray(result);var inheritTo=result;if(isArray)inheritTo=result[0];if(inheritTo)t.inheritsComments(inheritTo,node);node=obj[key]=result;updated=true;if(isArray&&_.contains(t.STATEMENT_OR_BLOCK_KEYS,key)&&!t.isBlockStatement(obj)){t.ensureBlock(obj,key)}};var stopped=false;var removed=false;var context={stop:function(){stopped=true},remove:function(){this.stop();removed=true}};var ourScope=scope;if(t.isScope(node))ourScope=new Scope(node,scope);if(opts.enter){var result=opts.enter.call(context,node,parent,ourScope);maybeReplace(result);if(removed){obj[key]=null;updated=true}if(stopped)return}traverse(node,opts,ourScope);if(opts.exit){maybeReplace(opts.exit.call(context,node,parent,ourScope))}};if(_.isArray(nodes)){for(i in nodes){handle(nodes,i)}if(updated){parent[key]=_.flatten(parent[key]);if(key==="body"){parent[key]=_.compact(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.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;this.stop()}}});return has}},{"../types":76,"./scope":73,lodash:126}],73:[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 this.stop();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":76,"./index":72,"jshint/src/vars":125,lodash:126}],74:[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","Expression"],FunctionDeclaration:["Statement","Declaration","Scope","Function"],FunctionExpression:["Scope","Function","Expression"],BlockStatement:["Statement","Scope"],Program:["Scope"],CatchClause:["Scope"],LogicalExpression:["Binary","Expression"],BinaryExpression:["Binary","Expression"],UnaryExpression:["UnaryLike","Expression"],SpreadProperty:["UnaryLike"],SpreadElement:["UnaryLike"],ClassDeclaration:["Statement","Declaration","Class"],ClassExpression:["Class","Expression"],ForOfStatement:["Statement","For","Scope","Loop"],ForInStatement:["Statement","For","Scope","Loop"],ForStatement:["Statement","For","Scope","Loop"],ObjectPattern:["Pattern"],ArrayPattern:["Pattern"],Property:["UserWhitespacable"],XJSElement:["UserWhitespacable","Expression"],ArrayExpression:["Expression"],AssignmentExpression:["Expression"],AwaitExpression:["Expression"],BindFunctionExpression:["Expression"],BindMemberExpression:["Expression"],CallExpression:["Expression"],ComprehensionExpression:["Expression"],ConditionalExpression:["Expression"],Identifier:["Expression"],Literal:["Expression"],MemberExpression:["Expression"],NewExpression:["Expression"],ObjectExpression:["Expression"],SequenceExpression:["Expression"],TaggedTemplateExpression:["Expression"],ThisExpression:["Expression"],UpdateExpression:["Expression"],VirtualPropertyExpression:["Expression"],XJSEmptyExpression:["Expression"],XJSMemberExpression:["Expression"],YieldExpression:["Expression"]}
},{}],75:[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"],ImportDeclaration:["specifiers","source"],ImportSpecifier:["id","name"],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"]}},{}],76:[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.isFalsyExpression=function(node){if(t.isLiteral(node)){return!node.value}else if(t.isIdentifier(node)){return node.name==="undefined"}return false};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 arrKeys=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(arrKeys){for(var i in arrKeys){var key=arrKeys[i];search=search.concat(id[key]||[])}}}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","declaration"],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.COMMENT_KEYS=["leadingComments","trailingComments"];t.removeComments=function(child){_.each(t.COMMENT_KEYS,function(key){delete child[key]});return child};t.inheritsComments=function(child,parent){_.each(t.COMMENT_KEYS,function(key){child[key]=_.uniq(_.compact([].concat(child[key],parent[key])))});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":74,"./builder-keys":75,"./visitor-keys":77,esutils:124,lodash:126}],77:[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"]}},{}],78:[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+"/transformation/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":178,"./patch":24,"./traverse":72,"./types":76,"acorn-6to5":1,buffer:95,estraverse:120,fs:93,lodash:126,path:102,util:118}],79:[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":90,"../lib/types":91}],80:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var builtin=types.builtInTypes;var 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":91,"./core":79}],81:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var builtin=types.builtInTypes;var isBoolean=builtin.boolean;var 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":90,"../lib/types":91,"./core":79}],82:[function(require,module,exports){require("./core");var types=require("../lib/types");var def=types.Type.def;var or=types.Type.or;var builtin=types.builtInTypes;var 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":90,"../lib/types":91,"./core":79}],83:[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":90,"../lib/types":91,"./core":79}],84:[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":90,"../lib/types":91,"./core":79}],85:[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":92,assert:94}],86:[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":88,"./scope":89,"./types":91,assert:94,util:118}],87:[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":86,"./types":91,assert:94}],88:[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":91,assert:94}],89:[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":86,"./types":91,assert:94}],90:[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":91}],91:[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:94}],92:[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":79,"./def/e4x":80,"./def/es6":81,"./def/es7":82,"./def/fb-harmony":83,"./def/mozilla":84,"./lib/equiv":85,"./lib/node-path":86,"./lib/path-visitor":87,"./lib/types":91}],93:[function(require,module,exports){},{}],94:[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/":118}],95:[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":96,ieee754:97,"is-array":98}],96:[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)},{}],97:[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}},{}],98:[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)}},{}],99:[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}},{}],100:[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}}},{}],101:[function(require,module,exports){module.exports=Array.isArray||function(arr){return Object.prototype.toString.call(arr)=="[object Array]"}},{}],102:[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:103}],103:[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")}},{}],104:[function(require,module,exports){module.exports=require("./lib/_stream_duplex.js")},{"./lib/_stream_duplex.js":105}],105:[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":107,"./_stream_writable":109,_process:103,"core-util-is":110,inherits:100}],106:[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":108,"core-util-is":110,inherits:100}],107:[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:103,buffer:95,"core-util-is":110,events:99,inherits:100,isarray:101,stream:115,"string_decoder/":116}],108:[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":105,"core-util-is":110,inherits:100}],109:[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":105,_process:103,buffer:95,"core-util-is":110,inherits:100,stream:115}],110:[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:95}],111:[function(require,module,exports){module.exports=require("./lib/_stream_passthrough.js")},{"./lib/_stream_passthrough.js":106}],112:[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":105,"./lib/_stream_passthrough.js":106,"./lib/_stream_readable.js":107,"./lib/_stream_transform.js":108,"./lib/_stream_writable.js":109,stream:115}],113:[function(require,module,exports){module.exports=require("./lib/_stream_transform.js")},{"./lib/_stream_transform.js":108}],114:[function(require,module,exports){module.exports=require("./lib/_stream_writable.js")},{"./lib/_stream_writable.js":109}],115:[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:99,inherits:100,"readable-stream/duplex.js":104,"readable-stream/passthrough.js":111,"readable-stream/readable.js":112,"readable-stream/transform.js":113,"readable-stream/writable.js":114}],116:[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:95}],117:[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"}},{}],118:[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":117,_process:103,inherits:100}],119:[function(require,module,exports){!function(returnThis,framework,undefined){"use strict";var global=returnThis(),OBJECT="Object",FUNCTION="Function",ARRAY="Array",STRING="String",NUMBER="Number",REGEXP="RegExp",DATE="Date",MAP="Map",SET="Set",WEAKMAP="WeakMap",WEAKSET="WeakSet",SYMBOL="Symbol",PROMISE="Promise",MATH="Math",ARGUMENTS="Arguments",PROTOTYPE="prototype",CONSTRUCTOR="constructor",TO_STRING="toString",TO_STRING_TAG=TO_STRING+"Tag",TO_LOCALE="toLocaleString",HAS_OWN="hasOwnProperty",FOR_EACH="forEach",ITERATOR="iterator",FF_ITERATOR="@@"+ITERATOR,PROCESS="process",CREATE_ELEMENT="createElement",Function=global[FUNCTION],Object=global[OBJECT],Array=global[ARRAY],String=global[STRING],Number=global[NUMBER],RegExp=global[REGEXP],Date=global[DATE],Map=global[MAP],Set=global[SET],WeakMap=global[WEAKMAP],WeakSet=global[WEAKSET],Symbol=global[SYMBOL],Math=global[MATH],TypeError=global.TypeError,setTimeout=global.setTimeout,setImmediate=global.setImmediate,clearImmediate=global.clearImmediate,process=global[PROCESS],nextTick=process&&process.nextTick,document=global.document,html=document&&document.documentElement,navigator=global.navigator,define=global.define,ArrayProto=Array[PROTOTYPE],ObjectProto=Object[PROTOTYPE],FunctionProto=Function[PROTOTYPE],Infinity=1/0,DOT=".";function isObject(it){return it!=null&&(typeof it=="object"||typeof it=="function")}function isFunction(it){return typeof it=="function"}var isNative=ctx(/./.test,/\[native code\]\s*\}\s*$/,1);var buildIn={Undefined:1,Null:1,Array:1,String:1,Arguments:1,Function:1,Error:1,Boolean:1,Number:1,Date:1,RegExp:1},toString=ObjectProto[TO_STRING];function setToStringTag(it,tag,stat){if(it)has(it=stat?it:it[PROTOTYPE],SYMBOL_TAG)||hidden(it,SYMBOL_TAG,tag)}function cof(it){return it==undefined?it===undefined?"Undefined":"Null":toString.call(it).slice(8,-1)}function classof(it){var klass=cof(it),tag;return klass==OBJECT&&(tag=it[SYMBOL_TAG])?has(buildIn,tag)?"~"+tag:tag:klass}var call=FunctionProto.call,REFERENCE_GET;function part(){var length=arguments.length,args=Array(length),i=0,_=path._,holder=false;while(length>i)if((args[i]=arguments[i++])===_)holder=true;return partial(this,args,length,holder,_,false)}function partial(fn,argsPart,lengthPart,holder,_,bind,context){assertFunction(fn);return function(){var that=bind?context:this,length=arguments.length,i=0,j=0,args;if(!holder&&!length)return invoke(fn,argsPart,that);args=argsPart.slice();if(holder)for(;lengthPart>i;i++)if(args[i]===_)args[i]=arguments[j++];while(length>j)args.push(arguments[j++]);return invoke(fn,args,that)}}function ctx(fn,that,length){assertFunction(fn);if(~length&&that===undefined)return fn;switch(length){case 1:return function(a){return fn.call(that,a)};case 2:return function(a,b){return fn.call(that,a,b)};case 3:return function(a,b,c){return fn.call(that,a,b,c)}}return function(){return fn.apply(that,arguments)}}function invoke(fn,args,that){var un=that===undefined;switch(args.length|0){case 0:return un?fn():fn.call(that);case 1:return un?fn(args[0]):fn.call(that,args[0]);case 2:return un?fn(args[0],args[1]):fn.call(that,args[0],args[1]);case 3:return un?fn(args[0],args[1],args[2]):fn.call(that,args[0],args[1],args[2]);case 4:return un?fn(args[0],args[1],args[2],args[3]):fn.call(that,args[0],args[1],args[2],args[3]);case 5:return un?fn(args[0],args[1],args[2],args[3],args[4]):fn.call(that,args[0],args[1],args[2],args[3],args[4])}return fn.apply(that,args)}var create=Object.create,getPrototypeOf=Object.getPrototypeOf,defineProperty=Object.defineProperty,defineProperties=Object.defineProperties,getOwnDescriptor=Object.getOwnPropertyDescriptor,getKeys=Object.keys,getNames=Object.getOwnPropertyNames,getSymbols=Object.getOwnPropertySymbols,has=ctx(call,ObjectProto[HAS_OWN],2),ES5Object=Object;function get(object,key){if(has(object,key))return object[key]}function ownKeys(it){return getSymbols?getNames(it).concat(getSymbols(it)):getNames(it)}var assign=Object.assign||function(target,source){var T=Object(assertDefined(target)),l=arguments.length,i=1;while(l>i){var S=ES5Object(arguments[i++]),keys=getKeys(S),length=keys.length,j=0,key;
while(length>j)T[key=keys[j++]]=S[key]}return T};function keyOf(object,el){var O=ES5Object(object),keys=getKeys(O),length=keys.length,index=0,key;while(length>index)if(O[key=keys[index++]]===el)return key}function array(it){return String(it).split(",")}var push=ArrayProto.push,unshift=ArrayProto.unshift,slice=ArrayProto.slice,splice=ArrayProto.splice,indexOf=ArrayProto.indexOf,forEach=ArrayProto[FOR_EACH];function createArrayMethod(type){var isMap=type==1,isFilter=type==2,isSome=type==3,isEvery=type==4,isFindIndex=type==6,noholes=type==5||isFindIndex;return function(callbackfn,that){var O=Object(assertDefined(this)),self=ES5Object(O),f=ctx(callbackfn,that,3),length=toLength(self.length),index=0,result=isMap?Array(length):isFilter?[]:undefined,val,res;for(;length>index;index++)if(noholes||index in self){val=self[index];res=f(val,index,O);if(type){if(isMap)result[index]=res;else if(res)switch(type){case 3:return true;case 5:return val;case 6:return index;case 2:result.push(val)}else if(isEvery)return false}}return isFindIndex?-1:isSome||isEvery?isEvery:result}}function createArrayContains(isContains){return function(el,fromIndex){var O=ES5Object(assertDefined(this)),length=toLength(O.length),index=toIndex(fromIndex,length);if(isContains&&el!=el){for(;length>index;index++)if(sameNaN(O[index]))return isContains||index}else for(;length>index;index++)if(isContains||index in O){if(O[index]===el)return isContains||index}return!isContains&&-1}}function turn(mapfn,target){assertFunction(mapfn);var memo=target==undefined?[]:Object(target),O=ES5Object(this),length=toLength(O.length),index=0;for(;length>index;index++){if(mapfn(memo,O[index],index,this)===false)break}return memo}function generic(A,B){return typeof A=="function"?A:B}var MAX_SAFE_INTEGER=9007199254740991,ceil=Math.ceil,floor=Math.floor,max=Math.max,min=Math.min,random=Math.random,trunc=Math.trunc||function(it){return(it>0?floor:ceil)(it)};function sameNaN(number){return number!=number}function toInteger(it){return isNaN(it)?0:trunc(it)}function toLength(it){return it>0?min(toInteger(it),MAX_SAFE_INTEGER):0}function toIndex(index,length){var index=toInteger(index);return index<0?max(index+length,0):min(index,length)}function createReplacer(regExp,replace,isStatic){var replacer=isObject(replace)?function(part){return replace[part]}:replace;return function(it){return String(isStatic?it:this).replace(regExp,replacer)}}function createPointAt(toString){return function(pos){var s=String(assertDefined(this)),i=toInteger(pos),l=s.length,a,b;if(i<0||i>=l)return toString?"":undefined;a=s.charCodeAt(i);return a<55296||a>56319||i+1===l||(b=s.charCodeAt(i+1))<56320||b>57343?toString?s.charAt(i):a:toString?s.slice(i,i+2):(a-55296<<10)+(b-56320)+65536}}var REDUCE_ERROR="Reduce of empty object with no initial value";function assert(condition,msg1,msg2){if(!condition)throw TypeError(msg2?msg1+msg2:msg1)}function assertDefined(it){if(it==undefined)throw TypeError("Function called on null or undefined");return it}function assertFunction(it){assert(isFunction(it),it," is not a function!");return it}function assertObject(it){assert(isObject(it),it," is not an object!");return it}function assertInstance(it,Constructor,name){assert(it instanceof Constructor,name,": use the 'new' operator!")}function descriptor(bitmap,value){return{enumerable:!(bitmap&1),configurable:!(bitmap&2),writable:!(bitmap&4),value:value}}function simpleSet(object,key,value){object[key]=value;return object}function createDefiner(bitmap){return DESC?function(object,key,value){return defineProperty(object,key,descriptor(bitmap,value))}:simpleSet}function uid(key){return SYMBOL+"("+key+")_"+(++sid+random())[TO_STRING](36)}function getWellKnownSymbol(name,setter){return Symbol&&Symbol[name]||(setter?Symbol:safeSymbol)(SYMBOL+DOT+name)}var DESC=!!function(){try{return defineProperty({},0,ObjectProto)}catch(e){}}(),sid=0,hidden=createDefiner(1),set=Symbol?simpleSet:hidden,safeSymbol=Symbol||uid;function assignHidden(target,src){for(var key in src)hidden(target,key,src[key]);return target}var SYMBOL_ITERATOR=getWellKnownSymbol(ITERATOR),SYMBOL_TAG=getWellKnownSymbol(TO_STRING_TAG),SUPPORT_FF_ITER=FF_ITERATOR in ArrayProto,ITER=safeSymbol("iter"),KEY=1,VALUE=2,Iterators={},IteratorPrototype={},NATIVE_ITERATORS=SYMBOL_ITERATOR in ArrayProto,BUGGY_ITERATORS="keys"in ArrayProto&&!("next"in[].keys());setIterator(IteratorPrototype,returnThis);function setIterator(O,value){hidden(O,SYMBOL_ITERATOR,value);SUPPORT_FF_ITER&&hidden(O,FF_ITERATOR,value)}function createIterator(Constructor,NAME,next,proto){Constructor[PROTOTYPE]=create(proto||IteratorPrototype,{next:descriptor(1,next)});setToStringTag(Constructor,NAME+" Iterator")}function defineIterator(Constructor,NAME,value,DEFAULT){var proto=Constructor[PROTOTYPE],iter=get(proto,SYMBOL_ITERATOR)||get(proto,FF_ITERATOR)||DEFAULT&&get(proto,DEFAULT)||value;if(framework){setIterator(proto,iter);if(iter!==value){var iterProto=getPrototypeOf(iter.call(new Constructor));setToStringTag(iterProto,NAME+" Iterator",true);has(proto,FF_ITERATOR)&&setIterator(iterProto,returnThis)}}Iterators[NAME]=iter;Iterators[NAME+" Iterator"]=returnThis}function defineStdIterators(Base,NAME,Constructor,next,DEFAULT){function createIter(kind){return function(){return new Constructor(this,kind)}}createIterator(Constructor,NAME,next);defineIterator(Base,NAME,createIter(DEFAULT),DEFAULT==VALUE?"values":"entries");DEFAULT&&$define(PROTO+FORCED*BUGGY_ITERATORS,NAME,{entries:createIter(KEY+VALUE),keys:createIter(KEY),values:createIter(VALUE)})}function iterResult(done,value){return{value:value,done:!!done}}function isIterable(it){var O=Object(it);return SYMBOL_ITERATOR in O||has(Iterators,classof(O))}function getIterator(it){return assertObject((it[SYMBOL_ITERATOR]||Iterators[classof(it)]).call(it))}function stepCall(fn,value,entries){return entries?invoke(fn,value):fn(value)}function forOf(iterable,entries,fn,that){var iterator=getIterator(iterable),f=ctx(fn,that,entries?2:1),step;while(!(step=iterator.next()).done)if(stepCall(f,step.value,entries)===false)return}var NODE=cof(process)==PROCESS,core={},path=framework?global:core,old=global.core,FORCED=1,GLOBAL=2,STATIC=4,PROTO=8,BIND=16,WRAP=32;function $define(type,name,source){var key,own,out,exp,isGlobal=type&GLOBAL,target=isGlobal?global:type&STATIC?global[name]:(global[name]||ObjectProto)[PROTOTYPE],exports=isGlobal?core:core[name]||(core[name]={});if(isGlobal)source=name;for(key in source){own=!(type&FORCED)&&target&&key in target&&(!isFunction(target[key])||isNative(target[key]));out=(own?target:source)[key];if(type&BIND&&own)exp=ctx(out,global);else if(type&WRAP&&!framework&&target[key]==out){exp=function(param){return this instanceof out?new out(param):out(param)};exp[PROTOTYPE]=out[PROTOTYPE]}else exp=type&PROTO&&isFunction(out)?ctx(call,out):out;if(exports[key]!=out)hidden(exports,key,exp);if(framework&&target&&!own){if(isGlobal)target[key]=out;else delete target[key]&&hidden(target,key,out)}}}if(NODE)module.exports=core;if(isFunction(define)&&define.amd)define(function(){return core});if(!NODE||framework){core.noConflict=function(){global.core=old;return core};global.core=core}$define(GLOBAL+FORCED,{global:global});!function(TAG,SymbolRegistry,setter){if(!isNative(Symbol)){Symbol=function(description){assert(!(this instanceof Symbol),SYMBOL+" is not a "+CONSTRUCTOR);var tag=uid(description);setter&&defineProperty(ObjectProto,tag,{configurable:true,set:function(value){hidden(this,tag,value)}});return set(create(Symbol[PROTOTYPE]),TAG,tag)};hidden(Symbol[PROTOTYPE],TO_STRING,function(){return this[TAG]})}$define(GLOBAL+WRAP,{Symbol:Symbol});var symbolStatics={"for":function(key){return has(SymbolRegistry,key+="")?SymbolRegistry[key]:SymbolRegistry[key]=Symbol(key)},iterator:SYMBOL_ITERATOR,keyFor:part.call(keyOf,SymbolRegistry),toStringTag:SYMBOL_TAG=getWellKnownSymbol(TO_STRING_TAG,true),pure:safeSymbol,set:set,useSetter:function(){setter=true},useSimple:function(){setter=false}};forEach.call(array("hasInstance,isConcatSpreadable,match,replace,search,"+"species,split,toPrimitive,unscopables"),function(it){symbolStatics[it]=getWellKnownSymbol(it)});$define(STATIC,SYMBOL,symbolStatics);setToStringTag(Symbol,SYMBOL);$define(GLOBAL,{Reflect:{ownKeys:ownKeys}})}(safeSymbol("tag"),{},true);!function(isFinite,tmp){var RangeError=global.RangeError,isInteger=Number.isInteger||function(it){return!isObject(it)&&isFinite(it)&&floor(it)===it},sign=Math.sign||function sign(it){return(it=+it)==0||it!=it?it:it<0?-1:1},pow=Math.pow,abs=Math.abs,exp=Math.exp,log=Math.log,sqrt=Math.sqrt,fcc=String.fromCharCode,at=createPointAt(true);var objectStatic={assign:assign,is:function(x,y){return x===y?x!==0||1/x===1/y:x!=x&&y!=y}};"__proto__"in ObjectProto&&function(buggy,set){try{set=ctx(call,getOwnDescriptor(ObjectProto,"__proto__").set,2);set({},ArrayProto)}catch(e){buggy=true}objectStatic.setPrototypeOf=function(O,proto){assertObject(O);assert(proto===null||isObject(proto),proto,": can't set as prototype!");if(buggy)O.__proto__=proto;else set(O,proto);return O}}();$define(STATIC,OBJECT,objectStatic);function asinh(x){return!isFinite(x=+x)||x==0?x:x<0?-asinh(-x):log(x+sqrt(x*x+1))}$define(STATIC,NUMBER,{EPSILON:pow(2,-52),isFinite:function(it){return typeof it=="number"&&isFinite(it)},isInteger:isInteger,isNaN:sameNaN,isSafeInteger:function(number){return isInteger(number)&&abs(number)<=MAX_SAFE_INTEGER},MAX_SAFE_INTEGER:MAX_SAFE_INTEGER,MIN_SAFE_INTEGER:-MAX_SAFE_INTEGER,parseFloat:parseFloat,parseInt:parseInt});$define(STATIC,MATH,{acosh:function(x){return x<1?NaN:log(x+sqrt(x*x-1))},asinh:asinh,atanh:function(x){return x==0?+x:log((1+ +x)/(1-x))/2},cbrt:function(x){return sign(x)*pow(abs(x),1/3)},clz32:function(x){return(x>>>=0)?32-x[TO_STRING](2).length:32},cosh:function(x){return(exp(x)+exp(-x))/2},expm1:function(x){return x==0?+x:x>-1e-6&&x<1e-6?+x+x*x/2:exp(x)-1},fround:function(x){return new Float32Array([x])[0]},hypot:function(value1,value2){var sum=0,length=arguments.length,value;while(length--){value=+arguments[length];if(value==Infinity||value==-Infinity)return Infinity;sum+=value*value}return sqrt(sum)},imul:function(x,y){var UInt16=65535,xl=UInt16&x,yl=UInt16&y;return 0|xl*yl+((UInt16&x>>>16)*yl+xl*(UInt16&y>>>16)<<16>>>0)},log1p:function(x){return x>-1e-8&&x<1e-8?x-x*x/2:log(1+ +x)},log10:function(x){return log(x)/Math.LN10},log2:function(x){return log(x)/Math.LN2},sign:sign,sinh:function(x){return x==0?+x:(exp(x)-exp(-x))/2},tanh:function(x){return isFinite(x)?x==0?+x:(exp(x)-exp(-x))/(exp(x)+exp(-x)):sign(x)},trunc:trunc});setToStringTag(Math,MATH,true);function assertNotRegExp(it){if(isObject(it)&&it instanceof RegExp)throw TypeError()}$define(STATIC,STRING,{fromCodePoint:function(){var res=[],len=arguments.length,i=0,code;while(len>i){code=+arguments[i++];if(toIndex(code,1114111)!==code)throw RangeError(code+" is not a valid code point");res.push(code<65536?fcc(code):fcc(((code-=65536)>>10)+55296,code%1024+56320))}return res.join("")},raw:function(callSite){var raw=ES5Object(assertDefined(callSite.raw)),len=toLength(raw.length),sln=arguments.length,res=[],i=0;while(len>i){res.push(String(raw[i++]));if(i<sln)res.push(String(arguments[i]))}return res.join("")}});$define(PROTO,STRING,{codePointAt:createPointAt(false),endsWith:function(searchString,endPosition){assertNotRegExp(searchString);var len=this.length,end=endPosition===undefined?len:min(toLength(endPosition),len);searchString+="";return String(this).slice(end-searchString.length,end)===searchString},includes:function(searchString,position){return!!~String(assertDefined(this)).indexOf(searchString,position)},repeat:function(count){var str=String(assertDefined(this)),res="",n=toInteger(count);if(0>n||n==Infinity)throw RangeError("Count can't be negative");for(;n>0;(n>>>=1)&&(str+=str))if(n&1)res+=str;return res},startsWith:function(searchString,position){assertNotRegExp(searchString);var index=toLength(min(position,this.length));searchString+="";return String(this).slice(index,index+searchString.length)===searchString}});defineStdIterators(String,STRING,function(iterated){set(this,ITER,{o:String(iterated),i:0})},function(){var iter=this[ITER],O=iter.o,index=iter.i,point;if(index>=O.length)return iterResult(1);point=at.call(O,index);iter.i+=point.length;return iterResult(0,point)});$define(STATIC,ARRAY,{from:function(arrayLike,mapfn,that){var O=Object(assertDefined(arrayLike)),result=new(generic(this,Array)),mapping=mapfn!==undefined,f=mapping?ctx(mapfn,that,2):undefined,index=0,length;if(isIterable(O))for(var iter=getIterator(O),step;!(step=iter.next()).done;index++){result[index]=mapping?f(step.value,index):step.value}else for(length=toLength(O.length);length>index;index++){result[index]=mapping?f(O[index],index):O[index]}result.length=index;return result},of:function(){var index=0,length=arguments.length,result=new(generic(this,Array))(length);while(length>index)result[index]=arguments[index++];result.length=length;return result}});$define(PROTO,ARRAY,{copyWithin:function(target,start,end){var O=Object(assertDefined(this)),len=toLength(O.length),to=toIndex(target,len),from=toIndex(start,len),fin=end===undefined?len:toIndex(end,len),count=min(fin-from,len-to),inc=1;if(from<to&&to<from+count){inc=-1;from=from+count-1;to=to+count-1}while(count-->0){if(from in O)O[to]=O[from];else delete O[to];to+=inc;from+=inc}return O},fill:function(value,start,end){var O=Object(assertDefined(this)),length=toLength(O.length),index=toIndex(start,length),endPos=end===undefined?length:toIndex(end,length);while(endPos>index)O[index++]=value;return O},find:createArrayMethod(5),findIndex:createArrayMethod(6)});defineStdIterators(Array,ARRAY,function(iterated,kind){set(this,ITER,{o:ES5Object(iterated),i:0,k:kind})},function(){var iter=this[ITER],O=iter.o,kind=iter.k,index=iter.i++;if(!O||index>=O.length)return iter.o=undefined,iterResult(1);if(kind==KEY)return iterResult(0,index);if(kind==VALUE)return iterResult(0,O[index]);return iterResult(0,[index,O[index]])},VALUE);Iterators[ARGUMENTS]=Iterators[ARRAY];setToStringTag(global.JSON,"JSON",true);if(framework){tmp[SYMBOL_TAG]=DOT;if(cof(tmp)!=DOT)hidden(ObjectProto,TO_STRING,function(){return"[object "+classof(this)+"]"});if(/./g.flags!="g")defineProperty(RegExp[PROTOTYPE],"flags",{configurable:true,get:createReplacer(/^.*\/(\w*)$/,"$1")})}}(isFinite,{});isFunction(setImmediate)&&isFunction(clearImmediate)||function(ONREADYSTATECHANGE){var postMessage=global.postMessage,addEventListener=global.addEventListener,MessageChannel=global.MessageChannel,counter=0,queue={},defer,channel,port;setImmediate=function(fn){var args=[],i=1;while(arguments.length>i)args.push(arguments[i++]);queue[++counter]=function(){invoke(isFunction(fn)?fn:Function(fn),args)};defer(counter);return counter};clearImmediate=function(id){delete queue[id]};function run(id){if(has(queue,id)){var fn=queue[id];delete queue[id];fn()}}function listner(event){run(event.data)}if(NODE){defer=function(id){nextTick(part.call(run,id))}}else if(addEventListener&&isFunction(postMessage)&&!global.importScripts){defer=function(id){postMessage(id,"*")};addEventListener("message",listner,false)}else if(isFunction(MessageChannel)){channel=new MessageChannel;port=channel.port2;channel.port1.onmessage=listner;defer=ctx(port.postMessage,port,1)}else if(document&&ONREADYSTATECHANGE in document[CREATE_ELEMENT]("script")){defer=function(id){html.appendChild(document[CREATE_ELEMENT]("script"))[ONREADYSTATECHANGE]=function(){html.removeChild(this);run(id)}}}else{defer=function(id){setTimeout(part.call(run,id),0)}}}("onreadystatechange");$define(GLOBAL+BIND,{setImmediate:setImmediate,clearImmediate:clearImmediate});!function(Promise,test){isFunction(Promise)&&isFunction(Promise.resolve)&&Promise.resolve(test=new Promise(Function()))==test||function(asap,DEF){function isThenable(o){var then;if(isObject(o))then=o.then;return isFunction(then)?then:false}function notify(def){var chain=def.chain;chain.length&&asap(function(){var msg=def.msg,ok=def.state==1,i=0;while(chain.length>i)!function(react){var cb=ok?react.ok:react.fail,ret,then;try{if(cb){ret=cb===true?msg:cb(msg);if(ret===react.P){react.rej(TypeError(PROMISE+"-chain cycle"))}else if(then=isThenable(ret)){then.call(ret,react.res,react.rej)}else react.res(ret)}else react.rej(msg)}catch(err){react.rej(err)}}(chain[i++]);chain.length=0})}function resolve(msg){var def=this,then,wrapper;if(def.done)return;def.done=true;def=def.def||def;try{if(then=isThenable(msg)){wrapper={def:def,done:false};then.call(msg,ctx(resolve,wrapper,1),ctx(reject,wrapper,1))}else{def.msg=msg;def.state=1;notify(def)}}catch(err){reject.call(wrapper||{def:def,done:false},err)}}function reject(msg){var def=this;if(def.done)return;def.done=true;def=def.def||def;def.msg=msg;def.state=2;notify(def)}Promise=function(executor){assertFunction(executor);assertInstance(this,Promise,PROMISE);var def={chain:[],state:0,done:false,msg:undefined};hidden(this,DEF,def);try{executor(ctx(resolve,def,1),ctx(reject,def,1))}catch(err){reject.call(def,err)}};assignHidden(Promise[PROTOTYPE],{then:function(onFulfilled,onRejected){var react={ok:isFunction(onFulfilled)?onFulfilled:true,fail:isFunction(onRejected)?onRejected:false},P=react.P=new this[CONSTRUCTOR](function(resolve,reject){react.res=assertFunction(resolve);react.rej=assertFunction(reject)}),def=this[DEF];def.chain.push(react);def.state&¬ify(def);return P},"catch":function(onRejected){return this.then(undefined,onRejected)}});assignHidden(Promise,{all:function(iterable){var Promise=this,values=[];return new Promise(function(resolve,reject){forOf(iterable,false,push,values);var remaining=values.length,results=Array(remaining);if(remaining)forEach.call(values,function(promise,index){Promise.resolve(promise).then(function(value){results[index]=value;--remaining||resolve(results)},reject)});else resolve(results)})},race:function(iterable){var Promise=this;return new Promise(function(resolve,reject){forOf(iterable,false,function(promise){Promise.resolve(promise).then(resolve,reject)})})},reject:function(r){return new this(function(resolve,reject){reject(r)})},resolve:function(x){return isObject(x)&&getPrototypeOf(x)===this[PROTOTYPE]?x:new this(function(resolve,reject){resolve(x)})}})}(nextTick||setImmediate,safeSymbol("def"));setToStringTag(Promise,PROMISE);$define(GLOBAL+FORCED*!isNative(Promise),{Promise:Promise})}(global[PROMISE]);!function(){var UID=safeSymbol("uid"),DATA=safeSymbol("data"),WEAK=safeSymbol("weak"),LAST=safeSymbol("last"),FIRST=safeSymbol("first"),SIZE=DESC?safeSymbol("size"):"size",uid=0;function getCollection(C,NAME,methods,commonMethods,isMap,isWeak){var ADDER=isMap?"set":"add",proto=C&&C[PROTOTYPE],O={};function initFromIterable(that,iterable){if(iterable!=undefined)forOf(iterable,isMap,that[ADDER],that);return that}function fixSVZ(key,chain){var method=proto[key];framework&&hidden(proto,key,function(a,b){var result=method.call(this,a===0?0:a,b);return chain?this:result})}if(!isNative(C)||!(isWeak||!BUGGY_ITERATORS&&has(proto,"entries"))){C=isWeak?function(iterable){assertInstance(this,C,NAME);set(this,UID,uid++);initFromIterable(this,iterable)}:function(iterable){var that=this;assertInstance(that,C,NAME);set(that,DATA,create(null));set(that,SIZE,0);set(that,LAST,undefined);set(that,FIRST,undefined);initFromIterable(that,iterable)};assignHidden(assignHidden(C[PROTOTYPE],methods),commonMethods);isWeak||defineProperty(C[PROTOTYPE],"size",{get:function(){return assertDefined(this[SIZE])}})}else{var Native=C,inst=new C,chain=inst[ADDER](isWeak?{}:-0,1),buggyZero;if(!NATIVE_ITERATORS||!C.length){C=function(iterable){assertInstance(this,C,NAME);return initFromIterable(new Native,iterable)};C[PROTOTYPE]=proto}isWeak||inst[FOR_EACH](function(val,key){buggyZero=1/key===-Infinity});if(buggyZero){fixSVZ("delete");fixSVZ("has");isMap&&fixSVZ("get")}if(buggyZero||chain!==inst)fixSVZ(ADDER,true)}setToStringTag(C,NAME);O[NAME]=C;$define(GLOBAL+WRAP+FORCED*!isNative(C),O);isWeak||defineStdIterators(C,NAME,function(iterated,kind){set(this,ITER,{o:iterated,k:kind})},function(){var iter=this[ITER],O=iter.o,kind=iter.k,entry=iter.l;while(entry&&entry.r)entry=entry.p;if(!O||!(iter.l=entry=entry?entry.n:O[FIRST]))return iter.o=undefined,iterResult(1);if(kind==KEY)return iterResult(0,entry.k);if(kind==VALUE)return iterResult(0,entry.v);return iterResult(0,[entry.k,entry.v])},isMap?KEY+VALUE:VALUE);return C}function fastKey(it,create){if(!isObject(it))return(typeof it=="string"?"S":"P")+it;if(!has(it,UID)){if(create)hidden(it,UID,++uid);else return""}return"O"+it[UID]}function def(that,key,value){var index=fastKey(key,true),data=that[DATA],last=that[LAST],entry;if(index in data)data[index].v=value;else{entry=data[index]={k:key,v:value,p:last};if(!that[FIRST])that[FIRST]=entry;if(last)last.n=entry;that[LAST]=entry;that[SIZE]++}return that}function del(that,index){var data=that[DATA],entry=data[index],next=entry.n,prev=entry.p;delete data[index];entry.r=true;if(prev)prev.n=next;if(next)next.p=prev;if(that[FIRST]==entry)that[FIRST]=next;if(that[LAST]==entry)that[LAST]=prev;that[SIZE]--}var collectionMethods={clear:function(){for(var index in this[DATA])del(this,index)},"delete":function(key){var index=fastKey(key),contains=index in this[DATA];if(contains)del(this,index);return contains},forEach:function(callbackfn,that){var f=ctx(callbackfn,that,3),entry;while(entry=entry?entry.n:this[FIRST]){f(entry.v,entry.k,this);while(entry&&entry.r)entry=entry.p}},has:function(key){return fastKey(key)in this[DATA]}};Map=getCollection(Map,MAP,{get:function(key){var entry=this[DATA][fastKey(key)];return entry&&entry.v},set:function(key,value){return def(this,key===0?0:key,value)}},collectionMethods,true);Set=getCollection(Set,SET,{add:function(value){return def(this,value=value===0?0:value,value)}},collectionMethods);function setWeak(that,key,value){has(assertObject(key),WEAK)||hidden(key,WEAK,{});key[WEAK][that[UID]]=value;return that}function hasWeak(key){return isObject(key)&&has(key,WEAK)&&has(key[WEAK],this[UID])}var weakMethods={"delete":function(key){return hasWeak.call(this,key)&&delete key[WEAK][this[UID]]},has:hasWeak};WeakMap=getCollection(WeakMap,WEAKMAP,{get:function(key){if(isObject(key)&&has(key,WEAK))return key[WEAK][this[UID]]},set:function(key,value){return setWeak(this,key,value)}},weakMethods,true,true);WeakSet=getCollection(WeakSet,WEAKSET,{add:function(value){return setWeak(this,value,true)}},weakMethods,false,true)}();!function(){$define(PROTO,ARRAY,{includes:createArrayContains(true)});$define(PROTO,STRING,{at:createPointAt(true)});function createObjectToArray(isEntries){return function(object){var O=ES5Object(object),keys=getKeys(object),length=keys.length,i=0,result=Array(length),key;if(isEntries)while(length>i)result[i]=[key=keys[i++],O[key]];else while(length>i)result[i]=O[keys[i++]];return result}}$define(STATIC,OBJECT,{values:createObjectToArray(false),entries:createObjectToArray(true)});$define(STATIC,REGEXP,{escape:createReplacer(/([\\\-[\]{}()*+?.,^$|])/g,"\\$1",true)})}();!function(REFERENCE){REFERENCE_GET=getWellKnownSymbol(REFERENCE+"Get",true);var REFERENCE_SET=getWellKnownSymbol(REFERENCE+SET,true),REFERENCE_DELETE=getWellKnownSymbol(REFERENCE+"Delete",true);$define(STATIC,SYMBOL,{referenceGet:REFERENCE_GET,referenceSet:REFERENCE_SET,referenceDelete:REFERENCE_DELETE});hidden(FunctionProto,REFERENCE_GET,returnThis);function setMapMethods(Constructor){if(Constructor){var MapProto=Constructor[PROTOTYPE];hidden(MapProto,REFERENCE_GET,MapProto.get);hidden(MapProto,REFERENCE_SET,MapProto.set);hidden(MapProto,REFERENCE_DELETE,MapProto["delete"])}}setMapMethods(Map);setMapMethods(WeakMap)}("reference");!function(DICT){function Dict(iterable){var dict=create(null);if(iterable!=undefined){if(isIterable(iterable)){for(var iter=getIterator(iterable),step,value;!(step=iter.next()).done;){value=step.value;dict[value[0]]=value[1]}}else assign(dict,iterable)}return dict}Dict[PROTOTYPE]=null;function DictIterator(iterated,kind){set(this,ITER,{o:ES5Object(iterated),a:getKeys(iterated),i:0,k:kind})}createIterator(DictIterator,DICT,function(){var iter=this[ITER],O=iter.o,keys=iter.a,kind=iter.k,key;while(true){if(iter.i>=keys.length)return iterResult(1);if(has(O,key=keys[iter.i++]))break}if(kind==KEY)return iterResult(0,key);if(kind==VALUE)return iterResult(0,O[key]);return iterResult(0,[key,O[key]])});function createDictIter(kind){return function(it){return new DictIterator(it,kind)}}function createDictMethod(type){var isMap=type==1,isEvery=type==4;return function(object,callbackfn,that){var f=ctx(callbackfn,that,3),O=ES5Object(object),result=isMap||type==7||type==2?new(generic(this,Dict)):undefined,key,val,res;for(key in O)if(has(O,key)){val=O[key];res=f(val,key,object);if(type){if(isMap)result[key]=res;else if(res)switch(type){case 2:result[key]=val;break;case 3:return true;case 5:return val;case 6:return key;case 7:result[res[0]]=res[1]}else if(isEvery)return false}}return type==3||isEvery?isEvery:result}}function createDictReduce(isTurn){return function(object,mapfn,init){assertFunction(mapfn);var O=ES5Object(object),keys=getKeys(O),length=keys.length,i=0,memo,key,result;if(isTurn)memo=init==undefined?new(generic(this,Dict)):Object(init);else if(arguments.length<3){assert(length,REDUCE_ERROR);memo=O[keys[i++]]}else memo=Object(init);while(length>i)if(has(O,key=keys[i++])){result=mapfn(memo,O[key],key,object);if(isTurn){if(result===false)break}else memo=result}return memo}}var findKey=createDictMethod(6);function includes(object,el){return(el==el?keyOf(object,el):findKey(object,sameNaN))!==undefined}var dictMethods={keys:createDictIter(KEY),values:createDictIter(VALUE),entries:createDictIter(KEY+VALUE),forEach:createDictMethod(0),map:createDictMethod(1),filter:createDictMethod(2),some:createDictMethod(3),every:createDictMethod(4),find:createDictMethod(5),findKey:findKey,mapPairs:createDictMethod(7),reduce:createDictReduce(false),turn:createDictReduce(true),keyOf:keyOf,includes:includes,has:has,get:get,set:createDefiner(0),isDict:function(it){return isObject(it)&&getPrototypeOf(it)===Dict[PROTOTYPE]}};if(REFERENCE_GET)for(var key in dictMethods)!function(fn){function method(){for(var args=[this],i=0;i<arguments.length;)args.push(arguments[i++]);return invoke(fn,args)}fn[REFERENCE_GET]=function(){return method}}(dictMethods[key]);$define(GLOBAL+FORCED,{Dict:assignHidden(Dict,dictMethods)})}("Dict");!function(ENTRIES,FN){function $for(iterable,entries){if(!(this instanceof $for))return new $for(iterable,entries);this[ITER]=getIterator(iterable);this[ENTRIES]=!!entries}createIterator($for,"Wrapper",function(){return this[ITER].next()});var $forProto=$for[PROTOTYPE];setIterator($forProto,function(){return this[ITER]});function createChainIterator(next){function Iter(I,fn,that){this[ITER]=getIterator(I);this[ENTRIES]=I[ENTRIES];this[FN]=ctx(fn,that,I[ENTRIES]?2:1)}createIterator(Iter,"Chain",next,$forProto);setIterator(Iter[PROTOTYPE],returnThis);return Iter}var MapIter=createChainIterator(function(){var step=this[ITER].next();return step.done?step:iterResult(0,stepCall(this[FN],step.value,this[ENTRIES]))});var FilterIter=createChainIterator(function(){for(;;){var step=this[ITER].next();if(step.done||stepCall(this[FN],step.value,this[ENTRIES]))return step}});assignHidden($forProto,{of:function(fn,that){forOf(this,this[ENTRIES],fn,that)},array:function(fn,that){var result=[];forOf(fn!=undefined?this.map(fn,that):this,false,push,result);return result},filter:function(fn,that){return new FilterIter(this,fn,that)},map:function(fn,that){return new MapIter(this,fn,that)}});$for.isIterable=isIterable;$for.getIterator=getIterator;$define(GLOBAL+FORCED,{$for:$for})}("entries",safeSymbol("fn"));!function(_,toLocaleString){core._=path._=path._||{};$define(PROTO+FORCED,FUNCTION,{part:part,by:function(that){var fn=this,_=path._,holder=false,length=arguments.length,isThat=that===_,i=+!isThat,indent=i,it,args;if(isThat){it=fn;fn=call}else it=that;if(length<2)return ctx(fn,it,-1);args=Array(length-indent);while(length>i)if((args[i-indent]=arguments[i++])===_)holder=true;return partial(fn,args,length,holder,_,true,it)},only:function(numberArguments,that){var fn=assertFunction(this),n=toLength(numberArguments),isThat=arguments.length>1;return function(){var length=min(n,arguments.length),args=Array(length),i=0;while(length>i)args[i]=arguments[i++];return invoke(fn,args,isThat?that:this)}}});function tie(key){var that=this,bound={};return hidden(that,_,function(key){if(key===undefined||!(key in that))return toLocaleString.call(that);return has(bound,key)?bound[key]:bound[key]=ctx(that[key],that,-1)})[_](key)}hidden(path._,TO_STRING,function(){return _});hidden(ObjectProto,_,tie);DESC||hidden(ArrayProto,_,tie)}(DESC?uid("tie"):TO_LOCALE,ObjectProto[TO_LOCALE]);!function(){function define(target,mixin){var keys=ownKeys(ES5Object(mixin)),length=keys.length,i=0,key;while(length>i)defineProperty(target,key=keys[i++],getOwnDescriptor(mixin,key));return target}$define(STATIC+FORCED,OBJECT,{isObject:isObject,classof:classof,define:define,make:function(proto,mixin){return define(create(proto),mixin)}})}();$define(PROTO+FORCED,ARRAY,{turn:turn});!function(){function setArrayStatics(keys,length){$define(STATIC,ARRAY,turn.call(array(keys),function(memo,key){if(key in ArrayProto)memo[key]=ctx(call,ArrayProto[key],length)},{}))}setArrayStatics("pop,reverse,shift,keys,values,entries",1);setArrayStatics("indexOf,every,some,forEach,map,filter,find,findIndex,includes",3);setArrayStatics("join,slice,concat,push,splice,unshift,sort,lastIndexOf,"+"reduce,reduceRight,copyWithin,fill,turn")}();!function(){function NumberIterator(iterated){set(this,ITER,{l:toLength(iterated),i:0})}createIterator(NumberIterator,NUMBER,function(){var iter=this[ITER],i=iter.i++;return i<iter.l?iterResult(0,i):iterResult(1)});defineIterator(Number,NUMBER,function(){return new NumberIterator(this)});$define(PROTO+FORCED,NUMBER,{random:function(lim){var a=+this,b=lim==undefined?0:+lim,m=min(a,b);return random()*(max(a,b)-m)+m}});$define(PROTO+FORCED,NUMBER,turn.call(array("round,floor,ceil,abs,sin,asin,cos,acos,tan,atan,exp,sqrt,max,min,pow,atan2,"+"acosh,asinh,atanh,cbrt,clz32,cosh,expm1,hypot,imul,log1p,log10,log2,sign,sinh,tanh,trunc"),function(memo,key){var fn=Math[key];if(fn)memo[key]=function(){var args=[+this],i=0;while(arguments.length>i)args.push(arguments[i++]);return invoke(fn,args)}},{}))}();!function(){var escapeHTMLDict={"&":"&","<":"<",">":">",'"':""","'":"'"},unescapeHTMLDict={},key;for(key in escapeHTMLDict)unescapeHTMLDict[escapeHTMLDict[key]]=key;$define(PROTO+FORCED,STRING,{escapeHTML:createReplacer(/[&<>"']/g,escapeHTMLDict),unescapeHTML:createReplacer(/&(?:amp|lt|gt|quot|apos);/g,unescapeHTMLDict)})}();!function(formatRegExp,flexioRegExp,locales,current,SECONDS,MINUTES,HOURS,MONTH,YEAR){function createFormat(prefix){return function(template,locale){var that=this,dict=locales[has(locales,locale)?locale:current];function get(unit){return that[prefix+unit]()}return String(template).replace(formatRegExp,function(part){switch(part){case"s":return get(SECONDS);case"ss":return lz(get(SECONDS));case"m":return get(MINUTES);case"mm":return lz(get(MINUTES));case"h":return get(HOURS);case"hh":return lz(get(HOURS));case"D":return get(DATE);case"DD":return lz(get(DATE));case"W":return dict[0][get("Day")];case"N":return get(MONTH)+1;case"NN":return lz(get(MONTH)+1);case"M":return dict[2][get(MONTH)];case"MM":return dict[1][get(MONTH)];case"Y":return get(YEAR);case"YY":return lz(get(YEAR)%100)}return part})}}function lz(num){return num>9?num:"0"+num}function addLocale(lang,locale){function split(index){return turn.call(array(locale.months),function(memo,it){memo.push(it.replace(flexioRegExp,"$"+index))})}locales[lang]=[array(locale.weekdays),split(1),split(2)];return core}$define(PROTO+FORCED,DATE,{format:createFormat("get"),formatUTC:createFormat("getUTC")});addLocale(current,{weekdays:"Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday",months:"January,February,March,April,May,June,July,August,September,October,November,December"});
addLocale("ru",{weekdays:"Воскресенье,Понедельник,Вторник,Среда,Четверг,Пятница,Суббота",months:"Январ:я|ь,Феврал:я|ь,Март:а|,Апрел:я|ь,Ма:я|й,Июн:я|ь,"+"Июл:я|ь,Август:а|,Сентябр:я|ь,Октябр:я|ь,Ноябр:я|ь,Декабр:я|ь"});core.locale=function(locale){return has(locales,locale)?current=locale:current};core.addLocale=addLocale}(/\b\w\w?\b/g,/:(.*)\|(.*)$/,{},"en","Seconds","Minutes","Hours","Month","FullYear")}(Function("return this"),false)},{}],120:[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})},{}],121:[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}})()},{}],122:[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}})()},{}],123:[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":122}],124:[function(require,module,exports){(function(){"use strict";exports.ast=require("./ast");exports.code=require("./code");exports.keyword=require("./keyword")})()},{"./ast":121,"./code":122,"./keyword":123}],125:[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}},{}],126:[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:{})},{}],127:[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)},{}],128:[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":130,"./meta":131,"./util":132,assert:94,recast:159}],129:[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:94,recast:159}],130:[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":128,assert:94,recast:159,util:118}],131:[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:94,"private":127,recast:159}],132:[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:94,recast:159}],133:[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)}})},{"..":134,"./emit":128,"./hoist":129,"./util":132,assert:94,fs:93,recast:159}],134:[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":132,"./lib/visit":133,"./runtime":161,assert:94,defs:135,"esprima-fb":149,fs:93,path:102,recast:159,through:160}],135:[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":136,"./jshint_globals/vars.js":137,"./options":138,"./scope":139,"./stats":140,alter:141,assert:94,"ast-traverse":143,breakable:144,"simple-fmt":145,"simple-is":146,stringmap:147,stringset:148}],136:[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:94,"simple-fmt":145}],137:[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}},{}],138:[function(require,module,exports){module.exports={disallowVars:false,disallowDuplicated:true,disallowUnknownReferences:true,parse:require("esprima-fb").parse}},{"esprima-fb":149}],139:[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":136,"./options":138,assert:94,"simple-fmt":145,"simple-is":146,stringmap:147,stringset:148}],140:[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:94,"simple-fmt":145,"simple-is":146}],141:[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:94,stable:142}],142:[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}})()},{}],143:[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}},{}],144:[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}},{}],145:[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}},{}],146:[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}},{}],147:[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}},{}],148:[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}},{}],149:[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}()})},{}],150:[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":151,"./types":157,"./util":158,assert:94,"private":127}],151:[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":152,"./options":153,"./types":157,"./util":158,assert:94,"private":127,"source-map":168}],152:[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":151,"./types":157,"./util":158,assert:94}],153:[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":149}],154:[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":150,"./lines":151,"./options":153,"./patcher":155,"./types":157,assert:94}],155:[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":151,"./types":157,"./util":158,assert:94}],156:[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":150,"./lines":151,"./options":153,"./patcher":155,"./types":157,"./util":158,assert:94,"source-map":168}],157:[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":92}],158:[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":157,assert:94,"source-map":168}],159:[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":154,"./lib/printer":156,"./lib/types":157,_process:103,fs:93}],160:[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:103,stream:115}],161:[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}}}()},{}],162:[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:164}],163:[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}},{}],164:[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:{})},{}],165:[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:{})},{}],166:[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}})()},{}],167:[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":162,"./data/iu-mappings.json":163,regenerate:164,regjsgen:165,regjsparser:166}],168:[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":173,"./source-map/source-map-generator":174,"./source-map/source-node":175}],169:[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":176,amdefine:177}],170:[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":171,amdefine:177}],171:[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:177}],172:[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:177}],173:[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":169,"./base64-vlq":170,"./binary-search":172,"./util":176,amdefine:177}],174:[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":169,"./base64-vlq":170,"./util":176,amdefine:177}],175:[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":174,"./util":176,amdefine:177}],176:[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:177}],177:[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:103,path:102}],178:[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-from":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Array"},property:{type:"Identifier",name:"from"},computed:false},arguments:[{type:"Identifier",name:"VALUE"}]}}]},"array-push":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"KEY"},property:{type:"Identifier",name:"push"},computed:false},arguments:[{type:"Identifier",name:"STATEMENT"}]}}]},"async-to-generator":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"fn"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"FunctionExpression",id:null,params:[],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"gen"},init:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"fn"},property:{type:"Identifier",name:"apply"},computed:false},arguments:[{type:"ThisExpression"},{type:"Identifier",name:"arguments"}]}}],kind:"var"},{type:"ReturnStatement",argument:{type:"NewExpression",callee:{type:"Identifier",name:"Promise"},arguments:[{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"resolve"},{type:"Identifier",name:"reject"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"FunctionDeclaration",id:{type:"Identifier",name:"step"},params:[{type:"Identifier",name:"getNext"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"next"},init:null}],kind:"var"},{type:"TryStatement",block:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"Identifier",name:"next"},right:{type:"CallExpression",callee:{type:"Identifier",name:"getNext"},arguments:[]}}}]},handler:{type:"CatchClause",param:{type:"Identifier",name:"e"},guard:null,body:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"Identifier",name:"reject"},arguments:[{type:"Identifier",name:"e"}]}},{type:"ReturnStatement",argument:null}]}},guardedHandlers:[],finalizer:null},{type:"IfStatement",test:{type:"MemberExpression",object:{type:"Identifier",name:"next"},property:{type:"Identifier",name:"done"},computed:false},consequent:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"Identifier",name:"resolve"},arguments:[{type:"MemberExpression",object:{type:"Identifier",name:"next"},property:{type:"Identifier",name:"value"},computed:false}]}},{type:"ReturnStatement",argument:null}]},alternate:null},{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Promise"},property:{type:"Identifier",name:"resolve"},computed:false},arguments:[{type:"MemberExpression",object:{type:"Identifier",name:"next"},property:{type:"Identifier",name:"value"},computed:false}]},property:{type:"Identifier",name:"then"},computed:false},arguments:[{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"v"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"Identifier",name:"step"},arguments:[{type:"FunctionExpression",id:null,params:[],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"gen"},property:{type:"Identifier",name:"next"},computed:false},arguments:[{type:"Identifier",name:"v"}]}}]},expression:false}]}}]},expression:false},{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"e"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"Identifier",name:"step"},arguments:[{type:"FunctionExpression",id:null,params:[],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"gen"},property:{type:"Literal",value:"throw"},computed:true},arguments:[{type:"Identifier",name:"e"}]}}]},expression:false}]}}]},expression:false}]}}]},expression:false},{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"Identifier",name:"step"},arguments:[{type:"FunctionExpression",id:null,params:[],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"gen"},property:{type:"Identifier",name:"next"},computed:false},arguments:[]}}]},expression:false}]}}]},expression:false}]}}]},expression:false}}]},expression:false}}]},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}]},"common-export-default-assign":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"module"},property:{type:"Identifier",name:"exports"},computed:false},right:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"assign"},computed:false},arguments:[{type:"MemberExpression",object:{type:"Identifier",name:"exports"},property:{type:"Literal",value:"default"},computed:true},{type:"Identifier",name:"exports"}]}}}]},"corejs-iterator":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"MemberExpression",object:{type:"Identifier",name:"CORE_ID"},property:{type:"Identifier",name:"$for"},computed:false},property:{type:"Identifier",name:"getIterator"},computed:false},arguments:[{type:"Identifier",name:"VALUE"}]}}]},"define-property":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"obj"},{type:"Identifier",name:"key"},{type:"Identifier",name:"value"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Object"},property:{type:"Identifier",name:"defineProperty"},computed:false},arguments:[{type:"Identifier",name:"obj"},{type:"Identifier",name:"key"},{type:"ObjectExpression",properties:[{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"value"},value:{type:"Identifier",name:"value"},kind:"init"},{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"enumerable"},value:{type:"Literal",value:true},kind:"init"},{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"configurable"},value:{type:"Literal",value:true},kind:"init"},{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"writable"},value:{type:"Literal",value:true},kind:"init"}]}]}}]},expression:false}}]},"exports-assign":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"exports"},property:{type:"Identifier",name:"KEY"},computed:false},right:{type:"Identifier",name:"VALUE"}}}]},"exports-default-module-override":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"Identifier",name:"exports"},right:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"module"},property:{type:"Identifier",name:"exports"},computed:false},right:{type:"Identifier",name:"VALUE"}}}}]},"exports-default-module":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"AssignmentExpression",operator:"=",left:{type:"MemberExpression",object:{type:"Identifier",name:"module"},property:{type:"Identifier",name:"exports"},computed:false},right:{type:"Identifier",name:"VALUE"}}}]},"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:[]}}]},"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":{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}}]},"sliced-to-array":{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"arr"},{type:"Identifier",name:"i"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"IfStatement",test:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"Array"},property:{type:"Identifier",name:"isArray"},computed:false},arguments:[{type:"Identifier",name:"arr"}]},consequent:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"Identifier",name:"arr"}}]},alternate:{type:"BlockStatement",body:[{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"_arr"},init:{type:"ArrayExpression",elements:[]}}],kind:"var"},{type:"ForStatement",init:{type:"VariableDeclaration",declarations:[{type:"VariableDeclarator",id:{type:"Identifier",name:"_iterator"},init:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"arr"},property:{type:"MemberExpression",object:{type:"Identifier",name:"Symbol"},property:{type:"Identifier",name:"iterator"},computed:false},computed:true},arguments:[]}},{type:"VariableDeclarator",id:{type:"Identifier",name:"_step"},init:null}],kind:"var"},test:{type:"UnaryExpression",operator:"!",prefix:true,argument:{type:"MemberExpression",object:{type:"AssignmentExpression",operator:"=",left:{type:"Identifier",name:"_step"},right:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"_iterator"},property:{type:"Identifier",name:"next"},computed:false},arguments:[]}},property:{type:"Identifier",name:"done"},computed:false}},update:null,body:{type:"BlockStatement",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"_arr"},property:{type:"Identifier",name:"push"},computed:false},arguments:[{type:"MemberExpression",object:{type:"Identifier",name:"_step"},property:{type:"Identifier",name:"value"},computed:false}]}},{type:"IfStatement",test:{type:"LogicalExpression",left:{type:"Identifier",name:"i"},operator:"&&",right:{type:"BinaryExpression",left:{type:"MemberExpression",object:{type:"Identifier",name:"_arr"},property:{type:"Identifier",name:"length"},computed:false},operator:"===",right:{type:"Identifier",name:"i"}}},consequent:{type:"BreakStatement",label:null},alternate:null}]}},{type:"ReturnStatement",argument:{type:"Identifier",name:"_arr"}}]}}]},expression:false}}]},system:{type:"Program",body:[{type:"ExpressionStatement",expression:{type:"CallExpression",callee:{type:"MemberExpression",object:{type:"Identifier",name:"System"},property:{type:"Identifier",name:"register"},computed:false},arguments:[{type:"Identifier",name:"MODULE_NAME"},{type:"Identifier",name:"MODULE_DEPENDENCIES"},{type:"FunctionExpression",id:null,params:[{type:"Identifier",name:"EXPORT_IDENTIFIER"}],defaults:[],rest:null,generator:false,body:{type:"BlockStatement",body:[{type:"ReturnStatement",argument:{type:"ObjectExpression",properties:[{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"setters"},value:{type:"Identifier",name:"SETTERS"},kind:"init"},{type:"Property",method:false,shorthand:false,computed:false,key:{type:"Identifier",name:"execute"},value:{type:"Identifier",name:"EXECUTE"},kind:"init"}]}}]},expression:false}]}}]},"tagged-template-literal":{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)}); |
packages/ringcentral-widgets/components/Eula/index.js | ringcentral/ringcentral-js-widget | import React from 'react';
import PropTypes from 'prop-types';
import i18n from './i18n';
function Eula(props) {
const {
currentLocale,
className,
onLinkClicked,
brandId,
useEulaAbbreviation,
dataSign,
} = props;
let labelId = useEulaAbbreviation ? 'eulaAbbr' : 'eula';
let link;
const isFr = currentLocale.substr(0, 2).toLowerCase() === 'fr';
switch (brandId) {
case '3420': // att
labelId = 'serviceTerms';
link = 'http://www.att.com/officeathandpolicy';
break;
case '7710': // bt
labelId = 'termsOfService';
link = 'https://business.bt.com/terms/';
break;
case '7310': // telus
labelId = 'serviceTerms';
link = isFr
? 'https://business.telus.com/fr/campaigns/business-connect-service-terms?INTCMP=VAN_businessconnect_fr_serviceterms'
: 'https://business.telus.com/en/support/global/legal/business-connect-service-terms?INTCMP=VAN_businessconnect_serviceterms';
break;
default:
link = 'https://www.ringcentral.com/legal/eulatos.html';
break;
}
return (
<a
className={className}
href={link}
rel="noopener noreferrer"
target="_blank"
onClick={onLinkClicked ? (e) => props.onLinkClicked(e, link) : null}
data-sign={dataSign}
>
{i18n.getString(labelId)}
</a>
);
}
Eula.propTypes = {
dataSign: PropTypes.string,
brandId: PropTypes.string.isRequired,
currentLocale: PropTypes.string.isRequired,
className: PropTypes.string,
onLinkClicked: PropTypes.func,
useEulaAbbreviation: PropTypes.bool,
};
Eula.defaultProps = {
dataSign: null,
className: '',
onLinkClicked() {},
useEulaAbbreviation: false,
};
export default Eula;
|
ajax/libs/yasqe/2.3.9/yasqe.bundled.min.js | rileyjshaw/cdnjs | !function(e){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=e();else if("function"==typeof define&&define.amd)define([],e);else{var t;"undefined"!=typeof window?t=window:"undefined"!=typeof global?t=global:"undefined"!=typeof self&&(t=self),t.YASQE=e()}}(function(){var e;return function t(e,i,r){function n(s,a){if(!i[s]){if(!e[s]){var l="function"==typeof require&&require;if(!a&&l)return l(s,!0);if(o)return o(s,!0);var u=new Error("Cannot find module '"+s+"'");throw u.code="MODULE_NOT_FOUND",u}var p=i[s]={exports:{}};e[s][0].call(p.exports,function(t){var i=e[s][1][t];return n(i?i:t)},p,p.exports,t,e,i,r)}return i[s].exports}for(var o="function"==typeof require&&require,s=0;s<r.length;s++)n(r[s]);return n}({1:[function(e,t){t.exports=e("./main.js")},{"./main.js":31}],2:[function(e){"use strict";var t=e("jquery");t.deparam=function(e,i){var r={},n={"true":!0,"false":!1,"null":null};t.each(e.replace(/\+/g," ").split("&"),function(e,o){var s,a=o.split("="),l=decodeURIComponent(a[0]),u=r,p=0,c=l.split("]["),d=c.length-1;if(/\[/.test(c[0])&&/\]$/.test(c[d])){c[d]=c[d].replace(/\]$/,"");c=c.shift().split("[").concat(c);d=c.length-1}else d=0;if(2===a.length){s=decodeURIComponent(a[1]);i&&(s=s&&!isNaN(s)?+s:"undefined"===s?void 0:void 0!==n[s]?n[s]:s);if(d)for(;d>=p;p++){l=""===c[p]?u.length:c[p];u=u[l]=d>p?u[l]||(c[p+1]&&isNaN(c[p+1])?{}:[]):s}else t.isArray(r[l])?r[l].push(s):r[l]=void 0!==r[l]?[r[l],s]:s}else l&&(r[l]=i?void 0:"")});return r}},{jquery:16}],3:[function(e,t){t.exports={table:{"*[&&,valueLogical]":{"&&":["[&&,valueLogical]","*[&&,valueLogical]"],AS:[],")":[],",":[],"||":[],";":[]},"*[,,expression]":{",":["[,,expression]","*[,,expression]"],")":[]},"*[,,objectPath]":{",":["[,,objectPath]","*[,,objectPath]"],".":[],";":[],"]":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"*[,,object]":{",":["[,,object]","*[,,object]"],".":[],";":[],"]":[],"}":[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[]},"*[/,pathEltOrInverse]":{"/":["[/,pathEltOrInverse]","*[/,pathEltOrInverse]"],"|":[],")":[],"(":[],"[":[],VAR1:[],VAR2:[],NIL:[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},"*[;,?[or([verbPath,verbSimple]),objectList]]":{";":["[;,?[or([verbPath,verbSimple]),objectList]]","*[;,?[or([verbPath,verbSimple]),objectList]]"],".":[],"]":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"*[;,?[verb,objectList]]":{";":["[;,?[verb,objectList]]","*[;,?[verb,objectList]]"],".":[],"]":[],"}":[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[]},"*[UNION,groupGraphPattern]":{UNION:["[UNION,groupGraphPattern]","*[UNION,groupGraphPattern]"],VAR1:[],VAR2:[],NIL:[],"(":[],"[":[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],".":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"*[graphPatternNotTriples,?.,?triplesBlock]":{"{":["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],OPTIONAL:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],MINUS:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],GRAPH:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],SERVICE:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],FILTER:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],BIND:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],VALUES:["[graphPatternNotTriples,?.,?triplesBlock]","*[graphPatternNotTriples,?.,?triplesBlock]"],"}":[]},"*[quadsNotTriples,?.,?triplesTemplate]":{GRAPH:["[quadsNotTriples,?.,?triplesTemplate]","*[quadsNotTriples,?.,?triplesTemplate]"],"}":[]},"*[|,pathOneInPropertySet]":{"|":["[|,pathOneInPropertySet]","*[|,pathOneInPropertySet]"],")":[]},"*[|,pathSequence]":{"|":["[|,pathSequence]","*[|,pathSequence]"],")":[],"(":[],"[":[],VAR1:[],VAR2:[],NIL:[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},"*[||,conditionalAndExpression]":{"||":["[||,conditionalAndExpression]","*[||,conditionalAndExpression]"],AS:[],")":[],",":[],";":[]},"*dataBlockValue":{UNDEF:["dataBlockValue","*dataBlockValue"],IRI_REF:["dataBlockValue","*dataBlockValue"],TRUE:["dataBlockValue","*dataBlockValue"],FALSE:["dataBlockValue","*dataBlockValue"],PNAME_LN:["dataBlockValue","*dataBlockValue"],PNAME_NS:["dataBlockValue","*dataBlockValue"],STRING_LITERAL1:["dataBlockValue","*dataBlockValue"],STRING_LITERAL2:["dataBlockValue","*dataBlockValue"],STRING_LITERAL_LONG1:["dataBlockValue","*dataBlockValue"],STRING_LITERAL_LONG2:["dataBlockValue","*dataBlockValue"],INTEGER:["dataBlockValue","*dataBlockValue"],DECIMAL:["dataBlockValue","*dataBlockValue"],DOUBLE:["dataBlockValue","*dataBlockValue"],INTEGER_POSITIVE:["dataBlockValue","*dataBlockValue"],DECIMAL_POSITIVE:["dataBlockValue","*dataBlockValue"],DOUBLE_POSITIVE:["dataBlockValue","*dataBlockValue"],INTEGER_NEGATIVE:["dataBlockValue","*dataBlockValue"],DECIMAL_NEGATIVE:["dataBlockValue","*dataBlockValue"],DOUBLE_NEGATIVE:["dataBlockValue","*dataBlockValue"],"}":[],")":[]},"*datasetClause":{FROM:["datasetClause","*datasetClause"],WHERE:[],"{":[]},"*describeDatasetClause":{FROM:["describeDatasetClause","*describeDatasetClause"],ORDER:[],HAVING:[],GROUP:[],LIMIT:[],OFFSET:[],WHERE:[],"{":[],VALUES:[],$:[]},"*graphNode":{"(":["graphNode","*graphNode"],"[":["graphNode","*graphNode"],VAR1:["graphNode","*graphNode"],VAR2:["graphNode","*graphNode"],NIL:["graphNode","*graphNode"],IRI_REF:["graphNode","*graphNode"],TRUE:["graphNode","*graphNode"],FALSE:["graphNode","*graphNode"],BLANK_NODE_LABEL:["graphNode","*graphNode"],ANON:["graphNode","*graphNode"],PNAME_LN:["graphNode","*graphNode"],PNAME_NS:["graphNode","*graphNode"],STRING_LITERAL1:["graphNode","*graphNode"],STRING_LITERAL2:["graphNode","*graphNode"],STRING_LITERAL_LONG1:["graphNode","*graphNode"],STRING_LITERAL_LONG2:["graphNode","*graphNode"],INTEGER:["graphNode","*graphNode"],DECIMAL:["graphNode","*graphNode"],DOUBLE:["graphNode","*graphNode"],INTEGER_POSITIVE:["graphNode","*graphNode"],DECIMAL_POSITIVE:["graphNode","*graphNode"],DOUBLE_POSITIVE:["graphNode","*graphNode"],INTEGER_NEGATIVE:["graphNode","*graphNode"],DECIMAL_NEGATIVE:["graphNode","*graphNode"],DOUBLE_NEGATIVE:["graphNode","*graphNode"],")":[]},"*graphNodePath":{"(":["graphNodePath","*graphNodePath"],"[":["graphNodePath","*graphNodePath"],VAR1:["graphNodePath","*graphNodePath"],VAR2:["graphNodePath","*graphNodePath"],NIL:["graphNodePath","*graphNodePath"],IRI_REF:["graphNodePath","*graphNodePath"],TRUE:["graphNodePath","*graphNodePath"],FALSE:["graphNodePath","*graphNodePath"],BLANK_NODE_LABEL:["graphNodePath","*graphNodePath"],ANON:["graphNodePath","*graphNodePath"],PNAME_LN:["graphNodePath","*graphNodePath"],PNAME_NS:["graphNodePath","*graphNodePath"],STRING_LITERAL1:["graphNodePath","*graphNodePath"],STRING_LITERAL2:["graphNodePath","*graphNodePath"],STRING_LITERAL_LONG1:["graphNodePath","*graphNodePath"],STRING_LITERAL_LONG2:["graphNodePath","*graphNodePath"],INTEGER:["graphNodePath","*graphNodePath"],DECIMAL:["graphNodePath","*graphNodePath"],DOUBLE:["graphNodePath","*graphNodePath"],INTEGER_POSITIVE:["graphNodePath","*graphNodePath"],DECIMAL_POSITIVE:["graphNodePath","*graphNodePath"],DOUBLE_POSITIVE:["graphNodePath","*graphNodePath"],INTEGER_NEGATIVE:["graphNodePath","*graphNodePath"],DECIMAL_NEGATIVE:["graphNodePath","*graphNodePath"],DOUBLE_NEGATIVE:["graphNodePath","*graphNodePath"],")":[]},"*groupCondition":{"(":["groupCondition","*groupCondition"],STR:["groupCondition","*groupCondition"],LANG:["groupCondition","*groupCondition"],LANGMATCHES:["groupCondition","*groupCondition"],DATATYPE:["groupCondition","*groupCondition"],BOUND:["groupCondition","*groupCondition"],IRI:["groupCondition","*groupCondition"],URI:["groupCondition","*groupCondition"],BNODE:["groupCondition","*groupCondition"],RAND:["groupCondition","*groupCondition"],ABS:["groupCondition","*groupCondition"],CEIL:["groupCondition","*groupCondition"],FLOOR:["groupCondition","*groupCondition"],ROUND:["groupCondition","*groupCondition"],CONCAT:["groupCondition","*groupCondition"],STRLEN:["groupCondition","*groupCondition"],UCASE:["groupCondition","*groupCondition"],LCASE:["groupCondition","*groupCondition"],ENCODE_FOR_URI:["groupCondition","*groupCondition"],CONTAINS:["groupCondition","*groupCondition"],STRSTARTS:["groupCondition","*groupCondition"],STRENDS:["groupCondition","*groupCondition"],STRBEFORE:["groupCondition","*groupCondition"],STRAFTER:["groupCondition","*groupCondition"],YEAR:["groupCondition","*groupCondition"],MONTH:["groupCondition","*groupCondition"],DAY:["groupCondition","*groupCondition"],HOURS:["groupCondition","*groupCondition"],MINUTES:["groupCondition","*groupCondition"],SECONDS:["groupCondition","*groupCondition"],TIMEZONE:["groupCondition","*groupCondition"],TZ:["groupCondition","*groupCondition"],NOW:["groupCondition","*groupCondition"],UUID:["groupCondition","*groupCondition"],STRUUID:["groupCondition","*groupCondition"],MD5:["groupCondition","*groupCondition"],SHA1:["groupCondition","*groupCondition"],SHA256:["groupCondition","*groupCondition"],SHA384:["groupCondition","*groupCondition"],SHA512:["groupCondition","*groupCondition"],COALESCE:["groupCondition","*groupCondition"],IF:["groupCondition","*groupCondition"],STRLANG:["groupCondition","*groupCondition"],STRDT:["groupCondition","*groupCondition"],SAMETERM:["groupCondition","*groupCondition"],ISIRI:["groupCondition","*groupCondition"],ISURI:["groupCondition","*groupCondition"],ISBLANK:["groupCondition","*groupCondition"],ISLITERAL:["groupCondition","*groupCondition"],ISNUMERIC:["groupCondition","*groupCondition"],VAR1:["groupCondition","*groupCondition"],VAR2:["groupCondition","*groupCondition"],SUBSTR:["groupCondition","*groupCondition"],REPLACE:["groupCondition","*groupCondition"],REGEX:["groupCondition","*groupCondition"],EXISTS:["groupCondition","*groupCondition"],NOT:["groupCondition","*groupCondition"],IRI_REF:["groupCondition","*groupCondition"],PNAME_LN:["groupCondition","*groupCondition"],PNAME_NS:["groupCondition","*groupCondition"],VALUES:[],LIMIT:[],OFFSET:[],ORDER:[],HAVING:[],$:[],"}":[]},"*havingCondition":{"(":["havingCondition","*havingCondition"],STR:["havingCondition","*havingCondition"],LANG:["havingCondition","*havingCondition"],LANGMATCHES:["havingCondition","*havingCondition"],DATATYPE:["havingCondition","*havingCondition"],BOUND:["havingCondition","*havingCondition"],IRI:["havingCondition","*havingCondition"],URI:["havingCondition","*havingCondition"],BNODE:["havingCondition","*havingCondition"],RAND:["havingCondition","*havingCondition"],ABS:["havingCondition","*havingCondition"],CEIL:["havingCondition","*havingCondition"],FLOOR:["havingCondition","*havingCondition"],ROUND:["havingCondition","*havingCondition"],CONCAT:["havingCondition","*havingCondition"],STRLEN:["havingCondition","*havingCondition"],UCASE:["havingCondition","*havingCondition"],LCASE:["havingCondition","*havingCondition"],ENCODE_FOR_URI:["havingCondition","*havingCondition"],CONTAINS:["havingCondition","*havingCondition"],STRSTARTS:["havingCondition","*havingCondition"],STRENDS:["havingCondition","*havingCondition"],STRBEFORE:["havingCondition","*havingCondition"],STRAFTER:["havingCondition","*havingCondition"],YEAR:["havingCondition","*havingCondition"],MONTH:["havingCondition","*havingCondition"],DAY:["havingCondition","*havingCondition"],HOURS:["havingCondition","*havingCondition"],MINUTES:["havingCondition","*havingCondition"],SECONDS:["havingCondition","*havingCondition"],TIMEZONE:["havingCondition","*havingCondition"],TZ:["havingCondition","*havingCondition"],NOW:["havingCondition","*havingCondition"],UUID:["havingCondition","*havingCondition"],STRUUID:["havingCondition","*havingCondition"],MD5:["havingCondition","*havingCondition"],SHA1:["havingCondition","*havingCondition"],SHA256:["havingCondition","*havingCondition"],SHA384:["havingCondition","*havingCondition"],SHA512:["havingCondition","*havingCondition"],COALESCE:["havingCondition","*havingCondition"],IF:["havingCondition","*havingCondition"],STRLANG:["havingCondition","*havingCondition"],STRDT:["havingCondition","*havingCondition"],SAMETERM:["havingCondition","*havingCondition"],ISIRI:["havingCondition","*havingCondition"],ISURI:["havingCondition","*havingCondition"],ISBLANK:["havingCondition","*havingCondition"],ISLITERAL:["havingCondition","*havingCondition"],ISNUMERIC:["havingCondition","*havingCondition"],SUBSTR:["havingCondition","*havingCondition"],REPLACE:["havingCondition","*havingCondition"],REGEX:["havingCondition","*havingCondition"],EXISTS:["havingCondition","*havingCondition"],NOT:["havingCondition","*havingCondition"],IRI_REF:["havingCondition","*havingCondition"],PNAME_LN:["havingCondition","*havingCondition"],PNAME_NS:["havingCondition","*havingCondition"],VALUES:[],LIMIT:[],OFFSET:[],ORDER:[],$:[],"}":[]},"*or([[ (,*dataBlockValue,)],NIL])":{"(":["or([[ (,*dataBlockValue,)],NIL])","*or([[ (,*dataBlockValue,)],NIL])"],NIL:["or([[ (,*dataBlockValue,)],NIL])","*or([[ (,*dataBlockValue,)],NIL])"],"}":[]},"*or([[*,unaryExpression],[/,unaryExpression]])":{"*":["or([[*,unaryExpression],[/,unaryExpression]])","*or([[*,unaryExpression],[/,unaryExpression]])"],"/":["or([[*,unaryExpression],[/,unaryExpression]])","*or([[*,unaryExpression],[/,unaryExpression]])"],AS:[],")":[],",":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],"+":[],"-":[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],";":[]},"*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])":{"+":["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],"-":["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER_POSITIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL_POSITIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE_POSITIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER_NEGATIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL_NEGATIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE_NEGATIVE:["or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],AS:[],")":[],",":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],";":[]},"*or([baseDecl,prefixDecl])":{BASE:["or([baseDecl,prefixDecl])","*or([baseDecl,prefixDecl])"],PREFIX:["or([baseDecl,prefixDecl])","*or([baseDecl,prefixDecl])"],$:[],CONSTRUCT:[],DESCRIBE:[],ASK:[],INSERT:[],DELETE:[],SELECT:[],LOAD:[],CLEAR:[],DROP:[],ADD:[],MOVE:[],COPY:[],CREATE:[],WITH:[]},"*or([var,[ (,expression,AS,var,)]])":{"(":["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],VAR1:["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],VAR2:["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],WHERE:[],"{":[],FROM:[]},"*orderCondition":{ASC:["orderCondition","*orderCondition"],DESC:["orderCondition","*orderCondition"],VAR1:["orderCondition","*orderCondition"],VAR2:["orderCondition","*orderCondition"],"(":["orderCondition","*orderCondition"],STR:["orderCondition","*orderCondition"],LANG:["orderCondition","*orderCondition"],LANGMATCHES:["orderCondition","*orderCondition"],DATATYPE:["orderCondition","*orderCondition"],BOUND:["orderCondition","*orderCondition"],IRI:["orderCondition","*orderCondition"],URI:["orderCondition","*orderCondition"],BNODE:["orderCondition","*orderCondition"],RAND:["orderCondition","*orderCondition"],ABS:["orderCondition","*orderCondition"],CEIL:["orderCondition","*orderCondition"],FLOOR:["orderCondition","*orderCondition"],ROUND:["orderCondition","*orderCondition"],CONCAT:["orderCondition","*orderCondition"],STRLEN:["orderCondition","*orderCondition"],UCASE:["orderCondition","*orderCondition"],LCASE:["orderCondition","*orderCondition"],ENCODE_FOR_URI:["orderCondition","*orderCondition"],CONTAINS:["orderCondition","*orderCondition"],STRSTARTS:["orderCondition","*orderCondition"],STRENDS:["orderCondition","*orderCondition"],STRBEFORE:["orderCondition","*orderCondition"],STRAFTER:["orderCondition","*orderCondition"],YEAR:["orderCondition","*orderCondition"],MONTH:["orderCondition","*orderCondition"],DAY:["orderCondition","*orderCondition"],HOURS:["orderCondition","*orderCondition"],MINUTES:["orderCondition","*orderCondition"],SECONDS:["orderCondition","*orderCondition"],TIMEZONE:["orderCondition","*orderCondition"],TZ:["orderCondition","*orderCondition"],NOW:["orderCondition","*orderCondition"],UUID:["orderCondition","*orderCondition"],STRUUID:["orderCondition","*orderCondition"],MD5:["orderCondition","*orderCondition"],SHA1:["orderCondition","*orderCondition"],SHA256:["orderCondition","*orderCondition"],SHA384:["orderCondition","*orderCondition"],SHA512:["orderCondition","*orderCondition"],COALESCE:["orderCondition","*orderCondition"],IF:["orderCondition","*orderCondition"],STRLANG:["orderCondition","*orderCondition"],STRDT:["orderCondition","*orderCondition"],SAMETERM:["orderCondition","*orderCondition"],ISIRI:["orderCondition","*orderCondition"],ISURI:["orderCondition","*orderCondition"],ISBLANK:["orderCondition","*orderCondition"],ISLITERAL:["orderCondition","*orderCondition"],ISNUMERIC:["orderCondition","*orderCondition"],SUBSTR:["orderCondition","*orderCondition"],REPLACE:["orderCondition","*orderCondition"],REGEX:["orderCondition","*orderCondition"],EXISTS:["orderCondition","*orderCondition"],NOT:["orderCondition","*orderCondition"],IRI_REF:["orderCondition","*orderCondition"],PNAME_LN:["orderCondition","*orderCondition"],PNAME_NS:["orderCondition","*orderCondition"],VALUES:[],LIMIT:[],OFFSET:[],$:[],"}":[]},"*usingClause":{USING:["usingClause","*usingClause"],WHERE:[]},"*var":{VAR1:["var","*var"],VAR2:["var","*var"],")":[]},"*varOrIRIref":{VAR1:["varOrIRIref","*varOrIRIref"],VAR2:["varOrIRIref","*varOrIRIref"],IRI_REF:["varOrIRIref","*varOrIRIref"],PNAME_LN:["varOrIRIref","*varOrIRIref"],PNAME_NS:["varOrIRIref","*varOrIRIref"],ORDER:[],HAVING:[],GROUP:[],LIMIT:[],OFFSET:[],WHERE:[],"{":[],FROM:[],VALUES:[],$:[]},"+graphNode":{"(":["graphNode","*graphNode"],"[":["graphNode","*graphNode"],VAR1:["graphNode","*graphNode"],VAR2:["graphNode","*graphNode"],NIL:["graphNode","*graphNode"],IRI_REF:["graphNode","*graphNode"],TRUE:["graphNode","*graphNode"],FALSE:["graphNode","*graphNode"],BLANK_NODE_LABEL:["graphNode","*graphNode"],ANON:["graphNode","*graphNode"],PNAME_LN:["graphNode","*graphNode"],PNAME_NS:["graphNode","*graphNode"],STRING_LITERAL1:["graphNode","*graphNode"],STRING_LITERAL2:["graphNode","*graphNode"],STRING_LITERAL_LONG1:["graphNode","*graphNode"],STRING_LITERAL_LONG2:["graphNode","*graphNode"],INTEGER:["graphNode","*graphNode"],DECIMAL:["graphNode","*graphNode"],DOUBLE:["graphNode","*graphNode"],INTEGER_POSITIVE:["graphNode","*graphNode"],DECIMAL_POSITIVE:["graphNode","*graphNode"],DOUBLE_POSITIVE:["graphNode","*graphNode"],INTEGER_NEGATIVE:["graphNode","*graphNode"],DECIMAL_NEGATIVE:["graphNode","*graphNode"],DOUBLE_NEGATIVE:["graphNode","*graphNode"]},"+graphNodePath":{"(":["graphNodePath","*graphNodePath"],"[":["graphNodePath","*graphNodePath"],VAR1:["graphNodePath","*graphNodePath"],VAR2:["graphNodePath","*graphNodePath"],NIL:["graphNodePath","*graphNodePath"],IRI_REF:["graphNodePath","*graphNodePath"],TRUE:["graphNodePath","*graphNodePath"],FALSE:["graphNodePath","*graphNodePath"],BLANK_NODE_LABEL:["graphNodePath","*graphNodePath"],ANON:["graphNodePath","*graphNodePath"],PNAME_LN:["graphNodePath","*graphNodePath"],PNAME_NS:["graphNodePath","*graphNodePath"],STRING_LITERAL1:["graphNodePath","*graphNodePath"],STRING_LITERAL2:["graphNodePath","*graphNodePath"],STRING_LITERAL_LONG1:["graphNodePath","*graphNodePath"],STRING_LITERAL_LONG2:["graphNodePath","*graphNodePath"],INTEGER:["graphNodePath","*graphNodePath"],DECIMAL:["graphNodePath","*graphNodePath"],DOUBLE:["graphNodePath","*graphNodePath"],INTEGER_POSITIVE:["graphNodePath","*graphNodePath"],DECIMAL_POSITIVE:["graphNodePath","*graphNodePath"],DOUBLE_POSITIVE:["graphNodePath","*graphNodePath"],INTEGER_NEGATIVE:["graphNodePath","*graphNodePath"],DECIMAL_NEGATIVE:["graphNodePath","*graphNodePath"],DOUBLE_NEGATIVE:["graphNodePath","*graphNodePath"]},"+groupCondition":{"(":["groupCondition","*groupCondition"],STR:["groupCondition","*groupCondition"],LANG:["groupCondition","*groupCondition"],LANGMATCHES:["groupCondition","*groupCondition"],DATATYPE:["groupCondition","*groupCondition"],BOUND:["groupCondition","*groupCondition"],IRI:["groupCondition","*groupCondition"],URI:["groupCondition","*groupCondition"],BNODE:["groupCondition","*groupCondition"],RAND:["groupCondition","*groupCondition"],ABS:["groupCondition","*groupCondition"],CEIL:["groupCondition","*groupCondition"],FLOOR:["groupCondition","*groupCondition"],ROUND:["groupCondition","*groupCondition"],CONCAT:["groupCondition","*groupCondition"],STRLEN:["groupCondition","*groupCondition"],UCASE:["groupCondition","*groupCondition"],LCASE:["groupCondition","*groupCondition"],ENCODE_FOR_URI:["groupCondition","*groupCondition"],CONTAINS:["groupCondition","*groupCondition"],STRSTARTS:["groupCondition","*groupCondition"],STRENDS:["groupCondition","*groupCondition"],STRBEFORE:["groupCondition","*groupCondition"],STRAFTER:["groupCondition","*groupCondition"],YEAR:["groupCondition","*groupCondition"],MONTH:["groupCondition","*groupCondition"],DAY:["groupCondition","*groupCondition"],HOURS:["groupCondition","*groupCondition"],MINUTES:["groupCondition","*groupCondition"],SECONDS:["groupCondition","*groupCondition"],TIMEZONE:["groupCondition","*groupCondition"],TZ:["groupCondition","*groupCondition"],NOW:["groupCondition","*groupCondition"],UUID:["groupCondition","*groupCondition"],STRUUID:["groupCondition","*groupCondition"],MD5:["groupCondition","*groupCondition"],SHA1:["groupCondition","*groupCondition"],SHA256:["groupCondition","*groupCondition"],SHA384:["groupCondition","*groupCondition"],SHA512:["groupCondition","*groupCondition"],COALESCE:["groupCondition","*groupCondition"],IF:["groupCondition","*groupCondition"],STRLANG:["groupCondition","*groupCondition"],STRDT:["groupCondition","*groupCondition"],SAMETERM:["groupCondition","*groupCondition"],ISIRI:["groupCondition","*groupCondition"],ISURI:["groupCondition","*groupCondition"],ISBLANK:["groupCondition","*groupCondition"],ISLITERAL:["groupCondition","*groupCondition"],ISNUMERIC:["groupCondition","*groupCondition"],VAR1:["groupCondition","*groupCondition"],VAR2:["groupCondition","*groupCondition"],SUBSTR:["groupCondition","*groupCondition"],REPLACE:["groupCondition","*groupCondition"],REGEX:["groupCondition","*groupCondition"],EXISTS:["groupCondition","*groupCondition"],NOT:["groupCondition","*groupCondition"],IRI_REF:["groupCondition","*groupCondition"],PNAME_LN:["groupCondition","*groupCondition"],PNAME_NS:["groupCondition","*groupCondition"]},"+havingCondition":{"(":["havingCondition","*havingCondition"],STR:["havingCondition","*havingCondition"],LANG:["havingCondition","*havingCondition"],LANGMATCHES:["havingCondition","*havingCondition"],DATATYPE:["havingCondition","*havingCondition"],BOUND:["havingCondition","*havingCondition"],IRI:["havingCondition","*havingCondition"],URI:["havingCondition","*havingCondition"],BNODE:["havingCondition","*havingCondition"],RAND:["havingCondition","*havingCondition"],ABS:["havingCondition","*havingCondition"],CEIL:["havingCondition","*havingCondition"],FLOOR:["havingCondition","*havingCondition"],ROUND:["havingCondition","*havingCondition"],CONCAT:["havingCondition","*havingCondition"],STRLEN:["havingCondition","*havingCondition"],UCASE:["havingCondition","*havingCondition"],LCASE:["havingCondition","*havingCondition"],ENCODE_FOR_URI:["havingCondition","*havingCondition"],CONTAINS:["havingCondition","*havingCondition"],STRSTARTS:["havingCondition","*havingCondition"],STRENDS:["havingCondition","*havingCondition"],STRBEFORE:["havingCondition","*havingCondition"],STRAFTER:["havingCondition","*havingCondition"],YEAR:["havingCondition","*havingCondition"],MONTH:["havingCondition","*havingCondition"],DAY:["havingCondition","*havingCondition"],HOURS:["havingCondition","*havingCondition"],MINUTES:["havingCondition","*havingCondition"],SECONDS:["havingCondition","*havingCondition"],TIMEZONE:["havingCondition","*havingCondition"],TZ:["havingCondition","*havingCondition"],NOW:["havingCondition","*havingCondition"],UUID:["havingCondition","*havingCondition"],STRUUID:["havingCondition","*havingCondition"],MD5:["havingCondition","*havingCondition"],SHA1:["havingCondition","*havingCondition"],SHA256:["havingCondition","*havingCondition"],SHA384:["havingCondition","*havingCondition"],SHA512:["havingCondition","*havingCondition"],COALESCE:["havingCondition","*havingCondition"],IF:["havingCondition","*havingCondition"],STRLANG:["havingCondition","*havingCondition"],STRDT:["havingCondition","*havingCondition"],SAMETERM:["havingCondition","*havingCondition"],ISIRI:["havingCondition","*havingCondition"],ISURI:["havingCondition","*havingCondition"],ISBLANK:["havingCondition","*havingCondition"],ISLITERAL:["havingCondition","*havingCondition"],ISNUMERIC:["havingCondition","*havingCondition"],SUBSTR:["havingCondition","*havingCondition"],REPLACE:["havingCondition","*havingCondition"],REGEX:["havingCondition","*havingCondition"],EXISTS:["havingCondition","*havingCondition"],NOT:["havingCondition","*havingCondition"],IRI_REF:["havingCondition","*havingCondition"],PNAME_LN:["havingCondition","*havingCondition"],PNAME_NS:["havingCondition","*havingCondition"]},"+or([var,[ (,expression,AS,var,)]])":{"(":["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],VAR1:["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"],VAR2:["or([var,[ (,expression,AS,var,)]])","*or([var,[ (,expression,AS,var,)]])"]},"+orderCondition":{ASC:["orderCondition","*orderCondition"],DESC:["orderCondition","*orderCondition"],VAR1:["orderCondition","*orderCondition"],VAR2:["orderCondition","*orderCondition"],"(":["orderCondition","*orderCondition"],STR:["orderCondition","*orderCondition"],LANG:["orderCondition","*orderCondition"],LANGMATCHES:["orderCondition","*orderCondition"],DATATYPE:["orderCondition","*orderCondition"],BOUND:["orderCondition","*orderCondition"],IRI:["orderCondition","*orderCondition"],URI:["orderCondition","*orderCondition"],BNODE:["orderCondition","*orderCondition"],RAND:["orderCondition","*orderCondition"],ABS:["orderCondition","*orderCondition"],CEIL:["orderCondition","*orderCondition"],FLOOR:["orderCondition","*orderCondition"],ROUND:["orderCondition","*orderCondition"],CONCAT:["orderCondition","*orderCondition"],STRLEN:["orderCondition","*orderCondition"],UCASE:["orderCondition","*orderCondition"],LCASE:["orderCondition","*orderCondition"],ENCODE_FOR_URI:["orderCondition","*orderCondition"],CONTAINS:["orderCondition","*orderCondition"],STRSTARTS:["orderCondition","*orderCondition"],STRENDS:["orderCondition","*orderCondition"],STRBEFORE:["orderCondition","*orderCondition"],STRAFTER:["orderCondition","*orderCondition"],YEAR:["orderCondition","*orderCondition"],MONTH:["orderCondition","*orderCondition"],DAY:["orderCondition","*orderCondition"],HOURS:["orderCondition","*orderCondition"],MINUTES:["orderCondition","*orderCondition"],SECONDS:["orderCondition","*orderCondition"],TIMEZONE:["orderCondition","*orderCondition"],TZ:["orderCondition","*orderCondition"],NOW:["orderCondition","*orderCondition"],UUID:["orderCondition","*orderCondition"],STRUUID:["orderCondition","*orderCondition"],MD5:["orderCondition","*orderCondition"],SHA1:["orderCondition","*orderCondition"],SHA256:["orderCondition","*orderCondition"],SHA384:["orderCondition","*orderCondition"],SHA512:["orderCondition","*orderCondition"],COALESCE:["orderCondition","*orderCondition"],IF:["orderCondition","*orderCondition"],STRLANG:["orderCondition","*orderCondition"],STRDT:["orderCondition","*orderCondition"],SAMETERM:["orderCondition","*orderCondition"],ISIRI:["orderCondition","*orderCondition"],ISURI:["orderCondition","*orderCondition"],ISBLANK:["orderCondition","*orderCondition"],ISLITERAL:["orderCondition","*orderCondition"],ISNUMERIC:["orderCondition","*orderCondition"],SUBSTR:["orderCondition","*orderCondition"],REPLACE:["orderCondition","*orderCondition"],REGEX:["orderCondition","*orderCondition"],EXISTS:["orderCondition","*orderCondition"],NOT:["orderCondition","*orderCondition"],IRI_REF:["orderCondition","*orderCondition"],PNAME_LN:["orderCondition","*orderCondition"],PNAME_NS:["orderCondition","*orderCondition"]},"+varOrIRIref":{VAR1:["varOrIRIref","*varOrIRIref"],VAR2:["varOrIRIref","*varOrIRIref"],IRI_REF:["varOrIRIref","*varOrIRIref"],PNAME_LN:["varOrIRIref","*varOrIRIref"],PNAME_NS:["varOrIRIref","*varOrIRIref"]},"?.":{".":["."],VAR1:[],VAR2:[],NIL:[],"(":[],"[":[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"?DISTINCT":{DISTINCT:["DISTINCT"],"!":[],"+":[],"-":[],VAR1:[],VAR2:[],"(":[],STR:[],LANG:[],LANGMATCHES:[],DATATYPE:[],BOUND:[],IRI:[],URI:[],BNODE:[],RAND:[],ABS:[],CEIL:[],FLOOR:[],ROUND:[],CONCAT:[],STRLEN:[],UCASE:[],LCASE:[],ENCODE_FOR_URI:[],CONTAINS:[],STRSTARTS:[],STRENDS:[],STRBEFORE:[],STRAFTER:[],YEAR:[],MONTH:[],DAY:[],HOURS:[],MINUTES:[],SECONDS:[],TIMEZONE:[],TZ:[],NOW:[],UUID:[],STRUUID:[],MD5:[],SHA1:[],SHA256:[],SHA384:[],SHA512:[],COALESCE:[],IF:[],STRLANG:[],STRDT:[],SAMETERM:[],ISIRI:[],ISURI:[],ISBLANK:[],ISLITERAL:[],ISNUMERIC:[],TRUE:[],FALSE:[],COUNT:[],SUM:[],MIN:[],MAX:[],AVG:[],SAMPLE:[],GROUP_CONCAT:[],SUBSTR:[],REPLACE:[],REGEX:[],EXISTS:[],NOT:[],IRI_REF:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],PNAME_LN:[],PNAME_NS:[],"*":[]},"?GRAPH":{GRAPH:["GRAPH"],IRI_REF:[],PNAME_LN:[],PNAME_NS:[]},"?SILENT":{SILENT:["SILENT"],VAR1:[],VAR2:[],IRI_REF:[],PNAME_LN:[],PNAME_NS:[]},"?SILENT_1":{SILENT:["SILENT"],IRI_REF:[],PNAME_LN:[],PNAME_NS:[]},"?SILENT_2":{SILENT:["SILENT"],GRAPH:[],DEFAULT:[],NAMED:[],ALL:[]},"?SILENT_3":{SILENT:["SILENT"],GRAPH:[]},"?SILENT_4":{SILENT:["SILENT"],DEFAULT:[],GRAPH:[],IRI_REF:[],PNAME_LN:[],PNAME_NS:[]},"?WHERE":{WHERE:["WHERE"],"{":[]},"?[,,expression]":{",":["[,,expression]"],")":[]},"?[.,?constructTriples]":{".":["[.,?constructTriples]"],"}":[]},"?[.,?triplesBlock]":{".":["[.,?triplesBlock]"],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"?[.,?triplesTemplate]":{".":["[.,?triplesTemplate]"],"}":[],GRAPH:[]},"?[;,SEPARATOR,=,string]":{";":["[;,SEPARATOR,=,string]"],")":[]},"?[;,update]":{";":["[;,update]"],$:[]},"?[AS,var]":{AS:["[AS,var]"],")":[]},"?[INTO,graphRef]":{INTO:["[INTO,graphRef]"],";":[],$:[]},"?[or([verbPath,verbSimple]),objectList]":{VAR1:["[or([verbPath,verbSimple]),objectList]"],VAR2:["[or([verbPath,verbSimple]),objectList]"],"^":["[or([verbPath,verbSimple]),objectList]"],a:["[or([verbPath,verbSimple]),objectList]"],"!":["[or([verbPath,verbSimple]),objectList]"],"(":["[or([verbPath,verbSimple]),objectList]"],IRI_REF:["[or([verbPath,verbSimple]),objectList]"],PNAME_LN:["[or([verbPath,verbSimple]),objectList]"],PNAME_NS:["[or([verbPath,verbSimple]),objectList]"],";":[],".":[],"]":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"?[pathOneInPropertySet,*[|,pathOneInPropertySet]]":{a:["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],"^":["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],IRI_REF:["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],PNAME_LN:["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],PNAME_NS:["[pathOneInPropertySet,*[|,pathOneInPropertySet]]"],")":[]},"?[update1,?[;,update]]":{INSERT:["[update1,?[;,update]]"],DELETE:["[update1,?[;,update]]"],LOAD:["[update1,?[;,update]]"],CLEAR:["[update1,?[;,update]]"],DROP:["[update1,?[;,update]]"],ADD:["[update1,?[;,update]]"],MOVE:["[update1,?[;,update]]"],COPY:["[update1,?[;,update]]"],CREATE:["[update1,?[;,update]]"],WITH:["[update1,?[;,update]]"],$:[]},"?[verb,objectList]":{a:["[verb,objectList]"],VAR1:["[verb,objectList]"],VAR2:["[verb,objectList]"],IRI_REF:["[verb,objectList]"],PNAME_LN:["[verb,objectList]"],PNAME_NS:["[verb,objectList]"],";":[],".":[],"]":[],"}":[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[]},"?argList":{NIL:["argList"],"(":["argList"],AS:[],")":[],",":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],"+":[],"-":[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],"*":[],"/":[],";":[]},"?constructTriples":{VAR1:["constructTriples"],VAR2:["constructTriples"],NIL:["constructTriples"],"(":["constructTriples"],"[":["constructTriples"],IRI_REF:["constructTriples"],TRUE:["constructTriples"],FALSE:["constructTriples"],BLANK_NODE_LABEL:["constructTriples"],ANON:["constructTriples"],PNAME_LN:["constructTriples"],PNAME_NS:["constructTriples"],STRING_LITERAL1:["constructTriples"],STRING_LITERAL2:["constructTriples"],STRING_LITERAL_LONG1:["constructTriples"],STRING_LITERAL_LONG2:["constructTriples"],INTEGER:["constructTriples"],DECIMAL:["constructTriples"],DOUBLE:["constructTriples"],INTEGER_POSITIVE:["constructTriples"],DECIMAL_POSITIVE:["constructTriples"],DOUBLE_POSITIVE:["constructTriples"],INTEGER_NEGATIVE:["constructTriples"],DECIMAL_NEGATIVE:["constructTriples"],DOUBLE_NEGATIVE:["constructTriples"],"}":[]},"?groupClause":{GROUP:["groupClause"],VALUES:[],LIMIT:[],OFFSET:[],ORDER:[],HAVING:[],$:[],"}":[]},"?havingClause":{HAVING:["havingClause"],VALUES:[],LIMIT:[],OFFSET:[],ORDER:[],$:[],"}":[]},"?insertClause":{INSERT:["insertClause"],WHERE:[],USING:[]},"?limitClause":{LIMIT:["limitClause"],VALUES:[],$:[],"}":[]},"?limitOffsetClauses":{LIMIT:["limitOffsetClauses"],OFFSET:["limitOffsetClauses"],VALUES:[],$:[],"}":[]},"?offsetClause":{OFFSET:["offsetClause"],VALUES:[],$:[],"}":[]},"?or([DISTINCT,REDUCED])":{DISTINCT:["or([DISTINCT,REDUCED])"],REDUCED:["or([DISTINCT,REDUCED])"],"*":[],"(":[],VAR1:[],VAR2:[]},"?or([LANGTAG,[^^,iriRef]])":{LANGTAG:["or([LANGTAG,[^^,iriRef]])"],"^^":["or([LANGTAG,[^^,iriRef]])"],UNDEF:[],IRI_REF:[],TRUE:[],FALSE:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],a:[],VAR1:[],VAR2:[],"^":[],"!":[],"(":[],".":[],";":[],",":[],AS:[],")":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],"+":[],"-":[],"*":[],"/":[],"}":[],"[":[],NIL:[],BLANK_NODE_LABEL:[],ANON:[],"]":[],GRAPH:[],"{":[],OPTIONAL:[],MINUS:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[]},"?or([[*,unaryExpression],[/,unaryExpression]])":{"*":["or([[*,unaryExpression],[/,unaryExpression]])"],"/":["or([[*,unaryExpression],[/,unaryExpression]])"],"+":[],"-":[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[],AS:[],")":[],",":[],"||":[],"&&":[],"=":[],"!=":[],"<":[],">":[],"<=":[],">=":[],IN:[],NOT:[],";":[]},"?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])":{"=":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"!=":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"<":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],">":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"<=":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],">=":["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],IN:["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],NOT:["or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],AS:[],")":[],",":[],"||":[],"&&":[],";":[]},"?orderClause":{ORDER:["orderClause"],VALUES:[],LIMIT:[],OFFSET:[],$:[],"}":[]},"?pathMod":{"*":["pathMod"],"?":["pathMod"],"+":["pathMod"],"{":["pathMod"],"|":[],"/":[],")":[],"(":[],"[":[],VAR1:[],VAR2:[],NIL:[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},"?triplesBlock":{VAR1:["triplesBlock"],VAR2:["triplesBlock"],NIL:["triplesBlock"],"(":["triplesBlock"],"[":["triplesBlock"],IRI_REF:["triplesBlock"],TRUE:["triplesBlock"],FALSE:["triplesBlock"],BLANK_NODE_LABEL:["triplesBlock"],ANON:["triplesBlock"],PNAME_LN:["triplesBlock"],PNAME_NS:["triplesBlock"],STRING_LITERAL1:["triplesBlock"],STRING_LITERAL2:["triplesBlock"],STRING_LITERAL_LONG1:["triplesBlock"],STRING_LITERAL_LONG2:["triplesBlock"],INTEGER:["triplesBlock"],DECIMAL:["triplesBlock"],DOUBLE:["triplesBlock"],INTEGER_POSITIVE:["triplesBlock"],DECIMAL_POSITIVE:["triplesBlock"],DOUBLE_POSITIVE:["triplesBlock"],INTEGER_NEGATIVE:["triplesBlock"],DECIMAL_NEGATIVE:["triplesBlock"],DOUBLE_NEGATIVE:["triplesBlock"],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},"?triplesTemplate":{VAR1:["triplesTemplate"],VAR2:["triplesTemplate"],NIL:["triplesTemplate"],"(":["triplesTemplate"],"[":["triplesTemplate"],IRI_REF:["triplesTemplate"],TRUE:["triplesTemplate"],FALSE:["triplesTemplate"],BLANK_NODE_LABEL:["triplesTemplate"],ANON:["triplesTemplate"],PNAME_LN:["triplesTemplate"],PNAME_NS:["triplesTemplate"],STRING_LITERAL1:["triplesTemplate"],STRING_LITERAL2:["triplesTemplate"],STRING_LITERAL_LONG1:["triplesTemplate"],STRING_LITERAL_LONG2:["triplesTemplate"],INTEGER:["triplesTemplate"],DECIMAL:["triplesTemplate"],DOUBLE:["triplesTemplate"],INTEGER_POSITIVE:["triplesTemplate"],DECIMAL_POSITIVE:["triplesTemplate"],DOUBLE_POSITIVE:["triplesTemplate"],INTEGER_NEGATIVE:["triplesTemplate"],DECIMAL_NEGATIVE:["triplesTemplate"],DOUBLE_NEGATIVE:["triplesTemplate"],"}":[],GRAPH:[]},"?whereClause":{WHERE:["whereClause"],"{":["whereClause"],ORDER:[],HAVING:[],GROUP:[],LIMIT:[],OFFSET:[],VALUES:[],$:[]},"[ (,*dataBlockValue,)]":{"(":["(","*dataBlockValue",")"]},"[ (,*var,)]":{"(":["(","*var",")"]},"[ (,expression,)]":{"(":["(","expression",")"]},"[ (,expression,AS,var,)]":{"(":["(","expression","AS","var",")"]},"[!=,numericExpression]":{"!=":["!=","numericExpression"]},"[&&,valueLogical]":{"&&":["&&","valueLogical"]},"[*,unaryExpression]":{"*":["*","unaryExpression"]},"[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]":{WHERE:["*datasetClause","WHERE","{","?triplesTemplate","}","solutionModifier"],FROM:["*datasetClause","WHERE","{","?triplesTemplate","}","solutionModifier"]},"[+,multiplicativeExpression]":{"+":["+","multiplicativeExpression"]},"[,,expression]":{",":[",","expression"]},"[,,integer,}]":{",":[",","integer","}"]},"[,,objectPath]":{",":[",","objectPath"]},"[,,object]":{",":[",","object"]},"[,,or([},[integer,}]])]":{",":[",","or([},[integer,}]])"]},"[-,multiplicativeExpression]":{"-":["-","multiplicativeExpression"]},"[.,?constructTriples]":{".":[".","?constructTriples"]},"[.,?triplesBlock]":{".":[".","?triplesBlock"]},"[.,?triplesTemplate]":{".":[".","?triplesTemplate"]},"[/,pathEltOrInverse]":{"/":["/","pathEltOrInverse"]},"[/,unaryExpression]":{"/":["/","unaryExpression"]},"[;,?[or([verbPath,verbSimple]),objectList]]":{";":[";","?[or([verbPath,verbSimple]),objectList]"]},"[;,?[verb,objectList]]":{";":[";","?[verb,objectList]"]},"[;,SEPARATOR,=,string]":{";":[";","SEPARATOR","=","string"]},"[;,update]":{";":[";","update"]},"[<,numericExpression]":{"<":["<","numericExpression"]},"[<=,numericExpression]":{"<=":["<=","numericExpression"]},"[=,numericExpression]":{"=":["=","numericExpression"]},"[>,numericExpression]":{">":[">","numericExpression"]},"[>=,numericExpression]":{">=":[">=","numericExpression"]},"[AS,var]":{AS:["AS","var"]},"[IN,expressionList]":{IN:["IN","expressionList"]},"[INTO,graphRef]":{INTO:["INTO","graphRef"]},"[NAMED,iriRef]":{NAMED:["NAMED","iriRef"]},"[NOT,IN,expressionList]":{NOT:["NOT","IN","expressionList"]},"[UNION,groupGraphPattern]":{UNION:["UNION","groupGraphPattern"]},"[^^,iriRef]":{"^^":["^^","iriRef"]},"[constructTemplate,*datasetClause,whereClause,solutionModifier]":{"{":["constructTemplate","*datasetClause","whereClause","solutionModifier"]},"[deleteClause,?insertClause]":{DELETE:["deleteClause","?insertClause"]},"[graphPatternNotTriples,?.,?triplesBlock]":{"{":["graphPatternNotTriples","?.","?triplesBlock"],OPTIONAL:["graphPatternNotTriples","?.","?triplesBlock"],MINUS:["graphPatternNotTriples","?.","?triplesBlock"],GRAPH:["graphPatternNotTriples","?.","?triplesBlock"],SERVICE:["graphPatternNotTriples","?.","?triplesBlock"],FILTER:["graphPatternNotTriples","?.","?triplesBlock"],BIND:["graphPatternNotTriples","?.","?triplesBlock"],VALUES:["graphPatternNotTriples","?.","?triplesBlock"]},"[integer,or([[,,or([},[integer,}]])],}])]":{INTEGER:["integer","or([[,,or([},[integer,}]])],}])"]},"[integer,}]":{INTEGER:["integer","}"]},"[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]":{INTEGER_POSITIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL_POSITIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE_POSITIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],INTEGER_NEGATIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL_NEGATIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE_NEGATIVE:["or([numericLiteralPositive,numericLiteralNegative])","?or([[*,unaryExpression],[/,unaryExpression]])"]},"[or([verbPath,verbSimple]),objectList]":{VAR1:["or([verbPath,verbSimple])","objectList"],VAR2:["or([verbPath,verbSimple])","objectList"],"^":["or([verbPath,verbSimple])","objectList"],a:["or([verbPath,verbSimple])","objectList"],"!":["or([verbPath,verbSimple])","objectList"],"(":["or([verbPath,verbSimple])","objectList"],IRI_REF:["or([verbPath,verbSimple])","objectList"],PNAME_LN:["or([verbPath,verbSimple])","objectList"],PNAME_NS:["or([verbPath,verbSimple])","objectList"]},"[pathOneInPropertySet,*[|,pathOneInPropertySet]]":{a:["pathOneInPropertySet","*[|,pathOneInPropertySet]"],"^":["pathOneInPropertySet","*[|,pathOneInPropertySet]"],IRI_REF:["pathOneInPropertySet","*[|,pathOneInPropertySet]"],PNAME_LN:["pathOneInPropertySet","*[|,pathOneInPropertySet]"],PNAME_NS:["pathOneInPropertySet","*[|,pathOneInPropertySet]"]},"[quadsNotTriples,?.,?triplesTemplate]":{GRAPH:["quadsNotTriples","?.","?triplesTemplate"]},"[update1,?[;,update]]":{INSERT:["update1","?[;,update]"],DELETE:["update1","?[;,update]"],LOAD:["update1","?[;,update]"],CLEAR:["update1","?[;,update]"],DROP:["update1","?[;,update]"],ADD:["update1","?[;,update]"],MOVE:["update1","?[;,update]"],COPY:["update1","?[;,update]"],CREATE:["update1","?[;,update]"],WITH:["update1","?[;,update]"]},"[verb,objectList]":{a:["verb","objectList"],VAR1:["verb","objectList"],VAR2:["verb","objectList"],IRI_REF:["verb","objectList"],PNAME_LN:["verb","objectList"],PNAME_NS:["verb","objectList"]},"[|,pathOneInPropertySet]":{"|":["|","pathOneInPropertySet"]},"[|,pathSequence]":{"|":["|","pathSequence"]},"[||,conditionalAndExpression]":{"||":["||","conditionalAndExpression"]},add:{ADD:["ADD","?SILENT_4","graphOrDefault","TO","graphOrDefault"]},additiveExpression:{"!":["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],"+":["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],"-":["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],VAR1:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],VAR2:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],"(":["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STR:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],LANG:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],LANGMATCHES:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DATATYPE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],BOUND:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],IRI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],URI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],BNODE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],RAND:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ABS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],CEIL:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],FLOOR:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ROUND:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],CONCAT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRLEN:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],UCASE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],LCASE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ENCODE_FOR_URI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],CONTAINS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRSTARTS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRENDS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRBEFORE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRAFTER:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],YEAR:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MONTH:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DAY:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],HOURS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MINUTES:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SECONDS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],TIMEZONE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],TZ:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],NOW:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],UUID:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRUUID:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MD5:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SHA1:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SHA256:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SHA384:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SHA512:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],COALESCE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],IF:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRLANG:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRDT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SAMETERM:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISIRI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISURI:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISBLANK:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISLITERAL:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],ISNUMERIC:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],TRUE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],FALSE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],COUNT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SUM:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MIN:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],MAX:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],AVG:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SAMPLE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],GROUP_CONCAT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],SUBSTR:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],REPLACE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],REGEX:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],EXISTS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],NOT:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],IRI_REF:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRING_LITERAL1:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRING_LITERAL2:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRING_LITERAL_LONG1:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],STRING_LITERAL_LONG2:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER_POSITIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL_POSITIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE_POSITIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],INTEGER_NEGATIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DECIMAL_NEGATIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],DOUBLE_NEGATIVE:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],PNAME_LN:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"],PNAME_NS:["multiplicativeExpression","*or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])"]},aggregate:{COUNT:["COUNT","(","?DISTINCT","or([*,expression])",")"],SUM:["SUM","(","?DISTINCT","expression",")"],MIN:["MIN","(","?DISTINCT","expression",")"],MAX:["MAX","(","?DISTINCT","expression",")"],AVG:["AVG","(","?DISTINCT","expression",")"],SAMPLE:["SAMPLE","(","?DISTINCT","expression",")"],GROUP_CONCAT:["GROUP_CONCAT","(","?DISTINCT","expression","?[;,SEPARATOR,=,string]",")"]},allowBnodes:{"}":[]},allowVars:{"}":[]},argList:{NIL:["NIL"],"(":["(","?DISTINCT","expression","*[,,expression]",")"]},askQuery:{ASK:["ASK","*datasetClause","whereClause","solutionModifier"]},baseDecl:{BASE:["BASE","IRI_REF"]},bind:{BIND:["BIND","(","expression","AS","var",")"]},blankNode:{BLANK_NODE_LABEL:["BLANK_NODE_LABEL"],ANON:["ANON"]},blankNodePropertyList:{"[":["[","propertyListNotEmpty","]"]},blankNodePropertyListPath:{"[":["[","propertyListPathNotEmpty","]"]},booleanLiteral:{TRUE:["TRUE"],FALSE:["FALSE"]},brackettedExpression:{"(":["(","expression",")"]},builtInCall:{STR:["STR","(","expression",")"],LANG:["LANG","(","expression",")"],LANGMATCHES:["LANGMATCHES","(","expression",",","expression",")"],DATATYPE:["DATATYPE","(","expression",")"],BOUND:["BOUND","(","var",")"],IRI:["IRI","(","expression",")"],URI:["URI","(","expression",")"],BNODE:["BNODE","or([[ (,expression,)],NIL])"],RAND:["RAND","NIL"],ABS:["ABS","(","expression",")"],CEIL:["CEIL","(","expression",")"],FLOOR:["FLOOR","(","expression",")"],ROUND:["ROUND","(","expression",")"],CONCAT:["CONCAT","expressionList"],SUBSTR:["substringExpression"],STRLEN:["STRLEN","(","expression",")"],REPLACE:["strReplaceExpression"],UCASE:["UCASE","(","expression",")"],LCASE:["LCASE","(","expression",")"],ENCODE_FOR_URI:["ENCODE_FOR_URI","(","expression",")"],CONTAINS:["CONTAINS","(","expression",",","expression",")"],STRSTARTS:["STRSTARTS","(","expression",",","expression",")"],STRENDS:["STRENDS","(","expression",",","expression",")"],STRBEFORE:["STRBEFORE","(","expression",",","expression",")"],STRAFTER:["STRAFTER","(","expression",",","expression",")"],YEAR:["YEAR","(","expression",")"],MONTH:["MONTH","(","expression",")"],DAY:["DAY","(","expression",")"],HOURS:["HOURS","(","expression",")"],MINUTES:["MINUTES","(","expression",")"],SECONDS:["SECONDS","(","expression",")"],TIMEZONE:["TIMEZONE","(","expression",")"],TZ:["TZ","(","expression",")"],NOW:["NOW","NIL"],UUID:["UUID","NIL"],STRUUID:["STRUUID","NIL"],MD5:["MD5","(","expression",")"],SHA1:["SHA1","(","expression",")"],SHA256:["SHA256","(","expression",")"],SHA384:["SHA384","(","expression",")"],SHA512:["SHA512","(","expression",")"],COALESCE:["COALESCE","expressionList"],IF:["IF","(","expression",",","expression",",","expression",")"],STRLANG:["STRLANG","(","expression",",","expression",")"],STRDT:["STRDT","(","expression",",","expression",")"],SAMETERM:["SAMETERM","(","expression",",","expression",")"],ISIRI:["ISIRI","(","expression",")"],ISURI:["ISURI","(","expression",")"],ISBLANK:["ISBLANK","(","expression",")"],ISLITERAL:["ISLITERAL","(","expression",")"],ISNUMERIC:["ISNUMERIC","(","expression",")"],REGEX:["regexExpression"],EXISTS:["existsFunc"],NOT:["notExistsFunc"]},clear:{CLEAR:["CLEAR","?SILENT_2","graphRefAll"]},collection:{"(":["(","+graphNode",")"]},collectionPath:{"(":["(","+graphNodePath",")"]},conditionalAndExpression:{"!":["valueLogical","*[&&,valueLogical]"],"+":["valueLogical","*[&&,valueLogical]"],"-":["valueLogical","*[&&,valueLogical]"],VAR1:["valueLogical","*[&&,valueLogical]"],VAR2:["valueLogical","*[&&,valueLogical]"],"(":["valueLogical","*[&&,valueLogical]"],STR:["valueLogical","*[&&,valueLogical]"],LANG:["valueLogical","*[&&,valueLogical]"],LANGMATCHES:["valueLogical","*[&&,valueLogical]"],DATATYPE:["valueLogical","*[&&,valueLogical]"],BOUND:["valueLogical","*[&&,valueLogical]"],IRI:["valueLogical","*[&&,valueLogical]"],URI:["valueLogical","*[&&,valueLogical]"],BNODE:["valueLogical","*[&&,valueLogical]"],RAND:["valueLogical","*[&&,valueLogical]"],ABS:["valueLogical","*[&&,valueLogical]"],CEIL:["valueLogical","*[&&,valueLogical]"],FLOOR:["valueLogical","*[&&,valueLogical]"],ROUND:["valueLogical","*[&&,valueLogical]"],CONCAT:["valueLogical","*[&&,valueLogical]"],STRLEN:["valueLogical","*[&&,valueLogical]"],UCASE:["valueLogical","*[&&,valueLogical]"],LCASE:["valueLogical","*[&&,valueLogical]"],ENCODE_FOR_URI:["valueLogical","*[&&,valueLogical]"],CONTAINS:["valueLogical","*[&&,valueLogical]"],STRSTARTS:["valueLogical","*[&&,valueLogical]"],STRENDS:["valueLogical","*[&&,valueLogical]"],STRBEFORE:["valueLogical","*[&&,valueLogical]"],STRAFTER:["valueLogical","*[&&,valueLogical]"],YEAR:["valueLogical","*[&&,valueLogical]"],MONTH:["valueLogical","*[&&,valueLogical]"],DAY:["valueLogical","*[&&,valueLogical]"],HOURS:["valueLogical","*[&&,valueLogical]"],MINUTES:["valueLogical","*[&&,valueLogical]"],SECONDS:["valueLogical","*[&&,valueLogical]"],TIMEZONE:["valueLogical","*[&&,valueLogical]"],TZ:["valueLogical","*[&&,valueLogical]"],NOW:["valueLogical","*[&&,valueLogical]"],UUID:["valueLogical","*[&&,valueLogical]"],STRUUID:["valueLogical","*[&&,valueLogical]"],MD5:["valueLogical","*[&&,valueLogical]"],SHA1:["valueLogical","*[&&,valueLogical]"],SHA256:["valueLogical","*[&&,valueLogical]"],SHA384:["valueLogical","*[&&,valueLogical]"],SHA512:["valueLogical","*[&&,valueLogical]"],COALESCE:["valueLogical","*[&&,valueLogical]"],IF:["valueLogical","*[&&,valueLogical]"],STRLANG:["valueLogical","*[&&,valueLogical]"],STRDT:["valueLogical","*[&&,valueLogical]"],SAMETERM:["valueLogical","*[&&,valueLogical]"],ISIRI:["valueLogical","*[&&,valueLogical]"],ISURI:["valueLogical","*[&&,valueLogical]"],ISBLANK:["valueLogical","*[&&,valueLogical]"],ISLITERAL:["valueLogical","*[&&,valueLogical]"],ISNUMERIC:["valueLogical","*[&&,valueLogical]"],TRUE:["valueLogical","*[&&,valueLogical]"],FALSE:["valueLogical","*[&&,valueLogical]"],COUNT:["valueLogical","*[&&,valueLogical]"],SUM:["valueLogical","*[&&,valueLogical]"],MIN:["valueLogical","*[&&,valueLogical]"],MAX:["valueLogical","*[&&,valueLogical]"],AVG:["valueLogical","*[&&,valueLogical]"],SAMPLE:["valueLogical","*[&&,valueLogical]"],GROUP_CONCAT:["valueLogical","*[&&,valueLogical]"],SUBSTR:["valueLogical","*[&&,valueLogical]"],REPLACE:["valueLogical","*[&&,valueLogical]"],REGEX:["valueLogical","*[&&,valueLogical]"],EXISTS:["valueLogical","*[&&,valueLogical]"],NOT:["valueLogical","*[&&,valueLogical]"],IRI_REF:["valueLogical","*[&&,valueLogical]"],STRING_LITERAL1:["valueLogical","*[&&,valueLogical]"],STRING_LITERAL2:["valueLogical","*[&&,valueLogical]"],STRING_LITERAL_LONG1:["valueLogical","*[&&,valueLogical]"],STRING_LITERAL_LONG2:["valueLogical","*[&&,valueLogical]"],INTEGER:["valueLogical","*[&&,valueLogical]"],DECIMAL:["valueLogical","*[&&,valueLogical]"],DOUBLE:["valueLogical","*[&&,valueLogical]"],INTEGER_POSITIVE:["valueLogical","*[&&,valueLogical]"],DECIMAL_POSITIVE:["valueLogical","*[&&,valueLogical]"],DOUBLE_POSITIVE:["valueLogical","*[&&,valueLogical]"],INTEGER_NEGATIVE:["valueLogical","*[&&,valueLogical]"],DECIMAL_NEGATIVE:["valueLogical","*[&&,valueLogical]"],DOUBLE_NEGATIVE:["valueLogical","*[&&,valueLogical]"],PNAME_LN:["valueLogical","*[&&,valueLogical]"],PNAME_NS:["valueLogical","*[&&,valueLogical]"]},conditionalOrExpression:{"!":["conditionalAndExpression","*[||,conditionalAndExpression]"],"+":["conditionalAndExpression","*[||,conditionalAndExpression]"],"-":["conditionalAndExpression","*[||,conditionalAndExpression]"],VAR1:["conditionalAndExpression","*[||,conditionalAndExpression]"],VAR2:["conditionalAndExpression","*[||,conditionalAndExpression]"],"(":["conditionalAndExpression","*[||,conditionalAndExpression]"],STR:["conditionalAndExpression","*[||,conditionalAndExpression]"],LANG:["conditionalAndExpression","*[||,conditionalAndExpression]"],LANGMATCHES:["conditionalAndExpression","*[||,conditionalAndExpression]"],DATATYPE:["conditionalAndExpression","*[||,conditionalAndExpression]"],BOUND:["conditionalAndExpression","*[||,conditionalAndExpression]"],IRI:["conditionalAndExpression","*[||,conditionalAndExpression]"],URI:["conditionalAndExpression","*[||,conditionalAndExpression]"],BNODE:["conditionalAndExpression","*[||,conditionalAndExpression]"],RAND:["conditionalAndExpression","*[||,conditionalAndExpression]"],ABS:["conditionalAndExpression","*[||,conditionalAndExpression]"],CEIL:["conditionalAndExpression","*[||,conditionalAndExpression]"],FLOOR:["conditionalAndExpression","*[||,conditionalAndExpression]"],ROUND:["conditionalAndExpression","*[||,conditionalAndExpression]"],CONCAT:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRLEN:["conditionalAndExpression","*[||,conditionalAndExpression]"],UCASE:["conditionalAndExpression","*[||,conditionalAndExpression]"],LCASE:["conditionalAndExpression","*[||,conditionalAndExpression]"],ENCODE_FOR_URI:["conditionalAndExpression","*[||,conditionalAndExpression]"],CONTAINS:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRSTARTS:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRENDS:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRBEFORE:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRAFTER:["conditionalAndExpression","*[||,conditionalAndExpression]"],YEAR:["conditionalAndExpression","*[||,conditionalAndExpression]"],MONTH:["conditionalAndExpression","*[||,conditionalAndExpression]"],DAY:["conditionalAndExpression","*[||,conditionalAndExpression]"],HOURS:["conditionalAndExpression","*[||,conditionalAndExpression]"],MINUTES:["conditionalAndExpression","*[||,conditionalAndExpression]"],SECONDS:["conditionalAndExpression","*[||,conditionalAndExpression]"],TIMEZONE:["conditionalAndExpression","*[||,conditionalAndExpression]"],TZ:["conditionalAndExpression","*[||,conditionalAndExpression]"],NOW:["conditionalAndExpression","*[||,conditionalAndExpression]"],UUID:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRUUID:["conditionalAndExpression","*[||,conditionalAndExpression]"],MD5:["conditionalAndExpression","*[||,conditionalAndExpression]"],SHA1:["conditionalAndExpression","*[||,conditionalAndExpression]"],SHA256:["conditionalAndExpression","*[||,conditionalAndExpression]"],SHA384:["conditionalAndExpression","*[||,conditionalAndExpression]"],SHA512:["conditionalAndExpression","*[||,conditionalAndExpression]"],COALESCE:["conditionalAndExpression","*[||,conditionalAndExpression]"],IF:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRLANG:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRDT:["conditionalAndExpression","*[||,conditionalAndExpression]"],SAMETERM:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISIRI:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISURI:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISBLANK:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISLITERAL:["conditionalAndExpression","*[||,conditionalAndExpression]"],ISNUMERIC:["conditionalAndExpression","*[||,conditionalAndExpression]"],TRUE:["conditionalAndExpression","*[||,conditionalAndExpression]"],FALSE:["conditionalAndExpression","*[||,conditionalAndExpression]"],COUNT:["conditionalAndExpression","*[||,conditionalAndExpression]"],SUM:["conditionalAndExpression","*[||,conditionalAndExpression]"],MIN:["conditionalAndExpression","*[||,conditionalAndExpression]"],MAX:["conditionalAndExpression","*[||,conditionalAndExpression]"],AVG:["conditionalAndExpression","*[||,conditionalAndExpression]"],SAMPLE:["conditionalAndExpression","*[||,conditionalAndExpression]"],GROUP_CONCAT:["conditionalAndExpression","*[||,conditionalAndExpression]"],SUBSTR:["conditionalAndExpression","*[||,conditionalAndExpression]"],REPLACE:["conditionalAndExpression","*[||,conditionalAndExpression]"],REGEX:["conditionalAndExpression","*[||,conditionalAndExpression]"],EXISTS:["conditionalAndExpression","*[||,conditionalAndExpression]"],NOT:["conditionalAndExpression","*[||,conditionalAndExpression]"],IRI_REF:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRING_LITERAL1:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRING_LITERAL2:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRING_LITERAL_LONG1:["conditionalAndExpression","*[||,conditionalAndExpression]"],STRING_LITERAL_LONG2:["conditionalAndExpression","*[||,conditionalAndExpression]"],INTEGER:["conditionalAndExpression","*[||,conditionalAndExpression]"],DECIMAL:["conditionalAndExpression","*[||,conditionalAndExpression]"],DOUBLE:["conditionalAndExpression","*[||,conditionalAndExpression]"],INTEGER_POSITIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],DECIMAL_POSITIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],DOUBLE_POSITIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],INTEGER_NEGATIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],DECIMAL_NEGATIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],DOUBLE_NEGATIVE:["conditionalAndExpression","*[||,conditionalAndExpression]"],PNAME_LN:["conditionalAndExpression","*[||,conditionalAndExpression]"],PNAME_NS:["conditionalAndExpression","*[||,conditionalAndExpression]"]},constraint:{"(":["brackettedExpression"],STR:["builtInCall"],LANG:["builtInCall"],LANGMATCHES:["builtInCall"],DATATYPE:["builtInCall"],BOUND:["builtInCall"],IRI:["builtInCall"],URI:["builtInCall"],BNODE:["builtInCall"],RAND:["builtInCall"],ABS:["builtInCall"],CEIL:["builtInCall"],FLOOR:["builtInCall"],ROUND:["builtInCall"],CONCAT:["builtInCall"],STRLEN:["builtInCall"],UCASE:["builtInCall"],LCASE:["builtInCall"],ENCODE_FOR_URI:["builtInCall"],CONTAINS:["builtInCall"],STRSTARTS:["builtInCall"],STRENDS:["builtInCall"],STRBEFORE:["builtInCall"],STRAFTER:["builtInCall"],YEAR:["builtInCall"],MONTH:["builtInCall"],DAY:["builtInCall"],HOURS:["builtInCall"],MINUTES:["builtInCall"],SECONDS:["builtInCall"],TIMEZONE:["builtInCall"],TZ:["builtInCall"],NOW:["builtInCall"],UUID:["builtInCall"],STRUUID:["builtInCall"],MD5:["builtInCall"],SHA1:["builtInCall"],SHA256:["builtInCall"],SHA384:["builtInCall"],SHA512:["builtInCall"],COALESCE:["builtInCall"],IF:["builtInCall"],STRLANG:["builtInCall"],STRDT:["builtInCall"],SAMETERM:["builtInCall"],ISIRI:["builtInCall"],ISURI:["builtInCall"],ISBLANK:["builtInCall"],ISLITERAL:["builtInCall"],ISNUMERIC:["builtInCall"],SUBSTR:["builtInCall"],REPLACE:["builtInCall"],REGEX:["builtInCall"],EXISTS:["builtInCall"],NOT:["builtInCall"],IRI_REF:["functionCall"],PNAME_LN:["functionCall"],PNAME_NS:["functionCall"]},constructQuery:{CONSTRUCT:["CONSTRUCT","or([[constructTemplate,*datasetClause,whereClause,solutionModifier],[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]])"]},constructTemplate:{"{":["{","?constructTriples","}"]},constructTriples:{VAR1:["triplesSameSubject","?[.,?constructTriples]"],VAR2:["triplesSameSubject","?[.,?constructTriples]"],NIL:["triplesSameSubject","?[.,?constructTriples]"],"(":["triplesSameSubject","?[.,?constructTriples]"],"[":["triplesSameSubject","?[.,?constructTriples]"],IRI_REF:["triplesSameSubject","?[.,?constructTriples]"],TRUE:["triplesSameSubject","?[.,?constructTriples]"],FALSE:["triplesSameSubject","?[.,?constructTriples]"],BLANK_NODE_LABEL:["triplesSameSubject","?[.,?constructTriples]"],ANON:["triplesSameSubject","?[.,?constructTriples]"],PNAME_LN:["triplesSameSubject","?[.,?constructTriples]"],PNAME_NS:["triplesSameSubject","?[.,?constructTriples]"],STRING_LITERAL1:["triplesSameSubject","?[.,?constructTriples]"],STRING_LITERAL2:["triplesSameSubject","?[.,?constructTriples]"],STRING_LITERAL_LONG1:["triplesSameSubject","?[.,?constructTriples]"],STRING_LITERAL_LONG2:["triplesSameSubject","?[.,?constructTriples]"],INTEGER:["triplesSameSubject","?[.,?constructTriples]"],DECIMAL:["triplesSameSubject","?[.,?constructTriples]"],DOUBLE:["triplesSameSubject","?[.,?constructTriples]"],INTEGER_POSITIVE:["triplesSameSubject","?[.,?constructTriples]"],DECIMAL_POSITIVE:["triplesSameSubject","?[.,?constructTriples]"],DOUBLE_POSITIVE:["triplesSameSubject","?[.,?constructTriples]"],INTEGER_NEGATIVE:["triplesSameSubject","?[.,?constructTriples]"],DECIMAL_NEGATIVE:["triplesSameSubject","?[.,?constructTriples]"],DOUBLE_NEGATIVE:["triplesSameSubject","?[.,?constructTriples]"]},copy:{COPY:["COPY","?SILENT_4","graphOrDefault","TO","graphOrDefault"]},create:{CREATE:["CREATE","?SILENT_3","graphRef"]},dataBlock:{NIL:["or([inlineDataOneVar,inlineDataFull])"],"(":["or([inlineDataOneVar,inlineDataFull])"],VAR1:["or([inlineDataOneVar,inlineDataFull])"],VAR2:["or([inlineDataOneVar,inlineDataFull])"]},dataBlockValue:{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],STRING_LITERAL1:["rdfLiteral"],STRING_LITERAL2:["rdfLiteral"],STRING_LITERAL_LONG1:["rdfLiteral"],STRING_LITERAL_LONG2:["rdfLiteral"],INTEGER:["numericLiteral"],DECIMAL:["numericLiteral"],DOUBLE:["numericLiteral"],INTEGER_POSITIVE:["numericLiteral"],DECIMAL_POSITIVE:["numericLiteral"],DOUBLE_POSITIVE:["numericLiteral"],INTEGER_NEGATIVE:["numericLiteral"],DECIMAL_NEGATIVE:["numericLiteral"],DOUBLE_NEGATIVE:["numericLiteral"],TRUE:["booleanLiteral"],FALSE:["booleanLiteral"],UNDEF:["UNDEF"]},datasetClause:{FROM:["FROM","or([defaultGraphClause,namedGraphClause])"]},defaultGraphClause:{IRI_REF:["sourceSelector"],PNAME_LN:["sourceSelector"],PNAME_NS:["sourceSelector"]},delete1:{DATA:["DATA","quadDataNoBnodes"],WHERE:["WHERE","quadPatternNoBnodes"],"{":["quadPatternNoBnodes","?insertClause","*usingClause","WHERE","groupGraphPattern"]},deleteClause:{DELETE:["DELETE","quadPattern"]},describeDatasetClause:{FROM:["FROM","or([defaultGraphClause,namedGraphClause])"]},describeQuery:{DESCRIBE:["DESCRIBE","or([+varOrIRIref,*])","*describeDatasetClause","?whereClause","solutionModifier"]},disallowBnodes:{"}":[],GRAPH:[],VAR1:[],VAR2:[],NIL:[],"(":[],"[":[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},disallowVars:{"}":[],GRAPH:[],VAR1:[],VAR2:[],NIL:[],"(":[],"[":[],IRI_REF:[],TRUE:[],FALSE:[],BLANK_NODE_LABEL:[],ANON:[],PNAME_LN:[],PNAME_NS:[],STRING_LITERAL1:[],STRING_LITERAL2:[],STRING_LITERAL_LONG1:[],STRING_LITERAL_LONG2:[],INTEGER:[],DECIMAL:[],DOUBLE:[],INTEGER_POSITIVE:[],DECIMAL_POSITIVE:[],DOUBLE_POSITIVE:[],INTEGER_NEGATIVE:[],DECIMAL_NEGATIVE:[],DOUBLE_NEGATIVE:[]},drop:{DROP:["DROP","?SILENT_2","graphRefAll"]},existsFunc:{EXISTS:["EXISTS","groupGraphPattern"]},expression:{"!":["conditionalOrExpression"],"+":["conditionalOrExpression"],"-":["conditionalOrExpression"],VAR1:["conditionalOrExpression"],VAR2:["conditionalOrExpression"],"(":["conditionalOrExpression"],STR:["conditionalOrExpression"],LANG:["conditionalOrExpression"],LANGMATCHES:["conditionalOrExpression"],DATATYPE:["conditionalOrExpression"],BOUND:["conditionalOrExpression"],IRI:["conditionalOrExpression"],URI:["conditionalOrExpression"],BNODE:["conditionalOrExpression"],RAND:["conditionalOrExpression"],ABS:["conditionalOrExpression"],CEIL:["conditionalOrExpression"],FLOOR:["conditionalOrExpression"],ROUND:["conditionalOrExpression"],CONCAT:["conditionalOrExpression"],STRLEN:["conditionalOrExpression"],UCASE:["conditionalOrExpression"],LCASE:["conditionalOrExpression"],ENCODE_FOR_URI:["conditionalOrExpression"],CONTAINS:["conditionalOrExpression"],STRSTARTS:["conditionalOrExpression"],STRENDS:["conditionalOrExpression"],STRBEFORE:["conditionalOrExpression"],STRAFTER:["conditionalOrExpression"],YEAR:["conditionalOrExpression"],MONTH:["conditionalOrExpression"],DAY:["conditionalOrExpression"],HOURS:["conditionalOrExpression"],MINUTES:["conditionalOrExpression"],SECONDS:["conditionalOrExpression"],TIMEZONE:["conditionalOrExpression"],TZ:["conditionalOrExpression"],NOW:["conditionalOrExpression"],UUID:["conditionalOrExpression"],STRUUID:["conditionalOrExpression"],MD5:["conditionalOrExpression"],SHA1:["conditionalOrExpression"],SHA256:["conditionalOrExpression"],SHA384:["conditionalOrExpression"],SHA512:["conditionalOrExpression"],COALESCE:["conditionalOrExpression"],IF:["conditionalOrExpression"],STRLANG:["conditionalOrExpression"],STRDT:["conditionalOrExpression"],SAMETERM:["conditionalOrExpression"],ISIRI:["conditionalOrExpression"],ISURI:["conditionalOrExpression"],ISBLANK:["conditionalOrExpression"],ISLITERAL:["conditionalOrExpression"],ISNUMERIC:["conditionalOrExpression"],TRUE:["conditionalOrExpression"],FALSE:["conditionalOrExpression"],COUNT:["conditionalOrExpression"],SUM:["conditionalOrExpression"],MIN:["conditionalOrExpression"],MAX:["conditionalOrExpression"],AVG:["conditionalOrExpression"],SAMPLE:["conditionalOrExpression"],GROUP_CONCAT:["conditionalOrExpression"],SUBSTR:["conditionalOrExpression"],REPLACE:["conditionalOrExpression"],REGEX:["conditionalOrExpression"],EXISTS:["conditionalOrExpression"],NOT:["conditionalOrExpression"],IRI_REF:["conditionalOrExpression"],STRING_LITERAL1:["conditionalOrExpression"],STRING_LITERAL2:["conditionalOrExpression"],STRING_LITERAL_LONG1:["conditionalOrExpression"],STRING_LITERAL_LONG2:["conditionalOrExpression"],INTEGER:["conditionalOrExpression"],DECIMAL:["conditionalOrExpression"],DOUBLE:["conditionalOrExpression"],INTEGER_POSITIVE:["conditionalOrExpression"],DECIMAL_POSITIVE:["conditionalOrExpression"],DOUBLE_POSITIVE:["conditionalOrExpression"],INTEGER_NEGATIVE:["conditionalOrExpression"],DECIMAL_NEGATIVE:["conditionalOrExpression"],DOUBLE_NEGATIVE:["conditionalOrExpression"],PNAME_LN:["conditionalOrExpression"],PNAME_NS:["conditionalOrExpression"]},expressionList:{NIL:["NIL"],"(":["(","expression","*[,,expression]",")"]},filter:{FILTER:["FILTER","constraint"]},functionCall:{IRI_REF:["iriRef","argList"],PNAME_LN:["iriRef","argList"],PNAME_NS:["iriRef","argList"]},graphGraphPattern:{GRAPH:["GRAPH","varOrIRIref","groupGraphPattern"]},graphNode:{VAR1:["varOrTerm"],VAR2:["varOrTerm"],NIL:["varOrTerm"],IRI_REF:["varOrTerm"],TRUE:["varOrTerm"],FALSE:["varOrTerm"],BLANK_NODE_LABEL:["varOrTerm"],ANON:["varOrTerm"],PNAME_LN:["varOrTerm"],PNAME_NS:["varOrTerm"],STRING_LITERAL1:["varOrTerm"],STRING_LITERAL2:["varOrTerm"],STRING_LITERAL_LONG1:["varOrTerm"],STRING_LITERAL_LONG2:["varOrTerm"],INTEGER:["varOrTerm"],DECIMAL:["varOrTerm"],DOUBLE:["varOrTerm"],INTEGER_POSITIVE:["varOrTerm"],DECIMAL_POSITIVE:["varOrTerm"],DOUBLE_POSITIVE:["varOrTerm"],INTEGER_NEGATIVE:["varOrTerm"],DECIMAL_NEGATIVE:["varOrTerm"],DOUBLE_NEGATIVE:["varOrTerm"],"(":["triplesNode"],"[":["triplesNode"]},graphNodePath:{VAR1:["varOrTerm"],VAR2:["varOrTerm"],NIL:["varOrTerm"],IRI_REF:["varOrTerm"],TRUE:["varOrTerm"],FALSE:["varOrTerm"],BLANK_NODE_LABEL:["varOrTerm"],ANON:["varOrTerm"],PNAME_LN:["varOrTerm"],PNAME_NS:["varOrTerm"],STRING_LITERAL1:["varOrTerm"],STRING_LITERAL2:["varOrTerm"],STRING_LITERAL_LONG1:["varOrTerm"],STRING_LITERAL_LONG2:["varOrTerm"],INTEGER:["varOrTerm"],DECIMAL:["varOrTerm"],DOUBLE:["varOrTerm"],INTEGER_POSITIVE:["varOrTerm"],DECIMAL_POSITIVE:["varOrTerm"],DOUBLE_POSITIVE:["varOrTerm"],INTEGER_NEGATIVE:["varOrTerm"],DECIMAL_NEGATIVE:["varOrTerm"],DOUBLE_NEGATIVE:["varOrTerm"],"(":["triplesNodePath"],"[":["triplesNodePath"]},graphOrDefault:{DEFAULT:["DEFAULT"],IRI_REF:["?GRAPH","iriRef"],PNAME_LN:["?GRAPH","iriRef"],PNAME_NS:["?GRAPH","iriRef"],GRAPH:["?GRAPH","iriRef"]},graphPatternNotTriples:{"{":["groupOrUnionGraphPattern"],OPTIONAL:["optionalGraphPattern"],MINUS:["minusGraphPattern"],GRAPH:["graphGraphPattern"],SERVICE:["serviceGraphPattern"],FILTER:["filter"],BIND:["bind"],VALUES:["inlineData"]},graphRef:{GRAPH:["GRAPH","iriRef"]},graphRefAll:{GRAPH:["graphRef"],DEFAULT:["DEFAULT"],NAMED:["NAMED"],ALL:["ALL"]},graphTerm:{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],STRING_LITERAL1:["rdfLiteral"],STRING_LITERAL2:["rdfLiteral"],STRING_LITERAL_LONG1:["rdfLiteral"],STRING_LITERAL_LONG2:["rdfLiteral"],INTEGER:["numericLiteral"],DECIMAL:["numericLiteral"],DOUBLE:["numericLiteral"],INTEGER_POSITIVE:["numericLiteral"],DECIMAL_POSITIVE:["numericLiteral"],DOUBLE_POSITIVE:["numericLiteral"],INTEGER_NEGATIVE:["numericLiteral"],DECIMAL_NEGATIVE:["numericLiteral"],DOUBLE_NEGATIVE:["numericLiteral"],TRUE:["booleanLiteral"],FALSE:["booleanLiteral"],BLANK_NODE_LABEL:["blankNode"],ANON:["blankNode"],NIL:["NIL"]},groupClause:{GROUP:["GROUP","BY","+groupCondition"]},groupCondition:{STR:["builtInCall"],LANG:["builtInCall"],LANGMATCHES:["builtInCall"],DATATYPE:["builtInCall"],BOUND:["builtInCall"],IRI:["builtInCall"],URI:["builtInCall"],BNODE:["builtInCall"],RAND:["builtInCall"],ABS:["builtInCall"],CEIL:["builtInCall"],FLOOR:["builtInCall"],ROUND:["builtInCall"],CONCAT:["builtInCall"],STRLEN:["builtInCall"],UCASE:["builtInCall"],LCASE:["builtInCall"],ENCODE_FOR_URI:["builtInCall"],CONTAINS:["builtInCall"],STRSTARTS:["builtInCall"],STRENDS:["builtInCall"],STRBEFORE:["builtInCall"],STRAFTER:["builtInCall"],YEAR:["builtInCall"],MONTH:["builtInCall"],DAY:["builtInCall"],HOURS:["builtInCall"],MINUTES:["builtInCall"],SECONDS:["builtInCall"],TIMEZONE:["builtInCall"],TZ:["builtInCall"],NOW:["builtInCall"],UUID:["builtInCall"],STRUUID:["builtInCall"],MD5:["builtInCall"],SHA1:["builtInCall"],SHA256:["builtInCall"],SHA384:["builtInCall"],SHA512:["builtInCall"],COALESCE:["builtInCall"],IF:["builtInCall"],STRLANG:["builtInCall"],STRDT:["builtInCall"],SAMETERM:["builtInCall"],ISIRI:["builtInCall"],ISURI:["builtInCall"],ISBLANK:["builtInCall"],ISLITERAL:["builtInCall"],ISNUMERIC:["builtInCall"],SUBSTR:["builtInCall"],REPLACE:["builtInCall"],REGEX:["builtInCall"],EXISTS:["builtInCall"],NOT:["builtInCall"],IRI_REF:["functionCall"],PNAME_LN:["functionCall"],PNAME_NS:["functionCall"],"(":["(","expression","?[AS,var]",")"],VAR1:["var"],VAR2:["var"]},groupGraphPattern:{"{":["{","or([subSelect,groupGraphPatternSub])","}"]},groupGraphPatternSub:{"{":["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],OPTIONAL:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],MINUS:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],GRAPH:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],SERVICE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],FILTER:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],BIND:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],VALUES:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],VAR1:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],VAR2:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],NIL:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],"(":["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],"[":["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],IRI_REF:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],TRUE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],FALSE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],BLANK_NODE_LABEL:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],ANON:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],PNAME_LN:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],PNAME_NS:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],STRING_LITERAL1:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],STRING_LITERAL2:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],STRING_LITERAL_LONG1:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],STRING_LITERAL_LONG2:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],INTEGER:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DECIMAL:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DOUBLE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],INTEGER_POSITIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DECIMAL_POSITIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DOUBLE_POSITIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],INTEGER_NEGATIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DECIMAL_NEGATIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],DOUBLE_NEGATIVE:["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"],"}":["?triplesBlock","*[graphPatternNotTriples,?.,?triplesBlock]"]},groupOrUnionGraphPattern:{"{":["groupGraphPattern","*[UNION,groupGraphPattern]"]},havingClause:{HAVING:["HAVING","+havingCondition"]},havingCondition:{"(":["constraint"],STR:["constraint"],LANG:["constraint"],LANGMATCHES:["constraint"],DATATYPE:["constraint"],BOUND:["constraint"],IRI:["constraint"],URI:["constraint"],BNODE:["constraint"],RAND:["constraint"],ABS:["constraint"],CEIL:["constraint"],FLOOR:["constraint"],ROUND:["constraint"],CONCAT:["constraint"],STRLEN:["constraint"],UCASE:["constraint"],LCASE:["constraint"],ENCODE_FOR_URI:["constraint"],CONTAINS:["constraint"],STRSTARTS:["constraint"],STRENDS:["constraint"],STRBEFORE:["constraint"],STRAFTER:["constraint"],YEAR:["constraint"],MONTH:["constraint"],DAY:["constraint"],HOURS:["constraint"],MINUTES:["constraint"],SECONDS:["constraint"],TIMEZONE:["constraint"],TZ:["constraint"],NOW:["constraint"],UUID:["constraint"],STRUUID:["constraint"],MD5:["constraint"],SHA1:["constraint"],SHA256:["constraint"],SHA384:["constraint"],SHA512:["constraint"],COALESCE:["constraint"],IF:["constraint"],STRLANG:["constraint"],STRDT:["constraint"],SAMETERM:["constraint"],ISIRI:["constraint"],ISURI:["constraint"],ISBLANK:["constraint"],ISLITERAL:["constraint"],ISNUMERIC:["constraint"],SUBSTR:["constraint"],REPLACE:["constraint"],REGEX:["constraint"],EXISTS:["constraint"],NOT:["constraint"],IRI_REF:["constraint"],PNAME_LN:["constraint"],PNAME_NS:["constraint"]},inlineData:{VALUES:["VALUES","dataBlock"]},inlineDataFull:{NIL:["or([NIL,[ (,*var,)]])","{","*or([[ (,*dataBlockValue,)],NIL])","}"],"(":["or([NIL,[ (,*var,)]])","{","*or([[ (,*dataBlockValue,)],NIL])","}"]},inlineDataOneVar:{VAR1:["var","{","*dataBlockValue","}"],VAR2:["var","{","*dataBlockValue","}"]},insert1:{DATA:["DATA","quadData"],"{":["quadPattern","*usingClause","WHERE","groupGraphPattern"]},insertClause:{INSERT:["INSERT","quadPattern"]},integer:{INTEGER:["INTEGER"]},iriRef:{IRI_REF:["IRI_REF"],PNAME_LN:["prefixedName"],PNAME_NS:["prefixedName"]},iriRefOrFunction:{IRI_REF:["iriRef","?argList"],PNAME_LN:["iriRef","?argList"],PNAME_NS:["iriRef","?argList"]},limitClause:{LIMIT:["LIMIT","INTEGER"]},limitOffsetClauses:{LIMIT:["limitClause","?offsetClause"],OFFSET:["offsetClause","?limitClause"]},load:{LOAD:["LOAD","?SILENT_1","iriRef","?[INTO,graphRef]"]},minusGraphPattern:{MINUS:["MINUS","groupGraphPattern"]},modify:{WITH:["WITH","iriRef","or([[deleteClause,?insertClause],insertClause])","*usingClause","WHERE","groupGraphPattern"]},move:{MOVE:["MOVE","?SILENT_4","graphOrDefault","TO","graphOrDefault"]},multiplicativeExpression:{"!":["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],"+":["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],"-":["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],VAR1:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],VAR2:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],"(":["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STR:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],LANG:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],LANGMATCHES:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DATATYPE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],BOUND:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],IRI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],URI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],BNODE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],RAND:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ABS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],CEIL:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],FLOOR:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ROUND:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],CONCAT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRLEN:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],UCASE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],LCASE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ENCODE_FOR_URI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],CONTAINS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRSTARTS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRENDS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRBEFORE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRAFTER:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],YEAR:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MONTH:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DAY:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],HOURS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MINUTES:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SECONDS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],TIMEZONE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],TZ:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],NOW:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],UUID:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRUUID:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MD5:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SHA1:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SHA256:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SHA384:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SHA512:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],COALESCE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],IF:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRLANG:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRDT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SAMETERM:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISIRI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISURI:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISBLANK:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISLITERAL:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],ISNUMERIC:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],TRUE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],FALSE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],COUNT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SUM:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MIN:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],MAX:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],AVG:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SAMPLE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],GROUP_CONCAT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],SUBSTR:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],REPLACE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],REGEX:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],EXISTS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],NOT:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],IRI_REF:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRING_LITERAL1:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRING_LITERAL2:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRING_LITERAL_LONG1:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],STRING_LITERAL_LONG2:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],INTEGER:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],INTEGER_POSITIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL_POSITIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE_POSITIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],INTEGER_NEGATIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DECIMAL_NEGATIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],DOUBLE_NEGATIVE:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],PNAME_LN:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"],PNAME_NS:["unaryExpression","*or([[*,unaryExpression],[/,unaryExpression]])"]},namedGraphClause:{NAMED:["NAMED","sourceSelector"]},notExistsFunc:{NOT:["NOT","EXISTS","groupGraphPattern"]},numericExpression:{"!":["additiveExpression"],"+":["additiveExpression"],"-":["additiveExpression"],VAR1:["additiveExpression"],VAR2:["additiveExpression"],"(":["additiveExpression"],STR:["additiveExpression"],LANG:["additiveExpression"],LANGMATCHES:["additiveExpression"],DATATYPE:["additiveExpression"],BOUND:["additiveExpression"],IRI:["additiveExpression"],URI:["additiveExpression"],BNODE:["additiveExpression"],RAND:["additiveExpression"],ABS:["additiveExpression"],CEIL:["additiveExpression"],FLOOR:["additiveExpression"],ROUND:["additiveExpression"],CONCAT:["additiveExpression"],STRLEN:["additiveExpression"],UCASE:["additiveExpression"],LCASE:["additiveExpression"],ENCODE_FOR_URI:["additiveExpression"],CONTAINS:["additiveExpression"],STRSTARTS:["additiveExpression"],STRENDS:["additiveExpression"],STRBEFORE:["additiveExpression"],STRAFTER:["additiveExpression"],YEAR:["additiveExpression"],MONTH:["additiveExpression"],DAY:["additiveExpression"],HOURS:["additiveExpression"],MINUTES:["additiveExpression"],SECONDS:["additiveExpression"],TIMEZONE:["additiveExpression"],TZ:["additiveExpression"],NOW:["additiveExpression"],UUID:["additiveExpression"],STRUUID:["additiveExpression"],MD5:["additiveExpression"],SHA1:["additiveExpression"],SHA256:["additiveExpression"],SHA384:["additiveExpression"],SHA512:["additiveExpression"],COALESCE:["additiveExpression"],IF:["additiveExpression"],STRLANG:["additiveExpression"],STRDT:["additiveExpression"],SAMETERM:["additiveExpression"],ISIRI:["additiveExpression"],ISURI:["additiveExpression"],ISBLANK:["additiveExpression"],ISLITERAL:["additiveExpression"],ISNUMERIC:["additiveExpression"],TRUE:["additiveExpression"],FALSE:["additiveExpression"],COUNT:["additiveExpression"],SUM:["additiveExpression"],MIN:["additiveExpression"],MAX:["additiveExpression"],AVG:["additiveExpression"],SAMPLE:["additiveExpression"],GROUP_CONCAT:["additiveExpression"],SUBSTR:["additiveExpression"],REPLACE:["additiveExpression"],REGEX:["additiveExpression"],EXISTS:["additiveExpression"],NOT:["additiveExpression"],IRI_REF:["additiveExpression"],STRING_LITERAL1:["additiveExpression"],STRING_LITERAL2:["additiveExpression"],STRING_LITERAL_LONG1:["additiveExpression"],STRING_LITERAL_LONG2:["additiveExpression"],INTEGER:["additiveExpression"],DECIMAL:["additiveExpression"],DOUBLE:["additiveExpression"],INTEGER_POSITIVE:["additiveExpression"],DECIMAL_POSITIVE:["additiveExpression"],DOUBLE_POSITIVE:["additiveExpression"],INTEGER_NEGATIVE:["additiveExpression"],DECIMAL_NEGATIVE:["additiveExpression"],DOUBLE_NEGATIVE:["additiveExpression"],PNAME_LN:["additiveExpression"],PNAME_NS:["additiveExpression"]},numericLiteral:{INTEGER:["numericLiteralUnsigned"],DECIMAL:["numericLiteralUnsigned"],DOUBLE:["numericLiteralUnsigned"],INTEGER_POSITIVE:["numericLiteralPositive"],DECIMAL_POSITIVE:["numericLiteralPositive"],DOUBLE_POSITIVE:["numericLiteralPositive"],INTEGER_NEGATIVE:["numericLiteralNegative"],DECIMAL_NEGATIVE:["numericLiteralNegative"],DOUBLE_NEGATIVE:["numericLiteralNegative"]},numericLiteralNegative:{INTEGER_NEGATIVE:["INTEGER_NEGATIVE"],DECIMAL_NEGATIVE:["DECIMAL_NEGATIVE"],DOUBLE_NEGATIVE:["DOUBLE_NEGATIVE"]},numericLiteralPositive:{INTEGER_POSITIVE:["INTEGER_POSITIVE"],DECIMAL_POSITIVE:["DECIMAL_POSITIVE"],DOUBLE_POSITIVE:["DOUBLE_POSITIVE"]},numericLiteralUnsigned:{INTEGER:["INTEGER"],DECIMAL:["DECIMAL"],DOUBLE:["DOUBLE"]},object:{"(":["graphNode"],"[":["graphNode"],VAR1:["graphNode"],VAR2:["graphNode"],NIL:["graphNode"],IRI_REF:["graphNode"],TRUE:["graphNode"],FALSE:["graphNode"],BLANK_NODE_LABEL:["graphNode"],ANON:["graphNode"],PNAME_LN:["graphNode"],PNAME_NS:["graphNode"],STRING_LITERAL1:["graphNode"],STRING_LITERAL2:["graphNode"],STRING_LITERAL_LONG1:["graphNode"],STRING_LITERAL_LONG2:["graphNode"],INTEGER:["graphNode"],DECIMAL:["graphNode"],DOUBLE:["graphNode"],INTEGER_POSITIVE:["graphNode"],DECIMAL_POSITIVE:["graphNode"],DOUBLE_POSITIVE:["graphNode"],INTEGER_NEGATIVE:["graphNode"],DECIMAL_NEGATIVE:["graphNode"],DOUBLE_NEGATIVE:["graphNode"]},objectList:{"(":["object","*[,,object]"],"[":["object","*[,,object]"],VAR1:["object","*[,,object]"],VAR2:["object","*[,,object]"],NIL:["object","*[,,object]"],IRI_REF:["object","*[,,object]"],TRUE:["object","*[,,object]"],FALSE:["object","*[,,object]"],BLANK_NODE_LABEL:["object","*[,,object]"],ANON:["object","*[,,object]"],PNAME_LN:["object","*[,,object]"],PNAME_NS:["object","*[,,object]"],STRING_LITERAL1:["object","*[,,object]"],STRING_LITERAL2:["object","*[,,object]"],STRING_LITERAL_LONG1:["object","*[,,object]"],STRING_LITERAL_LONG2:["object","*[,,object]"],INTEGER:["object","*[,,object]"],DECIMAL:["object","*[,,object]"],DOUBLE:["object","*[,,object]"],INTEGER_POSITIVE:["object","*[,,object]"],DECIMAL_POSITIVE:["object","*[,,object]"],DOUBLE_POSITIVE:["object","*[,,object]"],INTEGER_NEGATIVE:["object","*[,,object]"],DECIMAL_NEGATIVE:["object","*[,,object]"],DOUBLE_NEGATIVE:["object","*[,,object]"]},objectListPath:{"(":["objectPath","*[,,objectPath]"],"[":["objectPath","*[,,objectPath]"],VAR1:["objectPath","*[,,objectPath]"],VAR2:["objectPath","*[,,objectPath]"],NIL:["objectPath","*[,,objectPath]"],IRI_REF:["objectPath","*[,,objectPath]"],TRUE:["objectPath","*[,,objectPath]"],FALSE:["objectPath","*[,,objectPath]"],BLANK_NODE_LABEL:["objectPath","*[,,objectPath]"],ANON:["objectPath","*[,,objectPath]"],PNAME_LN:["objectPath","*[,,objectPath]"],PNAME_NS:["objectPath","*[,,objectPath]"],STRING_LITERAL1:["objectPath","*[,,objectPath]"],STRING_LITERAL2:["objectPath","*[,,objectPath]"],STRING_LITERAL_LONG1:["objectPath","*[,,objectPath]"],STRING_LITERAL_LONG2:["objectPath","*[,,objectPath]"],INTEGER:["objectPath","*[,,objectPath]"],DECIMAL:["objectPath","*[,,objectPath]"],DOUBLE:["objectPath","*[,,objectPath]"],INTEGER_POSITIVE:["objectPath","*[,,objectPath]"],DECIMAL_POSITIVE:["objectPath","*[,,objectPath]"],DOUBLE_POSITIVE:["objectPath","*[,,objectPath]"],INTEGER_NEGATIVE:["objectPath","*[,,objectPath]"],DECIMAL_NEGATIVE:["objectPath","*[,,objectPath]"],DOUBLE_NEGATIVE:["objectPath","*[,,objectPath]"]},objectPath:{"(":["graphNodePath"],"[":["graphNodePath"],VAR1:["graphNodePath"],VAR2:["graphNodePath"],NIL:["graphNodePath"],IRI_REF:["graphNodePath"],TRUE:["graphNodePath"],FALSE:["graphNodePath"],BLANK_NODE_LABEL:["graphNodePath"],ANON:["graphNodePath"],PNAME_LN:["graphNodePath"],PNAME_NS:["graphNodePath"],STRING_LITERAL1:["graphNodePath"],STRING_LITERAL2:["graphNodePath"],STRING_LITERAL_LONG1:["graphNodePath"],STRING_LITERAL_LONG2:["graphNodePath"],INTEGER:["graphNodePath"],DECIMAL:["graphNodePath"],DOUBLE:["graphNodePath"],INTEGER_POSITIVE:["graphNodePath"],DECIMAL_POSITIVE:["graphNodePath"],DOUBLE_POSITIVE:["graphNodePath"],INTEGER_NEGATIVE:["graphNodePath"],DECIMAL_NEGATIVE:["graphNodePath"],DOUBLE_NEGATIVE:["graphNodePath"]},offsetClause:{OFFSET:["OFFSET","INTEGER"]},optionalGraphPattern:{OPTIONAL:["OPTIONAL","groupGraphPattern"]},"or([*,expression])":{"*":["*"],"!":["expression"],"+":["expression"],"-":["expression"],VAR1:["expression"],VAR2:["expression"],"(":["expression"],STR:["expression"],LANG:["expression"],LANGMATCHES:["expression"],DATATYPE:["expression"],BOUND:["expression"],IRI:["expression"],URI:["expression"],BNODE:["expression"],RAND:["expression"],ABS:["expression"],CEIL:["expression"],FLOOR:["expression"],ROUND:["expression"],CONCAT:["expression"],STRLEN:["expression"],UCASE:["expression"],LCASE:["expression"],ENCODE_FOR_URI:["expression"],CONTAINS:["expression"],STRSTARTS:["expression"],STRENDS:["expression"],STRBEFORE:["expression"],STRAFTER:["expression"],YEAR:["expression"],MONTH:["expression"],DAY:["expression"],HOURS:["expression"],MINUTES:["expression"],SECONDS:["expression"],TIMEZONE:["expression"],TZ:["expression"],NOW:["expression"],UUID:["expression"],STRUUID:["expression"],MD5:["expression"],SHA1:["expression"],SHA256:["expression"],SHA384:["expression"],SHA512:["expression"],COALESCE:["expression"],IF:["expression"],STRLANG:["expression"],STRDT:["expression"],SAMETERM:["expression"],ISIRI:["expression"],ISURI:["expression"],ISBLANK:["expression"],ISLITERAL:["expression"],ISNUMERIC:["expression"],TRUE:["expression"],FALSE:["expression"],COUNT:["expression"],SUM:["expression"],MIN:["expression"],MAX:["expression"],AVG:["expression"],SAMPLE:["expression"],GROUP_CONCAT:["expression"],SUBSTR:["expression"],REPLACE:["expression"],REGEX:["expression"],EXISTS:["expression"],NOT:["expression"],IRI_REF:["expression"],STRING_LITERAL1:["expression"],STRING_LITERAL2:["expression"],STRING_LITERAL_LONG1:["expression"],STRING_LITERAL_LONG2:["expression"],INTEGER:["expression"],DECIMAL:["expression"],DOUBLE:["expression"],INTEGER_POSITIVE:["expression"],DECIMAL_POSITIVE:["expression"],DOUBLE_POSITIVE:["expression"],INTEGER_NEGATIVE:["expression"],DECIMAL_NEGATIVE:["expression"],DOUBLE_NEGATIVE:["expression"],PNAME_LN:["expression"],PNAME_NS:["expression"]},"or([+or([var,[ (,expression,AS,var,)]]),*])":{"(":["+or([var,[ (,expression,AS,var,)]])"],VAR1:["+or([var,[ (,expression,AS,var,)]])"],VAR2:["+or([var,[ (,expression,AS,var,)]])"],"*":["*"]},"or([+varOrIRIref,*])":{VAR1:["+varOrIRIref"],VAR2:["+varOrIRIref"],IRI_REF:["+varOrIRIref"],PNAME_LN:["+varOrIRIref"],PNAME_NS:["+varOrIRIref"],"*":["*"]},"or([ASC,DESC])":{ASC:["ASC"],DESC:["DESC"]},"or([DISTINCT,REDUCED])":{DISTINCT:["DISTINCT"],REDUCED:["REDUCED"]},"or([LANGTAG,[^^,iriRef]])":{LANGTAG:["LANGTAG"],"^^":["[^^,iriRef]"]},"or([NIL,[ (,*var,)]])":{NIL:["NIL"],"(":["[ (,*var,)]"]},"or([[ (,*dataBlockValue,)],NIL])":{"(":["[ (,*dataBlockValue,)]"],NIL:["NIL"]},"or([[ (,expression,)],NIL])":{"(":["[ (,expression,)]"],NIL:["NIL"]},"or([[*,unaryExpression],[/,unaryExpression]])":{"*":["[*,unaryExpression]"],"/":["[/,unaryExpression]"]},"or([[+,multiplicativeExpression],[-,multiplicativeExpression],[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]])":{"+":["[+,multiplicativeExpression]"],"-":["[-,multiplicativeExpression]"],INTEGER_POSITIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],DECIMAL_POSITIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],DOUBLE_POSITIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],INTEGER_NEGATIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],DECIMAL_NEGATIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"],DOUBLE_NEGATIVE:["[or([numericLiteralPositive,numericLiteralNegative]),?or([[*,unaryExpression],[/,unaryExpression]])]"]},"or([[,,or([},[integer,}]])],}])":{",":["[,,or([},[integer,}]])]"],"}":["}"]},"or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])":{"=":["[=,numericExpression]"],"!=":["[!=,numericExpression]"],"<":["[<,numericExpression]"],">":["[>,numericExpression]"],"<=":["[<=,numericExpression]"],">=":["[>=,numericExpression]"],IN:["[IN,expressionList]"],NOT:["[NOT,IN,expressionList]"]},"or([[constructTemplate,*datasetClause,whereClause,solutionModifier],[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]])":{"{":["[constructTemplate,*datasetClause,whereClause,solutionModifier]"],WHERE:["[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]"],FROM:["[*datasetClause,WHERE,{,?triplesTemplate,},solutionModifier]"]},"or([[deleteClause,?insertClause],insertClause])":{DELETE:["[deleteClause,?insertClause]"],INSERT:["insertClause"]},"or([[integer,or([[,,or([},[integer,}]])],}])],[,,integer,}]])":{INTEGER:["[integer,or([[,,or([},[integer,}]])],}])]"],",":["[,,integer,}]"]},"or([baseDecl,prefixDecl])":{BASE:["baseDecl"],PREFIX:["prefixDecl"]},"or([defaultGraphClause,namedGraphClause])":{IRI_REF:["defaultGraphClause"],PNAME_LN:["defaultGraphClause"],PNAME_NS:["defaultGraphClause"],NAMED:["namedGraphClause"]},"or([inlineDataOneVar,inlineDataFull])":{VAR1:["inlineDataOneVar"],VAR2:["inlineDataOneVar"],NIL:["inlineDataFull"],"(":["inlineDataFull"]},"or([iriRef,[NAMED,iriRef]])":{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],NAMED:["[NAMED,iriRef]"]},"or([iriRef,a])":{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],a:["a"]},"or([numericLiteralPositive,numericLiteralNegative])":{INTEGER_POSITIVE:["numericLiteralPositive"],DECIMAL_POSITIVE:["numericLiteralPositive"],DOUBLE_POSITIVE:["numericLiteralPositive"],INTEGER_NEGATIVE:["numericLiteralNegative"],DECIMAL_NEGATIVE:["numericLiteralNegative"],DOUBLE_NEGATIVE:["numericLiteralNegative"]},"or([queryAll,updateAll])":{CONSTRUCT:["queryAll"],DESCRIBE:["queryAll"],ASK:["queryAll"],SELECT:["queryAll"],INSERT:["updateAll"],DELETE:["updateAll"],LOAD:["updateAll"],CLEAR:["updateAll"],DROP:["updateAll"],ADD:["updateAll"],MOVE:["updateAll"],COPY:["updateAll"],CREATE:["updateAll"],WITH:["updateAll"],$:["updateAll"]},"or([selectQuery,constructQuery,describeQuery,askQuery])":{SELECT:["selectQuery"],CONSTRUCT:["constructQuery"],DESCRIBE:["describeQuery"],ASK:["askQuery"]},"or([subSelect,groupGraphPatternSub])":{SELECT:["subSelect"],"{":["groupGraphPatternSub"],OPTIONAL:["groupGraphPatternSub"],MINUS:["groupGraphPatternSub"],GRAPH:["groupGraphPatternSub"],SERVICE:["groupGraphPatternSub"],FILTER:["groupGraphPatternSub"],BIND:["groupGraphPatternSub"],VALUES:["groupGraphPatternSub"],VAR1:["groupGraphPatternSub"],VAR2:["groupGraphPatternSub"],NIL:["groupGraphPatternSub"],"(":["groupGraphPatternSub"],"[":["groupGraphPatternSub"],IRI_REF:["groupGraphPatternSub"],TRUE:["groupGraphPatternSub"],FALSE:["groupGraphPatternSub"],BLANK_NODE_LABEL:["groupGraphPatternSub"],ANON:["groupGraphPatternSub"],PNAME_LN:["groupGraphPatternSub"],PNAME_NS:["groupGraphPatternSub"],STRING_LITERAL1:["groupGraphPatternSub"],STRING_LITERAL2:["groupGraphPatternSub"],STRING_LITERAL_LONG1:["groupGraphPatternSub"],STRING_LITERAL_LONG2:["groupGraphPatternSub"],INTEGER:["groupGraphPatternSub"],DECIMAL:["groupGraphPatternSub"],DOUBLE:["groupGraphPatternSub"],INTEGER_POSITIVE:["groupGraphPatternSub"],DECIMAL_POSITIVE:["groupGraphPatternSub"],DOUBLE_POSITIVE:["groupGraphPatternSub"],INTEGER_NEGATIVE:["groupGraphPatternSub"],DECIMAL_NEGATIVE:["groupGraphPatternSub"],DOUBLE_NEGATIVE:["groupGraphPatternSub"],"}":["groupGraphPatternSub"]},"or([var,[ (,expression,AS,var,)]])":{VAR1:["var"],VAR2:["var"],"(":["[ (,expression,AS,var,)]"]},"or([verbPath,verbSimple])":{"^":["verbPath"],a:["verbPath"],"!":["verbPath"],"(":["verbPath"],IRI_REF:["verbPath"],PNAME_LN:["verbPath"],PNAME_NS:["verbPath"],VAR1:["verbSimple"],VAR2:["verbSimple"]},"or([},[integer,}]])":{"}":["}"],INTEGER:["[integer,}]"]},orderClause:{ORDER:["ORDER","BY","+orderCondition"]},orderCondition:{ASC:["or([ASC,DESC])","brackettedExpression"],DESC:["or([ASC,DESC])","brackettedExpression"],"(":["constraint"],STR:["constraint"],LANG:["constraint"],LANGMATCHES:["constraint"],DATATYPE:["constraint"],BOUND:["constraint"],IRI:["constraint"],URI:["constraint"],BNODE:["constraint"],RAND:["constraint"],ABS:["constraint"],CEIL:["constraint"],FLOOR:["constraint"],ROUND:["constraint"],CONCAT:["constraint"],STRLEN:["constraint"],UCASE:["constraint"],LCASE:["constraint"],ENCODE_FOR_URI:["constraint"],CONTAINS:["constraint"],STRSTARTS:["constraint"],STRENDS:["constraint"],STRBEFORE:["constraint"],STRAFTER:["constraint"],YEAR:["constraint"],MONTH:["constraint"],DAY:["constraint"],HOURS:["constraint"],MINUTES:["constraint"],SECONDS:["constraint"],TIMEZONE:["constraint"],TZ:["constraint"],NOW:["constraint"],UUID:["constraint"],STRUUID:["constraint"],MD5:["constraint"],SHA1:["constraint"],SHA256:["constraint"],SHA384:["constraint"],SHA512:["constraint"],COALESCE:["constraint"],IF:["constraint"],STRLANG:["constraint"],STRDT:["constraint"],SAMETERM:["constraint"],ISIRI:["constraint"],ISURI:["constraint"],ISBLANK:["constraint"],ISLITERAL:["constraint"],ISNUMERIC:["constraint"],SUBSTR:["constraint"],REPLACE:["constraint"],REGEX:["constraint"],EXISTS:["constraint"],NOT:["constraint"],IRI_REF:["constraint"],PNAME_LN:["constraint"],PNAME_NS:["constraint"],VAR1:["var"],VAR2:["var"]},path:{"^":["pathAlternative"],a:["pathAlternative"],"!":["pathAlternative"],"(":["pathAlternative"],IRI_REF:["pathAlternative"],PNAME_LN:["pathAlternative"],PNAME_NS:["pathAlternative"]},pathAlternative:{"^":["pathSequence","*[|,pathSequence]"],a:["pathSequence","*[|,pathSequence]"],"!":["pathSequence","*[|,pathSequence]"],"(":["pathSequence","*[|,pathSequence]"],IRI_REF:["pathSequence","*[|,pathSequence]"],PNAME_LN:["pathSequence","*[|,pathSequence]"],PNAME_NS:["pathSequence","*[|,pathSequence]"]},pathElt:{a:["pathPrimary","?pathMod"],"!":["pathPrimary","?pathMod"],"(":["pathPrimary","?pathMod"],IRI_REF:["pathPrimary","?pathMod"],PNAME_LN:["pathPrimary","?pathMod"],PNAME_NS:["pathPrimary","?pathMod"]},pathEltOrInverse:{a:["pathElt"],"!":["pathElt"],"(":["pathElt"],IRI_REF:["pathElt"],PNAME_LN:["pathElt"],PNAME_NS:["pathElt"],"^":["^","pathElt"]},pathMod:{"*":["*"],"?":["?"],"+":["+"],"{":["{","or([[integer,or([[,,or([},[integer,}]])],}])],[,,integer,}]])"]},pathNegatedPropertySet:{a:["pathOneInPropertySet"],"^":["pathOneInPropertySet"],IRI_REF:["pathOneInPropertySet"],PNAME_LN:["pathOneInPropertySet"],PNAME_NS:["pathOneInPropertySet"],"(":["(","?[pathOneInPropertySet,*[|,pathOneInPropertySet]]",")"]},pathOneInPropertySet:{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"],a:["a"],"^":["^","or([iriRef,a])"]},pathPrimary:{IRI_REF:["storeProperty","iriRef"],PNAME_LN:["storeProperty","iriRef"],PNAME_NS:["storeProperty","iriRef"],a:["storeProperty","a"],"!":["!","pathNegatedPropertySet"],"(":["(","path",")"]},pathSequence:{"^":["pathEltOrInverse","*[/,pathEltOrInverse]"],a:["pathEltOrInverse","*[/,pathEltOrInverse]"],"!":["pathEltOrInverse","*[/,pathEltOrInverse]"],"(":["pathEltOrInverse","*[/,pathEltOrInverse]"],IRI_REF:["pathEltOrInverse","*[/,pathEltOrInverse]"],PNAME_LN:["pathEltOrInverse","*[/,pathEltOrInverse]"],PNAME_NS:["pathEltOrInverse","*[/,pathEltOrInverse]"]},prefixDecl:{PREFIX:["PREFIX","PNAME_NS","IRI_REF"]},prefixedName:{PNAME_LN:["PNAME_LN"],PNAME_NS:["PNAME_NS"]},primaryExpression:{"(":["brackettedExpression"],STR:["builtInCall"],LANG:["builtInCall"],LANGMATCHES:["builtInCall"],DATATYPE:["builtInCall"],BOUND:["builtInCall"],IRI:["builtInCall"],URI:["builtInCall"],BNODE:["builtInCall"],RAND:["builtInCall"],ABS:["builtInCall"],CEIL:["builtInCall"],FLOOR:["builtInCall"],ROUND:["builtInCall"],CONCAT:["builtInCall"],STRLEN:["builtInCall"],UCASE:["builtInCall"],LCASE:["builtInCall"],ENCODE_FOR_URI:["builtInCall"],CONTAINS:["builtInCall"],STRSTARTS:["builtInCall"],STRENDS:["builtInCall"],STRBEFORE:["builtInCall"],STRAFTER:["builtInCall"],YEAR:["builtInCall"],MONTH:["builtInCall"],DAY:["builtInCall"],HOURS:["builtInCall"],MINUTES:["builtInCall"],SECONDS:["builtInCall"],TIMEZONE:["builtInCall"],TZ:["builtInCall"],NOW:["builtInCall"],UUID:["builtInCall"],STRUUID:["builtInCall"],MD5:["builtInCall"],SHA1:["builtInCall"],SHA256:["builtInCall"],SHA384:["builtInCall"],SHA512:["builtInCall"],COALESCE:["builtInCall"],IF:["builtInCall"],STRLANG:["builtInCall"],STRDT:["builtInCall"],SAMETERM:["builtInCall"],ISIRI:["builtInCall"],ISURI:["builtInCall"],ISBLANK:["builtInCall"],ISLITERAL:["builtInCall"],ISNUMERIC:["builtInCall"],SUBSTR:["builtInCall"],REPLACE:["builtInCall"],REGEX:["builtInCall"],EXISTS:["builtInCall"],NOT:["builtInCall"],IRI_REF:["iriRefOrFunction"],PNAME_LN:["iriRefOrFunction"],PNAME_NS:["iriRefOrFunction"],STRING_LITERAL1:["rdfLiteral"],STRING_LITERAL2:["rdfLiteral"],STRING_LITERAL_LONG1:["rdfLiteral"],STRING_LITERAL_LONG2:["rdfLiteral"],INTEGER:["numericLiteral"],DECIMAL:["numericLiteral"],DOUBLE:["numericLiteral"],INTEGER_POSITIVE:["numericLiteral"],DECIMAL_POSITIVE:["numericLiteral"],DOUBLE_POSITIVE:["numericLiteral"],INTEGER_NEGATIVE:["numericLiteral"],DECIMAL_NEGATIVE:["numericLiteral"],DOUBLE_NEGATIVE:["numericLiteral"],TRUE:["booleanLiteral"],FALSE:["booleanLiteral"],VAR1:["var"],VAR2:["var"],COUNT:["aggregate"],SUM:["aggregate"],MIN:["aggregate"],MAX:["aggregate"],AVG:["aggregate"],SAMPLE:["aggregate"],GROUP_CONCAT:["aggregate"]},prologue:{BASE:["*or([baseDecl,prefixDecl])"],PREFIX:["*or([baseDecl,prefixDecl])"],$:["*or([baseDecl,prefixDecl])"],CONSTRUCT:["*or([baseDecl,prefixDecl])"],DESCRIBE:["*or([baseDecl,prefixDecl])"],ASK:["*or([baseDecl,prefixDecl])"],INSERT:["*or([baseDecl,prefixDecl])"],DELETE:["*or([baseDecl,prefixDecl])"],SELECT:["*or([baseDecl,prefixDecl])"],LOAD:["*or([baseDecl,prefixDecl])"],CLEAR:["*or([baseDecl,prefixDecl])"],DROP:["*or([baseDecl,prefixDecl])"],ADD:["*or([baseDecl,prefixDecl])"],MOVE:["*or([baseDecl,prefixDecl])"],COPY:["*or([baseDecl,prefixDecl])"],CREATE:["*or([baseDecl,prefixDecl])"],WITH:["*or([baseDecl,prefixDecl])"]},propertyList:{a:["propertyListNotEmpty"],VAR1:["propertyListNotEmpty"],VAR2:["propertyListNotEmpty"],IRI_REF:["propertyListNotEmpty"],PNAME_LN:["propertyListNotEmpty"],PNAME_NS:["propertyListNotEmpty"],".":[],"}":[],GRAPH:[]},propertyListNotEmpty:{a:["verb","objectList","*[;,?[verb,objectList]]"],VAR1:["verb","objectList","*[;,?[verb,objectList]]"],VAR2:["verb","objectList","*[;,?[verb,objectList]]"],IRI_REF:["verb","objectList","*[;,?[verb,objectList]]"],PNAME_LN:["verb","objectList","*[;,?[verb,objectList]]"],PNAME_NS:["verb","objectList","*[;,?[verb,objectList]]"]},propertyListPath:{a:["propertyListNotEmpty"],VAR1:["propertyListNotEmpty"],VAR2:["propertyListNotEmpty"],IRI_REF:["propertyListNotEmpty"],PNAME_LN:["propertyListNotEmpty"],PNAME_NS:["propertyListNotEmpty"],".":[],"{":[],OPTIONAL:[],MINUS:[],GRAPH:[],SERVICE:[],FILTER:[],BIND:[],VALUES:[],"}":[]},propertyListPathNotEmpty:{VAR1:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],VAR2:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],"^":["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],a:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],"!":["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],"(":["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],IRI_REF:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],PNAME_LN:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"],PNAME_NS:["or([verbPath,verbSimple])","objectListPath","*[;,?[or([verbPath,verbSimple]),objectList]]"]},quadData:{"{":["{","disallowVars","quads","allowVars","}"]},quadDataNoBnodes:{"{":["{","disallowBnodes","disallowVars","quads","allowVars","allowBnodes","}"]},quadPattern:{"{":["{","quads","}"]},quadPatternNoBnodes:{"{":["{","disallowBnodes","quads","allowBnodes","}"]},quads:{GRAPH:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],VAR1:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],VAR2:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],NIL:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],"(":["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],"[":["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],IRI_REF:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],TRUE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],FALSE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],BLANK_NODE_LABEL:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],ANON:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],PNAME_LN:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],PNAME_NS:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],STRING_LITERAL1:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],STRING_LITERAL2:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],STRING_LITERAL_LONG1:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],STRING_LITERAL_LONG2:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],INTEGER:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DECIMAL:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DOUBLE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],INTEGER_POSITIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DECIMAL_POSITIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DOUBLE_POSITIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],INTEGER_NEGATIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DECIMAL_NEGATIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],DOUBLE_NEGATIVE:["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"],"}":["?triplesTemplate","*[quadsNotTriples,?.,?triplesTemplate]"]},quadsNotTriples:{GRAPH:["GRAPH","varOrIRIref","{","?triplesTemplate","}"]},queryAll:{CONSTRUCT:["or([selectQuery,constructQuery,describeQuery,askQuery])","valuesClause"],DESCRIBE:["or([selectQuery,constructQuery,describeQuery,askQuery])","valuesClause"],ASK:["or([selectQuery,constructQuery,describeQuery,askQuery])","valuesClause"],SELECT:["or([selectQuery,constructQuery,describeQuery,askQuery])","valuesClause"]},rdfLiteral:{STRING_LITERAL1:["string","?or([LANGTAG,[^^,iriRef]])"],STRING_LITERAL2:["string","?or([LANGTAG,[^^,iriRef]])"],STRING_LITERAL_LONG1:["string","?or([LANGTAG,[^^,iriRef]])"],STRING_LITERAL_LONG2:["string","?or([LANGTAG,[^^,iriRef]])"]},regexExpression:{REGEX:["REGEX","(","expression",",","expression","?[,,expression]",")"]},relationalExpression:{"!":["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"+":["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"-":["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],VAR1:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],VAR2:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],"(":["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STR:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],LANG:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],LANGMATCHES:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DATATYPE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],BOUND:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],IRI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],URI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],BNODE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],RAND:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ABS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],CEIL:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],FLOOR:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ROUND:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],CONCAT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRLEN:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],UCASE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],LCASE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ENCODE_FOR_URI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],CONTAINS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRSTARTS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRENDS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRBEFORE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRAFTER:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],YEAR:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MONTH:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DAY:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],HOURS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MINUTES:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SECONDS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],TIMEZONE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],TZ:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],NOW:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],UUID:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRUUID:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MD5:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SHA1:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SHA256:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SHA384:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SHA512:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],COALESCE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],IF:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRLANG:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRDT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SAMETERM:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISIRI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISURI:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISBLANK:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISLITERAL:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],ISNUMERIC:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],TRUE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],FALSE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],COUNT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SUM:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MIN:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],MAX:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],AVG:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SAMPLE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],GROUP_CONCAT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],SUBSTR:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],REPLACE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],REGEX:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],EXISTS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],NOT:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],IRI_REF:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRING_LITERAL1:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRING_LITERAL2:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRING_LITERAL_LONG1:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],STRING_LITERAL_LONG2:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],INTEGER:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DECIMAL:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DOUBLE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],INTEGER_POSITIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DECIMAL_POSITIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DOUBLE_POSITIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],INTEGER_NEGATIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DECIMAL_NEGATIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],DOUBLE_NEGATIVE:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],PNAME_LN:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"],PNAME_NS:["numericExpression","?or([[=,numericExpression],[!=,numericExpression],[<,numericExpression],[>,numericExpression],[<=,numericExpression],[>=,numericExpression],[IN,expressionList],[NOT,IN,expressionList]])"]},selectClause:{SELECT:["SELECT","?or([DISTINCT,REDUCED])","or([+or([var,[ (,expression,AS,var,)]]),*])"]},selectQuery:{SELECT:["selectClause","*datasetClause","whereClause","solutionModifier"]},serviceGraphPattern:{SERVICE:["SERVICE","?SILENT","varOrIRIref","groupGraphPattern"]},solutionModifier:{LIMIT:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],OFFSET:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],ORDER:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],HAVING:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],GROUP:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],VALUES:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],$:["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"],"}":["?groupClause","?havingClause","?orderClause","?limitOffsetClauses"]},sourceSelector:{IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"]},sparql11:{$:["prologue","or([queryAll,updateAll])","$"],CONSTRUCT:["prologue","or([queryAll,updateAll])","$"],DESCRIBE:["prologue","or([queryAll,updateAll])","$"],ASK:["prologue","or([queryAll,updateAll])","$"],INSERT:["prologue","or([queryAll,updateAll])","$"],DELETE:["prologue","or([queryAll,updateAll])","$"],SELECT:["prologue","or([queryAll,updateAll])","$"],LOAD:["prologue","or([queryAll,updateAll])","$"],CLEAR:["prologue","or([queryAll,updateAll])","$"],DROP:["prologue","or([queryAll,updateAll])","$"],ADD:["prologue","or([queryAll,updateAll])","$"],MOVE:["prologue","or([queryAll,updateAll])","$"],COPY:["prologue","or([queryAll,updateAll])","$"],CREATE:["prologue","or([queryAll,updateAll])","$"],WITH:["prologue","or([queryAll,updateAll])","$"],BASE:["prologue","or([queryAll,updateAll])","$"],PREFIX:["prologue","or([queryAll,updateAll])","$"]},storeProperty:{VAR1:[],VAR2:[],IRI_REF:[],PNAME_LN:[],PNAME_NS:[],a:[]},strReplaceExpression:{REPLACE:["REPLACE","(","expression",",","expression",",","expression","?[,,expression]",")"]},string:{STRING_LITERAL1:["STRING_LITERAL1"],STRING_LITERAL2:["STRING_LITERAL2"],STRING_LITERAL_LONG1:["STRING_LITERAL_LONG1"],STRING_LITERAL_LONG2:["STRING_LITERAL_LONG2"]},subSelect:{SELECT:["selectClause","whereClause","solutionModifier","valuesClause"]},substringExpression:{SUBSTR:["SUBSTR","(","expression",",","expression","?[,,expression]",")"]},triplesBlock:{VAR1:["triplesSameSubjectPath","?[.,?triplesBlock]"],VAR2:["triplesSameSubjectPath","?[.,?triplesBlock]"],NIL:["triplesSameSubjectPath","?[.,?triplesBlock]"],"(":["triplesSameSubjectPath","?[.,?triplesBlock]"],"[":["triplesSameSubjectPath","?[.,?triplesBlock]"],IRI_REF:["triplesSameSubjectPath","?[.,?triplesBlock]"],TRUE:["triplesSameSubjectPath","?[.,?triplesBlock]"],FALSE:["triplesSameSubjectPath","?[.,?triplesBlock]"],BLANK_NODE_LABEL:["triplesSameSubjectPath","?[.,?triplesBlock]"],ANON:["triplesSameSubjectPath","?[.,?triplesBlock]"],PNAME_LN:["triplesSameSubjectPath","?[.,?triplesBlock]"],PNAME_NS:["triplesSameSubjectPath","?[.,?triplesBlock]"],STRING_LITERAL1:["triplesSameSubjectPath","?[.,?triplesBlock]"],STRING_LITERAL2:["triplesSameSubjectPath","?[.,?triplesBlock]"],STRING_LITERAL_LONG1:["triplesSameSubjectPath","?[.,?triplesBlock]"],STRING_LITERAL_LONG2:["triplesSameSubjectPath","?[.,?triplesBlock]"],INTEGER:["triplesSameSubjectPath","?[.,?triplesBlock]"],DECIMAL:["triplesSameSubjectPath","?[.,?triplesBlock]"],DOUBLE:["triplesSameSubjectPath","?[.,?triplesBlock]"],INTEGER_POSITIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],DECIMAL_POSITIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],DOUBLE_POSITIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],INTEGER_NEGATIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],DECIMAL_NEGATIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"],DOUBLE_NEGATIVE:["triplesSameSubjectPath","?[.,?triplesBlock]"]},triplesNode:{"(":["collection"],"[":["blankNodePropertyList"]},triplesNodePath:{"(":["collectionPath"],"[":["blankNodePropertyListPath"]},triplesSameSubject:{VAR1:["varOrTerm","propertyListNotEmpty"],VAR2:["varOrTerm","propertyListNotEmpty"],NIL:["varOrTerm","propertyListNotEmpty"],IRI_REF:["varOrTerm","propertyListNotEmpty"],TRUE:["varOrTerm","propertyListNotEmpty"],FALSE:["varOrTerm","propertyListNotEmpty"],BLANK_NODE_LABEL:["varOrTerm","propertyListNotEmpty"],ANON:["varOrTerm","propertyListNotEmpty"],PNAME_LN:["varOrTerm","propertyListNotEmpty"],PNAME_NS:["varOrTerm","propertyListNotEmpty"],STRING_LITERAL1:["varOrTerm","propertyListNotEmpty"],STRING_LITERAL2:["varOrTerm","propertyListNotEmpty"],STRING_LITERAL_LONG1:["varOrTerm","propertyListNotEmpty"],STRING_LITERAL_LONG2:["varOrTerm","propertyListNotEmpty"],INTEGER:["varOrTerm","propertyListNotEmpty"],DECIMAL:["varOrTerm","propertyListNotEmpty"],DOUBLE:["varOrTerm","propertyListNotEmpty"],INTEGER_POSITIVE:["varOrTerm","propertyListNotEmpty"],DECIMAL_POSITIVE:["varOrTerm","propertyListNotEmpty"],DOUBLE_POSITIVE:["varOrTerm","propertyListNotEmpty"],INTEGER_NEGATIVE:["varOrTerm","propertyListNotEmpty"],DECIMAL_NEGATIVE:["varOrTerm","propertyListNotEmpty"],DOUBLE_NEGATIVE:["varOrTerm","propertyListNotEmpty"],"(":["triplesNode","propertyList"],"[":["triplesNode","propertyList"]},triplesSameSubjectPath:{VAR1:["varOrTerm","propertyListPathNotEmpty"],VAR2:["varOrTerm","propertyListPathNotEmpty"],NIL:["varOrTerm","propertyListPathNotEmpty"],IRI_REF:["varOrTerm","propertyListPathNotEmpty"],TRUE:["varOrTerm","propertyListPathNotEmpty"],FALSE:["varOrTerm","propertyListPathNotEmpty"],BLANK_NODE_LABEL:["varOrTerm","propertyListPathNotEmpty"],ANON:["varOrTerm","propertyListPathNotEmpty"],PNAME_LN:["varOrTerm","propertyListPathNotEmpty"],PNAME_NS:["varOrTerm","propertyListPathNotEmpty"],STRING_LITERAL1:["varOrTerm","propertyListPathNotEmpty"],STRING_LITERAL2:["varOrTerm","propertyListPathNotEmpty"],STRING_LITERAL_LONG1:["varOrTerm","propertyListPathNotEmpty"],STRING_LITERAL_LONG2:["varOrTerm","propertyListPathNotEmpty"],INTEGER:["varOrTerm","propertyListPathNotEmpty"],DECIMAL:["varOrTerm","propertyListPathNotEmpty"],DOUBLE:["varOrTerm","propertyListPathNotEmpty"],INTEGER_POSITIVE:["varOrTerm","propertyListPathNotEmpty"],DECIMAL_POSITIVE:["varOrTerm","propertyListPathNotEmpty"],DOUBLE_POSITIVE:["varOrTerm","propertyListPathNotEmpty"],INTEGER_NEGATIVE:["varOrTerm","propertyListPathNotEmpty"],DECIMAL_NEGATIVE:["varOrTerm","propertyListPathNotEmpty"],DOUBLE_NEGATIVE:["varOrTerm","propertyListPathNotEmpty"],"(":["triplesNodePath","propertyListPath"],"[":["triplesNodePath","propertyListPath"]},triplesTemplate:{VAR1:["triplesSameSubject","?[.,?triplesTemplate]"],VAR2:["triplesSameSubject","?[.,?triplesTemplate]"],NIL:["triplesSameSubject","?[.,?triplesTemplate]"],"(":["triplesSameSubject","?[.,?triplesTemplate]"],"[":["triplesSameSubject","?[.,?triplesTemplate]"],IRI_REF:["triplesSameSubject","?[.,?triplesTemplate]"],TRUE:["triplesSameSubject","?[.,?triplesTemplate]"],FALSE:["triplesSameSubject","?[.,?triplesTemplate]"],BLANK_NODE_LABEL:["triplesSameSubject","?[.,?triplesTemplate]"],ANON:["triplesSameSubject","?[.,?triplesTemplate]"],PNAME_LN:["triplesSameSubject","?[.,?triplesTemplate]"],PNAME_NS:["triplesSameSubject","?[.,?triplesTemplate]"],STRING_LITERAL1:["triplesSameSubject","?[.,?triplesTemplate]"],STRING_LITERAL2:["triplesSameSubject","?[.,?triplesTemplate]"],STRING_LITERAL_LONG1:["triplesSameSubject","?[.,?triplesTemplate]"],STRING_LITERAL_LONG2:["triplesSameSubject","?[.,?triplesTemplate]"],INTEGER:["triplesSameSubject","?[.,?triplesTemplate]"],DECIMAL:["triplesSameSubject","?[.,?triplesTemplate]"],DOUBLE:["triplesSameSubject","?[.,?triplesTemplate]"],INTEGER_POSITIVE:["triplesSameSubject","?[.,?triplesTemplate]"],DECIMAL_POSITIVE:["triplesSameSubject","?[.,?triplesTemplate]"],DOUBLE_POSITIVE:["triplesSameSubject","?[.,?triplesTemplate]"],INTEGER_NEGATIVE:["triplesSameSubject","?[.,?triplesTemplate]"],DECIMAL_NEGATIVE:["triplesSameSubject","?[.,?triplesTemplate]"],DOUBLE_NEGATIVE:["triplesSameSubject","?[.,?triplesTemplate]"]},unaryExpression:{"!":["!","primaryExpression"],"+":["+","primaryExpression"],"-":["-","primaryExpression"],VAR1:["primaryExpression"],VAR2:["primaryExpression"],"(":["primaryExpression"],STR:["primaryExpression"],LANG:["primaryExpression"],LANGMATCHES:["primaryExpression"],DATATYPE:["primaryExpression"],BOUND:["primaryExpression"],IRI:["primaryExpression"],URI:["primaryExpression"],BNODE:["primaryExpression"],RAND:["primaryExpression"],ABS:["primaryExpression"],CEIL:["primaryExpression"],FLOOR:["primaryExpression"],ROUND:["primaryExpression"],CONCAT:["primaryExpression"],STRLEN:["primaryExpression"],UCASE:["primaryExpression"],LCASE:["primaryExpression"],ENCODE_FOR_URI:["primaryExpression"],CONTAINS:["primaryExpression"],STRSTARTS:["primaryExpression"],STRENDS:["primaryExpression"],STRBEFORE:["primaryExpression"],STRAFTER:["primaryExpression"],YEAR:["primaryExpression"],MONTH:["primaryExpression"],DAY:["primaryExpression"],HOURS:["primaryExpression"],MINUTES:["primaryExpression"],SECONDS:["primaryExpression"],TIMEZONE:["primaryExpression"],TZ:["primaryExpression"],NOW:["primaryExpression"],UUID:["primaryExpression"],STRUUID:["primaryExpression"],MD5:["primaryExpression"],SHA1:["primaryExpression"],SHA256:["primaryExpression"],SHA384:["primaryExpression"],SHA512:["primaryExpression"],COALESCE:["primaryExpression"],IF:["primaryExpression"],STRLANG:["primaryExpression"],STRDT:["primaryExpression"],SAMETERM:["primaryExpression"],ISIRI:["primaryExpression"],ISURI:["primaryExpression"],ISBLANK:["primaryExpression"],ISLITERAL:["primaryExpression"],ISNUMERIC:["primaryExpression"],TRUE:["primaryExpression"],FALSE:["primaryExpression"],COUNT:["primaryExpression"],SUM:["primaryExpression"],MIN:["primaryExpression"],MAX:["primaryExpression"],AVG:["primaryExpression"],SAMPLE:["primaryExpression"],GROUP_CONCAT:["primaryExpression"],SUBSTR:["primaryExpression"],REPLACE:["primaryExpression"],REGEX:["primaryExpression"],EXISTS:["primaryExpression"],NOT:["primaryExpression"],IRI_REF:["primaryExpression"],STRING_LITERAL1:["primaryExpression"],STRING_LITERAL2:["primaryExpression"],STRING_LITERAL_LONG1:["primaryExpression"],STRING_LITERAL_LONG2:["primaryExpression"],INTEGER:["primaryExpression"],DECIMAL:["primaryExpression"],DOUBLE:["primaryExpression"],INTEGER_POSITIVE:["primaryExpression"],DECIMAL_POSITIVE:["primaryExpression"],DOUBLE_POSITIVE:["primaryExpression"],INTEGER_NEGATIVE:["primaryExpression"],DECIMAL_NEGATIVE:["primaryExpression"],DOUBLE_NEGATIVE:["primaryExpression"],PNAME_LN:["primaryExpression"],PNAME_NS:["primaryExpression"]},update:{INSERT:["prologue","?[update1,?[;,update]]"],DELETE:["prologue","?[update1,?[;,update]]"],LOAD:["prologue","?[update1,?[;,update]]"],CLEAR:["prologue","?[update1,?[;,update]]"],DROP:["prologue","?[update1,?[;,update]]"],ADD:["prologue","?[update1,?[;,update]]"],MOVE:["prologue","?[update1,?[;,update]]"],COPY:["prologue","?[update1,?[;,update]]"],CREATE:["prologue","?[update1,?[;,update]]"],WITH:["prologue","?[update1,?[;,update]]"],BASE:["prologue","?[update1,?[;,update]]"],PREFIX:["prologue","?[update1,?[;,update]]"],$:["prologue","?[update1,?[;,update]]"]},update1:{LOAD:["load"],CLEAR:["clear"],DROP:["drop"],ADD:["add"],MOVE:["move"],COPY:["copy"],CREATE:["create"],INSERT:["INSERT","insert1"],DELETE:["DELETE","delete1"],WITH:["modify"]},updateAll:{INSERT:["?[update1,?[;,update]]"],DELETE:["?[update1,?[;,update]]"],LOAD:["?[update1,?[;,update]]"],CLEAR:["?[update1,?[;,update]]"],DROP:["?[update1,?[;,update]]"],ADD:["?[update1,?[;,update]]"],MOVE:["?[update1,?[;,update]]"],COPY:["?[update1,?[;,update]]"],CREATE:["?[update1,?[;,update]]"],WITH:["?[update1,?[;,update]]"],$:["?[update1,?[;,update]]"]},usingClause:{USING:["USING","or([iriRef,[NAMED,iriRef]])"]},valueLogical:{"!":["relationalExpression"],"+":["relationalExpression"],"-":["relationalExpression"],VAR1:["relationalExpression"],VAR2:["relationalExpression"],"(":["relationalExpression"],STR:["relationalExpression"],LANG:["relationalExpression"],LANGMATCHES:["relationalExpression"],DATATYPE:["relationalExpression"],BOUND:["relationalExpression"],IRI:["relationalExpression"],URI:["relationalExpression"],BNODE:["relationalExpression"],RAND:["relationalExpression"],ABS:["relationalExpression"],CEIL:["relationalExpression"],FLOOR:["relationalExpression"],ROUND:["relationalExpression"],CONCAT:["relationalExpression"],STRLEN:["relationalExpression"],UCASE:["relationalExpression"],LCASE:["relationalExpression"],ENCODE_FOR_URI:["relationalExpression"],CONTAINS:["relationalExpression"],STRSTARTS:["relationalExpression"],STRENDS:["relationalExpression"],STRBEFORE:["relationalExpression"],STRAFTER:["relationalExpression"],YEAR:["relationalExpression"],MONTH:["relationalExpression"],DAY:["relationalExpression"],HOURS:["relationalExpression"],MINUTES:["relationalExpression"],SECONDS:["relationalExpression"],TIMEZONE:["relationalExpression"],TZ:["relationalExpression"],NOW:["relationalExpression"],UUID:["relationalExpression"],STRUUID:["relationalExpression"],MD5:["relationalExpression"],SHA1:["relationalExpression"],SHA256:["relationalExpression"],SHA384:["relationalExpression"],SHA512:["relationalExpression"],COALESCE:["relationalExpression"],IF:["relationalExpression"],STRLANG:["relationalExpression"],STRDT:["relationalExpression"],SAMETERM:["relationalExpression"],ISIRI:["relationalExpression"],ISURI:["relationalExpression"],ISBLANK:["relationalExpression"],ISLITERAL:["relationalExpression"],ISNUMERIC:["relationalExpression"],TRUE:["relationalExpression"],FALSE:["relationalExpression"],COUNT:["relationalExpression"],SUM:["relationalExpression"],MIN:["relationalExpression"],MAX:["relationalExpression"],AVG:["relationalExpression"],SAMPLE:["relationalExpression"],GROUP_CONCAT:["relationalExpression"],SUBSTR:["relationalExpression"],REPLACE:["relationalExpression"],REGEX:["relationalExpression"],EXISTS:["relationalExpression"],NOT:["relationalExpression"],IRI_REF:["relationalExpression"],STRING_LITERAL1:["relationalExpression"],STRING_LITERAL2:["relationalExpression"],STRING_LITERAL_LONG1:["relationalExpression"],STRING_LITERAL_LONG2:["relationalExpression"],INTEGER:["relationalExpression"],DECIMAL:["relationalExpression"],DOUBLE:["relationalExpression"],INTEGER_POSITIVE:["relationalExpression"],DECIMAL_POSITIVE:["relationalExpression"],DOUBLE_POSITIVE:["relationalExpression"],INTEGER_NEGATIVE:["relationalExpression"],DECIMAL_NEGATIVE:["relationalExpression"],DOUBLE_NEGATIVE:["relationalExpression"],PNAME_LN:["relationalExpression"],PNAME_NS:["relationalExpression"]},valuesClause:{VALUES:["VALUES","dataBlock"],$:[],"}":[]},"var":{VAR1:["VAR1"],VAR2:["VAR2"]},varOrIRIref:{VAR1:["var"],VAR2:["var"],IRI_REF:["iriRef"],PNAME_LN:["iriRef"],PNAME_NS:["iriRef"]},varOrTerm:{VAR1:["var"],VAR2:["var"],NIL:["graphTerm"],IRI_REF:["graphTerm"],TRUE:["graphTerm"],FALSE:["graphTerm"],BLANK_NODE_LABEL:["graphTerm"],ANON:["graphTerm"],PNAME_LN:["graphTerm"],PNAME_NS:["graphTerm"],STRING_LITERAL1:["graphTerm"],STRING_LITERAL2:["graphTerm"],STRING_LITERAL_LONG1:["graphTerm"],STRING_LITERAL_LONG2:["graphTerm"],INTEGER:["graphTerm"],DECIMAL:["graphTerm"],DOUBLE:["graphTerm"],INTEGER_POSITIVE:["graphTerm"],DECIMAL_POSITIVE:["graphTerm"],DOUBLE_POSITIVE:["graphTerm"],INTEGER_NEGATIVE:["graphTerm"],DECIMAL_NEGATIVE:["graphTerm"],DOUBLE_NEGATIVE:["graphTerm"]},verb:{VAR1:["storeProperty","varOrIRIref"],VAR2:["storeProperty","varOrIRIref"],IRI_REF:["storeProperty","varOrIRIref"],PNAME_LN:["storeProperty","varOrIRIref"],PNAME_NS:["storeProperty","varOrIRIref"],a:["storeProperty","a"]},verbPath:{"^":["path"],a:["path"],"!":["path"],"(":["path"],IRI_REF:["path"],PNAME_LN:["path"],PNAME_NS:["path"]},verbSimple:{VAR1:["var"],VAR2:["var"]},whereClause:{"{":["?WHERE","groupGraphPattern"],WHERE:["?WHERE","groupGraphPattern"]}},keywords:/^(GROUP_CONCAT|DATATYPE|BASE|PREFIX|SELECT|CONSTRUCT|DESCRIBE|ASK|FROM|NAMED|ORDER|BY|LIMIT|ASC|DESC|OFFSET|DISTINCT|REDUCED|WHERE|GRAPH|OPTIONAL|UNION|FILTER|GROUP|HAVING|AS|VALUES|LOAD|CLEAR|DROP|CREATE|MOVE|COPY|SILENT|INSERT|DELETE|DATA|WITH|TO|USING|NAMED|MINUS|BIND|LANGMATCHES|LANG|BOUND|SAMETERM|ISIRI|ISURI|ISBLANK|ISLITERAL|REGEX|TRUE|FALSE|UNDEF|ADD|DEFAULT|ALL|SERVICE|INTO|IN|NOT|IRI|URI|BNODE|RAND|ABS|CEIL|FLOOR|ROUND|CONCAT|STRLEN|UCASE|LCASE|ENCODE_FOR_URI|CONTAINS|STRSTARTS|STRENDS|STRBEFORE|STRAFTER|YEAR|MONTH|DAY|HOURS|MINUTES|SECONDS|TIMEZONE|TZ|NOW|UUID|STRUUID|MD5|SHA1|SHA256|SHA384|SHA512|COALESCE|IF|STRLANG|STRDT|ISNUMERIC|SUBSTR|REPLACE|EXISTS|COUNT|SUM|MIN|MAX|AVG|SAMPLE|SEPARATOR|STR)/i,punct:/^(\*|a|\.|\{|\}|,|\(|\)|;|\[|\]|\|\||&&|=|!=|!|<=|>=|<|>|\+|-|\/|\^\^|\?|\||\^)/,startSymbol:"sparql11",acceptEmpty:!0}
},{}],4:[function(e){"use strict";var t=e("codemirror");t.defineMode("sparql11",function(t){function i(){var e="<[^<>\"'|{}^\\\x00- ]*>",t="[A-Za-z\\u00C0-\\u00D6\\u00D8-\\u00F6\\u00F8-\\u02FF\\u0370-\\u037D\\u037F-\\u1FFF\\u200C-\\u200D\\u2070-\\u218F\\u2C00-\\u2FEF\\u3001-\\uD7FF\\uF900-\\uFDCF\\uFDF0-\\uFFFD]",i=t+"|_",r="("+i+"|-|[0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040])",n="("+i+"|[0-9])("+i+"|[0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040])*",o="\\?"+n,s="\\$"+n,a="("+t+")((("+r+")|\\.)*("+r+"))?",l="[0-9A-Fa-f]",u="(%"+l+l+")",p="(\\\\[_~\\.\\-!\\$&'\\(\\)\\*\\+,;=/\\?#@%])",c="("+u+"|"+p+")",d="("+i+"|:|[0-9]|"+c+")(("+r+"|\\.|:|"+c+")*("+r+"|:|"+c+"))?",f="_:("+i+"|[0-9])(("+r+"|\\.)*"+r+")?",h="("+a+")?:",E=h+d,m="@[a-zA-Z]+(-[a-zA-Z0-9]+)*",g="[eE][\\+-]?[0-9]+",v="[0-9]+",x="(([0-9]+\\.[0-9]*)|(\\.[0-9]+))",N="(([0-9]+\\.[0-9]*"+g+")|(\\.[0-9]+"+g+")|([0-9]+"+g+"))",L="\\+"+v,T="\\+"+x,I="\\+"+N,y="-"+v,A="-"+x,S="-"+N,C="\\\\[tbnrf\\\\\"']",R=l+"{4}",b="(\\\\u"+R+"|\\\\U00(10|0"+l+")"+R+")",O="'(([^\\x27\\x5C\\x0A\\x0D])|"+C+"|"+b+")*'",P='"(([^\\x22\\x5C\\x0A\\x0D])|'+C+"|"+b+')*"',D="'''(('|'')?([^'\\\\]|"+C+"|"+b+"))*'''",w='"""(("|"")?([^"\\\\]|'+C+"|"+b+'))*"""',_="[\\x20\\x09\\x0D\\x0A]",M="#([^\\n\\r]*[\\n\\r]|[^\\n\\r]*$)",k="("+_+"|("+M+"))*",G="\\("+k+"\\)",B="\\["+k+"\\]",U={terminal:[{name:"WS",regex:new RegExp("^"+_+"+"),style:"ws"},{name:"COMMENT",regex:new RegExp("^"+M),style:"comment"},{name:"IRI_REF",regex:new RegExp("^"+e),style:"variable-3"},{name:"VAR1",regex:new RegExp("^"+o),style:"atom"},{name:"VAR2",regex:new RegExp("^"+s),style:"atom"},{name:"LANGTAG",regex:new RegExp("^"+m),style:"meta"},{name:"DOUBLE",regex:new RegExp("^"+N),style:"number"},{name:"DECIMAL",regex:new RegExp("^"+x),style:"number"},{name:"INTEGER",regex:new RegExp("^"+v),style:"number"},{name:"DOUBLE_POSITIVE",regex:new RegExp("^"+I),style:"number"},{name:"DECIMAL_POSITIVE",regex:new RegExp("^"+T),style:"number"},{name:"INTEGER_POSITIVE",regex:new RegExp("^"+L),style:"number"},{name:"DOUBLE_NEGATIVE",regex:new RegExp("^"+S),style:"number"},{name:"DECIMAL_NEGATIVE",regex:new RegExp("^"+A),style:"number"},{name:"INTEGER_NEGATIVE",regex:new RegExp("^"+y),style:"number"},{name:"STRING_LITERAL_LONG1",regex:new RegExp("^"+D),style:"string"},{name:"STRING_LITERAL_LONG2",regex:new RegExp("^"+w),style:"string"},{name:"STRING_LITERAL1",regex:new RegExp("^"+O),style:"string"},{name:"STRING_LITERAL2",regex:new RegExp("^"+P),style:"string"},{name:"NIL",regex:new RegExp("^"+G),style:"punc"},{name:"ANON",regex:new RegExp("^"+B),style:"punc"},{name:"PNAME_LN",regex:new RegExp("^"+E),style:"string-2"},{name:"PNAME_NS",regex:new RegExp("^"+h),style:"string-2"},{name:"BLANK_NODE_LABEL",regex:new RegExp("^"+f),style:"string-2"}]};return U}function r(e){var t=[],i=a[e];if(void 0!=i)for(var r in i)t.push(r.toString());else t.push(e);return t}function n(e,t){function i(){for(var t=null,i=0;i<u.length;++i){t=e.match(u[i].regex,!0,!1);if(t)return{cat:u[i].name,style:u[i].style,text:t[0]}}t=e.match(s.keywords,!0,!1);if(t)return{cat:e.current().toUpperCase(),style:"keyword",text:t[0]};t=e.match(s.punct,!0,!1);if(t)return{cat:e.current(),style:"punc",text:t[0]};t=e.match(/^.[A-Za-z0-9]*/,!0,!1);return{cat:"<invalid_token>",style:"error",text:t[0]}}function n(){var i=e.column();t.errorStartPos=i;t.errorEndPos=i+c.text.length}function o(e){null==t.queryType&&("SELECT"==e||"CONSTRUCT"==e||"ASK"==e||"DESCRIBE"==e||"INSERT"==e||"DELETE"==e||"LOAD"==e||"CLEAR"==e||"CREATE"==e||"DROP"==e||"COPY"==e||"MOVE"==e||"ADD"==e)&&(t.queryType=e)}function l(e){"disallowVars"==e?t.allowVars=!1:"allowVars"==e?t.allowVars=!0:"disallowBnodes"==e?t.allowBnodes=!1:"allowBnodes"==e?t.allowBnodes=!0:"storeProperty"==e&&(t.storeProperty=!0)}function p(e){return(t.allowVars||"var"!=e)&&(t.allowBnodes||"blankNode"!=e&&"blankNodePropertyList"!=e&&"blankNodePropertyListPath"!=e)}0==e.pos&&(t.possibleCurrent=t.possibleNext);var c=i();if("<invalid_token>"==c.cat){if(1==t.OK){t.OK=!1;n()}t.complete=!1;return c.style}if("WS"==c.cat||"COMMENT"==c.cat){t.possibleCurrent=t.possibleNext;return c.style}for(var d,f=!1,h=c.cat;t.stack.length>0&&h&&t.OK&&!f;){d=t.stack.pop();if(a[d]){var E=a[d][h];if(void 0!=E&&p(d)){for(var m=E.length-1;m>=0;--m)t.stack.push(E[m]);l(d)}else{t.OK=!1;t.complete=!1;n();t.stack.push(d)}}else if(d==h){f=!0;o(d);for(var g=!0,v=t.stack.length;v>0;--v){var x=a[t.stack[v-1]];x&&x.$||(g=!1)}t.complete=g;if(t.storeProperty&&"punc"!=h.cat){t.lastProperty=c.text;t.storeProperty=!1}}else{t.OK=!1;t.complete=!1;n()}}if(!f&&t.OK){t.OK=!1;t.complete=!1;n()}t.possibleCurrent=t.possibleNext;t.possibleNext=r(t.stack[t.stack.length-1]);return c.style}function o(e,i){var r=0,n=e.stack.length-1;if(/^[\}\]\)]/.test(i)){for(var o=i.substr(0,1);n>=0;--n)if(e.stack[n]==o){--n;break}}else{var s=p[e.stack[n]];if(s){r+=s;--n}}for(;n>=0;--n){var s=c[e.stack[n]];s&&(r+=s)}return r*t.indentUnit}var s=(t.indentUnit,e("./_tokenizer-table.js")),a=s.table,l=i(),u=l.terminal,p={"*[,, object]":3,"*[(,),object]":3,"*[(,),objectPath]":3,"*[/,pathEltOrInverse]":2,object:2,objectPath:2,objectList:2,objectListPath:2,storeProperty:2,pathMod:2,"?pathMod":2,propertyListNotEmpty:1,propertyList:1,propertyListPath:1,propertyListPathNotEmpty:1,"?[verb,objectList]":1,"?[or([verbPath, verbSimple]),objectList]":1},c={"}":1,"]":0,")":1,"{":-1,"(":-1,"*[;,?[or([verbPath,verbSimple]),objectList]]":1};return{token:n,startState:function(){return{tokenize:n,OK:!0,complete:s.acceptEmpty,errorStartPos:null,errorEndPos:null,queryType:null,possibleCurrent:r(s.startSymbol),possibleNext:r(s.startSymbol),allowVars:!0,allowBnodes:!0,storeProperty:!1,lastProperty:"",stack:[s.startSymbol]}},indent:o,electricChars:"}])"}});t.defineMIME("application/x-sparql-query","sparql11")},{"./_tokenizer-table.js":3,codemirror:15}],5:[function(e,t){var i=t.exports=function(){this.words=0;this.prefixes=0;this.children=[]};i.prototype={insert:function(e,t){if(0!=e.length){var r,n,o=this;void 0===t&&(t=0);if(t!==e.length){o.prefixes++;r=e[t];void 0===o.children[r]&&(o.children[r]=new i);n=o.children[r];n.insert(e,t+1)}else o.words++}},remove:function(e,t){if(0!=e.length){var i,r,n=this;void 0===t&&(t=0);if(void 0!==n)if(t!==e.length){n.prefixes--;i=e[t];r=n.children[i];r.remove(e,t+1)}else n.words--}},update:function(e,t){if(0!=e.length&&0!=t.length){this.remove(e);this.insert(t)}},countWord:function(e,t){if(0==e.length)return 0;var i,r,n=this,o=0;void 0===t&&(t=0);if(t===e.length)return n.words;i=e[t];r=n.children[i];void 0!==r&&(o=r.countWord(e,t+1));return o},countPrefix:function(e,t){if(0==e.length)return 0;var i,r,n=this,o=0;void 0===t&&(t=0);if(t===e.length)return n.prefixes;var i=e[t];r=n.children[i];void 0!==r&&(o=r.countPrefix(e,t+1));return o},find:function(e){return 0==e.length?!1:this.countWord(e)>0?!0:!1},getAllWords:function(e){var t,i,r=this,n=[];void 0===e&&(e="");if(void 0===r)return[];r.words>0&&n.push(e);for(t in r.children){i=r.children[t];n=n.concat(i.getAllWords(e+t))}return n},autoComplete:function(e,t){var i,r,n=this;if(0==e.length)return void 0===t?n.getAllWords(e):[];void 0===t&&(t=0);i=e[t];r=n.children[i];return void 0===r?[]:t===e.length-1?r.getAllWords(e):r.autoComplete(e,t+1)}}},{}],6:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)})(function(e){"use strict";function t(e){var t=e.getWrapperElement();e.state.fullScreenRestore={scrollTop:window.pageYOffset,scrollLeft:window.pageXOffset,width:t.style.width,height:t.style.height};t.style.width="";t.style.height="auto";t.className+=" CodeMirror-fullscreen";document.documentElement.style.overflow="hidden";e.refresh()}function i(e){var t=e.getWrapperElement();t.className=t.className.replace(/\s*CodeMirror-fullscreen\b/,"");document.documentElement.style.overflow="";var i=e.state.fullScreenRestore;t.style.width=i.width;t.style.height=i.height;window.scrollTo(i.scrollLeft,i.scrollTop);e.refresh()}e.defineOption("fullScreen",!1,function(r,n,o){o==e.Init&&(o=!1);!o!=!n&&(n?t(r):i(r))})})},{"../../lib/codemirror":15}],7:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)})(function(e){function t(e,t,r,n){var o=e.getLineHandle(t.line),l=t.ch-1,u=l>=0&&a[o.text.charAt(l)]||a[o.text.charAt(++l)];if(!u)return null;var p=">"==u.charAt(1)?1:-1;if(r&&p>0!=(l==t.ch))return null;var c=e.getTokenTypeAt(s(t.line,l+1)),d=i(e,s(t.line,l+(p>0?1:0)),p,c||null,n);return null==d?null:{from:s(t.line,l),to:d&&d.pos,match:d&&d.ch==u.charAt(0),forward:p>0}}function i(e,t,i,r,n){for(var o=n&&n.maxScanLineLength||1e4,l=n&&n.maxScanLines||1e3,u=[],p=n&&n.bracketRegex?n.bracketRegex:/[(){}[\]]/,c=i>0?Math.min(t.line+l,e.lastLine()+1):Math.max(e.firstLine()-1,t.line-l),d=t.line;d!=c;d+=i){var f=e.getLine(d);if(f){var h=i>0?0:f.length-1,E=i>0?f.length:-1;if(!(f.length>o)){d==t.line&&(h=t.ch-(0>i?1:0));for(;h!=E;h+=i){var m=f.charAt(h);if(p.test(m)&&(void 0===r||e.getTokenTypeAt(s(d,h+1))==r)){var g=a[m];if(">"==g.charAt(1)==i>0)u.push(m);else{if(!u.length)return{pos:s(d,h),ch:m};u.pop()}}}}}}return d-i==(i>0?e.lastLine():e.firstLine())?!1:null}function r(e,i,r){for(var n=e.state.matchBrackets.maxHighlightLineLength||1e3,a=[],l=e.listSelections(),u=0;u<l.length;u++){var p=l[u].empty()&&t(e,l[u].head,!1,r);if(p&&e.getLine(p.from.line).length<=n){var c=p.match?"CodeMirror-matchingbracket":"CodeMirror-nonmatchingbracket";a.push(e.markText(p.from,s(p.from.line,p.from.ch+1),{className:c}));p.to&&e.getLine(p.to.line).length<=n&&a.push(e.markText(p.to,s(p.to.line,p.to.ch+1),{className:c}))}}if(a.length){o&&e.state.focused&&e.display.input.focus();var d=function(){e.operation(function(){for(var e=0;e<a.length;e++)a[e].clear()})};if(!i)return d;setTimeout(d,800)}}function n(e){e.operation(function(){if(l){l();l=null}l=r(e,!1,e.state.matchBrackets)})}var o=/MSIE \d/.test(navigator.userAgent)&&(null==document.documentMode||document.documentMode<8),s=e.Pos,a={"(":")>",")":"(<","[":"]>","]":"[<","{":"}>","}":"{<"},l=null;e.defineOption("matchBrackets",!1,function(t,i,r){r&&r!=e.Init&&t.off("cursorActivity",n);if(i){t.state.matchBrackets="object"==typeof i?i:{};t.on("cursorActivity",n)}});e.defineExtension("matchBrackets",function(){r(this,!0)});e.defineExtension("findMatchingBracket",function(e,i,r){return t(this,e,i,r)});e.defineExtension("scanForBracket",function(e,t,r,n){return i(this,e,t,r,n)})})},{"../../lib/codemirror":15}],8:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)})(function(e){"use strict";e.registerHelper("fold","brace",function(t,i){function r(r){for(var n=i.ch,l=0;;){var u=0>=n?-1:a.lastIndexOf(r,n-1);if(-1!=u){if(1==l&&u<i.ch)break;o=t.getTokenTypeAt(e.Pos(s,u+1));if(!/^(comment|string)/.test(o))return u+1;n=u-1}else{if(1==l)break;l=1;n=a.length}}}var n,o,s=i.line,a=t.getLine(s),l="{",u="}",n=r("{");if(null==n){l="[",u="]";n=r("[")}if(null!=n){var p,c,d=1,f=t.lastLine();e:for(var h=s;f>=h;++h)for(var E=t.getLine(h),m=h==s?n:0;;){var g=E.indexOf(l,m),v=E.indexOf(u,m);0>g&&(g=E.length);0>v&&(v=E.length);m=Math.min(g,v);if(m==E.length)break;if(t.getTokenTypeAt(e.Pos(h,m+1))==o)if(m==g)++d;else if(!--d){p=h;c=m;break e}++m}if(null!=p&&(s!=p||c!=n))return{from:e.Pos(s,n),to:e.Pos(p,c)}}});e.registerHelper("fold","import",function(t,i){function r(i){if(i<t.firstLine()||i>t.lastLine())return null;var r=t.getTokenAt(e.Pos(i,1));/\S/.test(r.string)||(r=t.getTokenAt(e.Pos(i,r.end+1)));if("keyword"!=r.type||"import"!=r.string)return null;for(var n=i,o=Math.min(t.lastLine(),i+10);o>=n;++n){var s=t.getLine(n),a=s.indexOf(";");if(-1!=a)return{startCh:r.end,end:e.Pos(n,a)}}}var n,i=i.line,o=r(i);if(!o||r(i-1)||(n=r(i-2))&&n.end.line==i-1)return null;for(var s=o.end;;){var a=r(s.line+1);if(null==a)break;s=a.end}return{from:t.clipPos(e.Pos(i,o.startCh+1)),to:s}});e.registerHelper("fold","include",function(t,i){function r(i){if(i<t.firstLine()||i>t.lastLine())return null;var r=t.getTokenAt(e.Pos(i,1));/\S/.test(r.string)||(r=t.getTokenAt(e.Pos(i,r.end+1)));return"meta"==r.type&&"#include"==r.string.slice(0,8)?r.start+8:void 0}var i=i.line,n=r(i);if(null==n||null!=r(i-1))return null;for(var o=i;;){var s=r(o+1);if(null==s)break;++o}return{from:e.Pos(i,n+1),to:t.clipPos(e.Pos(o))}})})},{"../../lib/codemirror":15}],9:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)})(function(e){"use strict";function t(t,n,o,s){function a(e){var i=l(t,n);if(!i||i.to.line-i.from.line<u)return null;for(var r=t.findMarksAt(i.from),o=0;o<r.length;++o)if(r[o].__isFold&&"fold"!==s){if(!e)return null;i.cleared=!0;r[o].clear()}return i}if(o&&o.call){var l=o;o=null}else var l=r(t,o,"rangeFinder");"number"==typeof n&&(n=e.Pos(n,0));var u=r(t,o,"minFoldSize"),p=a(!0);if(r(t,o,"scanUp"))for(;!p&&n.line>t.firstLine();){n=e.Pos(n.line-1,0);p=a(!1)}if(p&&!p.cleared&&"unfold"!==s){var c=i(t,o);e.on(c,"mousedown",function(t){d.clear();e.e_preventDefault(t)});var d=t.markText(p.from,p.to,{replacedWith:c,clearOnEnter:!0,__isFold:!0});d.on("clear",function(i,r){e.signal(t,"unfold",t,i,r)});e.signal(t,"fold",t,p.from,p.to)}}function i(e,t){var i=r(e,t,"widget");if("string"==typeof i){var n=document.createTextNode(i);i=document.createElement("span");i.appendChild(n);i.className="CodeMirror-foldmarker"}return i}function r(e,t,i){if(t&&void 0!==t[i])return t[i];var r=e.options.foldOptions;return r&&void 0!==r[i]?r[i]:n[i]}e.newFoldFunction=function(e,i){return function(r,n){t(r,n,{rangeFinder:e,widget:i})}};e.defineExtension("foldCode",function(e,i,r){t(this,e,i,r)});e.defineExtension("isFolded",function(e){for(var t=this.findMarksAt(e),i=0;i<t.length;++i)if(t[i].__isFold)return!0});e.commands.toggleFold=function(e){e.foldCode(e.getCursor())};e.commands.fold=function(e){e.foldCode(e.getCursor(),null,"fold")};e.commands.unfold=function(e){e.foldCode(e.getCursor(),null,"unfold")};e.commands.foldAll=function(t){t.operation(function(){for(var i=t.firstLine(),r=t.lastLine();r>=i;i++)t.foldCode(e.Pos(i,0),null,"fold")})};e.commands.unfoldAll=function(t){t.operation(function(){for(var i=t.firstLine(),r=t.lastLine();r>=i;i++)t.foldCode(e.Pos(i,0),null,"unfold")})};e.registerHelper("fold","combine",function(){var e=Array.prototype.slice.call(arguments,0);return function(t,i){for(var r=0;r<e.length;++r){var n=e[r](t,i);if(n)return n}}});e.registerHelper("fold","auto",function(e,t){for(var i=e.getHelpers(t,"fold"),r=0;r<i.length;r++){var n=i[r](e,t);if(n)return n}});var n={rangeFinder:e.fold.auto,widget:"↔",minFoldSize:0,scanUp:!1};e.defineOption("foldOptions",null);e.defineExtension("foldOption",function(e,t){return r(this,e,t)})})},{"../../lib/codemirror":15}],10:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror"),t("./foldcode")):"function"==typeof e&&e.amd?e(["../../lib/codemirror","./foldcode"],n):n(CodeMirror)})(function(e){"use strict";function t(e){this.options=e;this.from=this.to=0}function i(e){e===!0&&(e={});null==e.gutter&&(e.gutter="CodeMirror-foldgutter");null==e.indicatorOpen&&(e.indicatorOpen="CodeMirror-foldgutter-open");null==e.indicatorFolded&&(e.indicatorFolded="CodeMirror-foldgutter-folded");return e}function r(e,t){for(var i=e.findMarksAt(c(t)),r=0;r<i.length;++r)if(i[r].__isFold&&i[r].find().from.line==t)return!0}function n(e){if("string"==typeof e){var t=document.createElement("div");t.className=e+" CodeMirror-guttermarker-subtle";return t}return e.cloneNode(!0)}function o(e,t,i){var o=e.state.foldGutter.options,s=t,a=e.foldOption(o,"minFoldSize"),l=e.foldOption(o,"rangeFinder");e.eachLine(t,i,function(t){var i=null;if(r(e,s))i=n(o.indicatorFolded);else{var u=c(s,0),p=l&&l(e,u);p&&p.to.line-p.from.line>=a&&(i=n(o.indicatorOpen))}e.setGutterMarker(t,o.gutter,i);++s})}function s(e){var t=e.getViewport(),i=e.state.foldGutter;if(i){e.operation(function(){o(e,t.from,t.to)});i.from=t.from;i.to=t.to}}function a(e,t,i){var r=e.state.foldGutter.options;i==r.gutter&&e.foldCode(c(t,0),r.rangeFinder)}function l(e){var t=e.state.foldGutter,i=e.state.foldGutter.options;t.from=t.to=0;clearTimeout(t.changeUpdate);t.changeUpdate=setTimeout(function(){s(e)},i.foldOnChangeTimeSpan||600)}function u(e){var t=e.state.foldGutter,i=e.state.foldGutter.options;clearTimeout(t.changeUpdate);t.changeUpdate=setTimeout(function(){var i=e.getViewport();t.from==t.to||i.from-t.to>20||t.from-i.to>20?s(e):e.operation(function(){if(i.from<t.from){o(e,i.from,t.from);t.from=i.from}if(i.to>t.to){o(e,t.to,i.to);t.to=i.to}})},i.updateViewportTimeSpan||400)}function p(e,t){var i=e.state.foldGutter,r=t.line;r>=i.from&&r<i.to&&o(e,r,r+1)}e.defineOption("foldGutter",!1,function(r,n,o){if(o&&o!=e.Init){r.clearGutter(r.state.foldGutter.options.gutter);r.state.foldGutter=null;r.off("gutterClick",a);r.off("change",l);r.off("viewportChange",u);r.off("fold",p);r.off("unfold",p);r.off("swapDoc",s)}if(n){r.state.foldGutter=new t(i(n));s(r);r.on("gutterClick",a);r.on("change",l);r.on("viewportChange",u);r.on("fold",p);r.on("unfold",p);r.on("swapDoc",s)}});var c=e.Pos})},{"../../lib/codemirror":15,"./foldcode":9}],11:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)})(function(e){"use strict";function t(e,t){return e.line-t.line||e.ch-t.ch}function i(e,t,i,r){this.line=t;this.ch=i;this.cm=e;this.text=e.getLine(t);this.min=r?r.from:e.firstLine();this.max=r?r.to-1:e.lastLine()}function r(e,t){var i=e.cm.getTokenTypeAt(d(e.line,t));return i&&/\btag\b/.test(i)}function n(e){if(!(e.line>=e.max)){e.ch=0;e.text=e.cm.getLine(++e.line);return!0}}function o(e){if(!(e.line<=e.min)){e.text=e.cm.getLine(--e.line);e.ch=e.text.length;return!0}}function s(e){for(;;){var t=e.text.indexOf(">",e.ch);if(-1==t){if(n(e))continue;return}if(r(e,t+1)){var i=e.text.lastIndexOf("/",t),o=i>-1&&!/\S/.test(e.text.slice(i+1,t));e.ch=t+1;return o?"selfClose":"regular"}e.ch=t+1}}function a(e){for(;;){var t=e.ch?e.text.lastIndexOf("<",e.ch-1):-1;if(-1==t){if(o(e))continue;return}if(r(e,t+1)){E.lastIndex=t;e.ch=t;var i=E.exec(e.text);if(i&&i.index==t)return i}else e.ch=t}}function l(e){for(;;){E.lastIndex=e.ch;var t=E.exec(e.text);if(!t){if(n(e))continue;return}if(r(e,t.index+1)){e.ch=t.index+t[0].length;return t}e.ch=t.index+1}}function u(e){for(;;){var t=e.ch?e.text.lastIndexOf(">",e.ch-1):-1;if(-1==t){if(o(e))continue;return}if(r(e,t+1)){var i=e.text.lastIndexOf("/",t),n=i>-1&&!/\S/.test(e.text.slice(i+1,t));e.ch=t+1;return n?"selfClose":"regular"}e.ch=t}}function p(e,t){for(var i=[];;){var r,n=l(e),o=e.line,a=e.ch-(n?n[0].length:0);if(!n||!(r=s(e)))return;if("selfClose"!=r)if(n[1]){for(var u=i.length-1;u>=0;--u)if(i[u]==n[2]){i.length=u;break}if(0>u&&(!t||t==n[2]))return{tag:n[2],from:d(o,a),to:d(e.line,e.ch)}}else i.push(n[2])}}function c(e,t){for(var i=[];;){var r=u(e);if(!r)return;if("selfClose"!=r){var n=e.line,o=e.ch,s=a(e);if(!s)return;if(s[1])i.push(s[2]);else{for(var l=i.length-1;l>=0;--l)if(i[l]==s[2]){i.length=l;break}if(0>l&&(!t||t==s[2]))return{tag:s[2],from:d(e.line,e.ch),to:d(n,o)}}}else a(e)}}var d=e.Pos,f="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",h=f+"-:.0-9\\u00B7\\u0300-\\u036F\\u203F-\\u2040",E=new RegExp("<(/?)(["+f+"]["+h+"]*)","g");e.registerHelper("fold","xml",function(e,t){for(var r=new i(e,t.line,0);;){var n,o=l(r);if(!o||r.line!=t.line||!(n=s(r)))return;if(!o[1]&&"selfClose"!=n){var t=d(r.line,r.ch),a=p(r,o[2]);return a&&{from:t,to:a.from}}}});e.findMatchingTag=function(e,r,n){var o=new i(e,r.line,r.ch,n);if(-1!=o.text.indexOf(">")||-1!=o.text.indexOf("<")){var l=s(o),u=l&&d(o.line,o.ch),f=l&&a(o);if(l&&f&&!(t(o,r)>0)){var h={from:d(o.line,o.ch),to:u,tag:f[2]};if("selfClose"==l)return{open:h,close:null,at:"open"};if(f[1])return{open:c(o,f[2]),close:h,at:"close"};o=new i(e,u.line,u.ch,n);return{open:h,close:p(o,f[2]),at:"open"}}}};e.findEnclosingTag=function(e,t,r){for(var n=new i(e,t.line,t.ch,r);;){var o=c(n);if(!o)break;var s=new i(e,t.line,t.ch,r),a=p(s,o.tag);if(a)return{open:o,close:a}}};e.scanForClosingTag=function(e,t,r,n){var o=new i(e,t.line,t.ch,n?{from:0,to:n}:null);return p(o,r)}})},{"../../lib/codemirror":15}],12:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)})(function(e){"use strict";function t(e,t){this.cm=e;this.options=this.buildOptions(t);this.widget=this.onClose=null}function i(e){return"string"==typeof e?e:e.text}function r(e,t){function i(e,i){var n;n="string"!=typeof i?function(e){return i(e,t)}:r.hasOwnProperty(i)?r[i]:i;o[e]=n}var r={Up:function(){t.moveFocus(-1)},Down:function(){t.moveFocus(1)},PageUp:function(){t.moveFocus(-t.menuSize()+1,!0)},PageDown:function(){t.moveFocus(t.menuSize()-1,!0)},Home:function(){t.setFocus(0)},End:function(){t.setFocus(t.length-1)},Enter:t.pick,Tab:t.pick,Esc:t.close},n=e.options.customKeys,o=n?{}:r;if(n)for(var s in n)n.hasOwnProperty(s)&&i(s,n[s]);var a=e.options.extraKeys;if(a)for(var s in a)a.hasOwnProperty(s)&&i(s,a[s]);return o}function n(e,t){for(;t&&t!=e;){if("LI"===t.nodeName.toUpperCase()&&t.parentNode==e)return t;t=t.parentNode}}function o(t,o){this.completion=t;this.data=o;var l=this,u=t.cm,p=this.hints=document.createElement("ul");p.className="CodeMirror-hints";this.selectedHint=o.selectedHint||0;for(var c=o.list,d=0;d<c.length;++d){var f=p.appendChild(document.createElement("li")),h=c[d],E=s+(d!=this.selectedHint?"":" "+a);null!=h.className&&(E=h.className+" "+E);f.className=E;h.render?h.render(f,o,h):f.appendChild(document.createTextNode(h.displayText||i(h)));f.hintId=d}var m=u.cursorCoords(t.options.alignWithWord?o.from:null),g=m.left,v=m.bottom,x=!0;p.style.left=g+"px";p.style.top=v+"px";var N=window.innerWidth||Math.max(document.body.offsetWidth,document.documentElement.offsetWidth),L=window.innerHeight||Math.max(document.body.offsetHeight,document.documentElement.offsetHeight);(t.options.container||document.body).appendChild(p);var T=p.getBoundingClientRect(),I=T.bottom-L;if(I>0){var y=T.bottom-T.top,A=m.top-(m.bottom-T.top);if(A-y>0){p.style.top=(v=m.top-y)+"px";x=!1}else if(y>L){p.style.height=L-5+"px";p.style.top=(v=m.bottom-T.top)+"px";var S=u.getCursor();if(o.from.ch!=S.ch){m=u.cursorCoords(S);p.style.left=(g=m.left)+"px";T=p.getBoundingClientRect()}}}var C=T.right-N;if(C>0){if(T.right-T.left>N){p.style.width=N-5+"px";C-=T.right-T.left-N}p.style.left=(g=m.left-C)+"px"}u.addKeyMap(this.keyMap=r(t,{moveFocus:function(e,t){l.changeActive(l.selectedHint+e,t)},setFocus:function(e){l.changeActive(e)},menuSize:function(){return l.screenAmount()},length:c.length,close:function(){t.close()},pick:function(){l.pick()},data:o}));if(t.options.closeOnUnfocus){var R;u.on("blur",this.onBlur=function(){R=setTimeout(function(){t.close()},100)});u.on("focus",this.onFocus=function(){clearTimeout(R)})}var b=u.getScrollInfo();u.on("scroll",this.onScroll=function(){var e=u.getScrollInfo(),i=u.getWrapperElement().getBoundingClientRect(),r=v+b.top-e.top,n=r-(window.pageYOffset||(document.documentElement||document.body).scrollTop);x||(n+=p.offsetHeight);if(n<=i.top||n>=i.bottom)return t.close();p.style.top=r+"px";p.style.left=g+b.left-e.left+"px"});e.on(p,"dblclick",function(e){var t=n(p,e.target||e.srcElement);if(t&&null!=t.hintId){l.changeActive(t.hintId);l.pick()}});e.on(p,"click",function(e){var i=n(p,e.target||e.srcElement);if(i&&null!=i.hintId){l.changeActive(i.hintId);t.options.completeOnSingleClick&&l.pick()}});e.on(p,"mousedown",function(){setTimeout(function(){u.focus()},20)});e.signal(o,"select",c[0],p.firstChild);return!0}var s="CodeMirror-hint",a="CodeMirror-hint-active";e.showHint=function(e,t,i){if(!t)return e.showHint(i);i&&i.async&&(t.async=!0);var r={hint:t};if(i)for(var n in i)r[n]=i[n];return e.showHint(r)};e.defineExtension("showHint",function(i){if(!(this.listSelections().length>1||this.somethingSelected())){this.state.completionActive&&this.state.completionActive.close();var r=this.state.completionActive=new t(this,i),n=r.options.hint;if(n){e.signal(this,"startCompletion",this);if(!n.async)return r.showHints(n(this,r.options));n(this,function(e){r.showHints(e)},r.options);return void 0}}});t.prototype={close:function(){if(this.active()){this.cm.state.completionActive=null;this.widget&&this.widget.close();this.onClose&&this.onClose();e.signal(this.cm,"endCompletion",this.cm)}},active:function(){return this.cm.state.completionActive==this},pick:function(t,r){var n=t.list[r];n.hint?n.hint(this.cm,t,n):this.cm.replaceRange(i(n),n.from||t.from,n.to||t.to,"complete");e.signal(t,"pick",n);this.close()},showHints:function(e){if(!e||!e.list.length||!this.active())return this.close();this.options.completeSingle&&1==e.list.length?this.pick(e,0):this.showWidget(e);return void 0},showWidget:function(t){function i(){if(!l){l=!0;p.close();p.cm.off("cursorActivity",a);t&&e.signal(t,"close")}}function r(){if(!l){e.signal(t,"update");var i=p.options.hint;i.async?i(p.cm,n,p.options):n(i(p.cm,p.options))}}function n(e){t=e;if(!l){if(!t||!t.list.length)return i();p.widget&&p.widget.close();p.widget=new o(p,t)}}function s(){if(u){E(u);u=0}}function a(){s();var e=p.cm.getCursor(),t=p.cm.getLine(e.line);if(e.line!=d.line||t.length-e.ch!=f-d.ch||e.ch<d.ch||p.cm.somethingSelected()||e.ch&&c.test(t.charAt(e.ch-1)))p.close();else{u=h(r);p.widget&&p.widget.close()}}this.widget=new o(this,t);e.signal(t,"shown");var l,u=0,p=this,c=this.options.closeCharacters,d=this.cm.getCursor(),f=this.cm.getLine(d.line).length,h=window.requestAnimationFrame||function(e){return setTimeout(e,1e3/60)},E=window.cancelAnimationFrame||clearTimeout;this.cm.on("cursorActivity",a);this.onClose=i},buildOptions:function(e){var t=this.cm.options.hintOptions,i={};for(var r in l)i[r]=l[r];if(t)for(var r in t)void 0!==t[r]&&(i[r]=t[r]);if(e)for(var r in e)void 0!==e[r]&&(i[r]=e[r]);return i}};o.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 e=this.completion.cm;if(this.completion.options.closeOnUnfocus){e.off("blur",this.onBlur);e.off("focus",this.onFocus)}e.off("scroll",this.onScroll)}},pick:function(){this.completion.pick(this.data,this.selectedHint)},changeActive:function(t,i){t>=this.data.list.length?t=i?this.data.list.length-1:0:0>t&&(t=i?0:this.data.list.length-1);if(this.selectedHint!=t){var r=this.hints.childNodes[this.selectedHint];r.className=r.className.replace(" "+a,"");r=this.hints.childNodes[this.selectedHint=t];r.className+=" "+a;r.offsetTop<this.hints.scrollTop?this.hints.scrollTop=r.offsetTop-3:r.offsetTop+r.offsetHeight>this.hints.scrollTop+this.hints.clientHeight&&(this.hints.scrollTop=r.offsetTop+r.offsetHeight-this.hints.clientHeight+3);e.signal(this.data,"select",this.data.list[this.selectedHint],r)}},screenAmount:function(){return Math.floor(this.hints.clientHeight/this.hints.firstChild.offsetHeight)||1}};e.registerHelper("hint","auto",function(t,i){var r,n=t.getHelpers(t.getCursor(),"hint");if(n.length)for(var o=0;o<n.length;o++){var s=n[o](t,i);if(s&&s.list.length)return s}else if(r=t.getHelper(t.getCursor(),"hintWords")){if(r)return e.hint.fromList(t,{words:r})}else if(e.hint.anyword)return e.hint.anyword(t,i)});e.registerHelper("hint","fromList",function(t,i){for(var r=t.getCursor(),n=t.getTokenAt(r),o=[],s=0;s<i.words.length;s++){var a=i.words[s];a.slice(0,n.string.length)==n.string&&o.push(a)}return o.length?{list:o,from:e.Pos(r.line,n.start),to:e.Pos(r.line,n.end)}:void 0});e.commands.autocomplete=e.showHint;var l={hint:e.hint.auto,completeSingle:!0,alignWithWord:!0,closeCharacters:/[\s()\[\]{};:>,]/,closeOnUnfocus:!0,completeOnSingleClick:!1,container:null,customKeys:null,extraKeys:null};e.defineOption("hintOptions",null)})},{"../../lib/codemirror":15}],13:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)})(function(e){"use strict";e.runMode=function(t,i,r,n){var o=e.getMode(e.defaults,i),s=/MSIE \d/.test(navigator.userAgent),a=s&&(null==document.documentMode||document.documentMode<9);if(1==r.nodeType){var l=n&&n.tabSize||e.defaults.tabSize,u=r,p=0;u.innerHTML="";r=function(e,t){if("\n"!=e){for(var i="",r=0;;){var n=e.indexOf(" ",r);if(-1==n){i+=e.slice(r);p+=e.length-r;break}p+=n-r;i+=e.slice(r,n);var o=l-p%l;p+=o;for(var s=0;o>s;++s)i+=" ";r=n+1}if(t){var c=u.appendChild(document.createElement("span"));c.className="cm-"+t.replace(/ +/g," cm-");c.appendChild(document.createTextNode(i))}else u.appendChild(document.createTextNode(i))}else{u.appendChild(document.createTextNode(a?"\r":e));p=0}}}for(var c=e.splitLines(t),d=n&&n.state||e.startState(o),f=0,h=c.length;h>f;++f){f&&r("\n");var E=new e.StringStream(c[f]);!E.string&&o.blankLine&&o.blankLine(d);for(;!E.eol();){var m=o.token(E,d);r(E.current(),m,f,E.start,d);E.start=E.pos}}}})},{"../../lib/codemirror":15}],14:[function(t,i,r){(function(n){"object"==typeof r&&"object"==typeof i?n(t("../../lib/codemirror")):"function"==typeof e&&e.amd?e(["../../lib/codemirror"],n):n(CodeMirror)})(function(e){"use strict";function t(e,t,n,o){this.atOccurrence=!1;this.doc=e;null==o&&"string"==typeof t&&(o=!1);n=n?e.clipPos(n):r(0,0);this.pos={from:n,to:n};if("string"!=typeof t){t.global||(t=new RegExp(t.source,t.ignoreCase?"ig":"g"));this.matches=function(i,n){if(i){t.lastIndex=0;for(var o,s,a=e.getLine(n.line).slice(0,n.ch),l=0;;){t.lastIndex=l;var u=t.exec(a);if(!u)break;o=u;s=o.index;l=o.index+(o[0].length||1);if(l==a.length)break}var p=o&&o[0].length||0;p||(0==s&&0==a.length?o=void 0:s!=e.getLine(n.line).length&&p++)}else{t.lastIndex=n.ch;var a=e.getLine(n.line),o=t.exec(a),p=o&&o[0].length||0,s=o&&o.index;s+p==a.length||p||(p=1)}return o&&p?{from:r(n.line,s),to:r(n.line,s+p),match:o}:void 0}}else{var s=t;o&&(t=t.toLowerCase());var a=o?function(e){return e.toLowerCase()}:function(e){return e},l=t.split("\n");if(1==l.length)this.matches=t.length?function(n,o){if(n){var l=e.getLine(o.line).slice(0,o.ch),u=a(l),p=u.lastIndexOf(t);if(p>-1){p=i(l,u,p);return{from:r(o.line,p),to:r(o.line,p+s.length)}}}else{var l=e.getLine(o.line).slice(o.ch),u=a(l),p=u.indexOf(t);if(p>-1){p=i(l,u,p)+o.ch;return{from:r(o.line,p),to:r(o.line,p+s.length)}}}}:function(){};else{var u=s.split("\n");this.matches=function(t,i){var n=l.length-1;if(t){if(i.line-(l.length-1)<e.firstLine())return;if(a(e.getLine(i.line).slice(0,u[n].length))!=l[l.length-1])return;for(var o=r(i.line,u[n].length),s=i.line-1,p=n-1;p>=1;--p,--s)if(l[p]!=a(e.getLine(s)))return;var c=e.getLine(s),d=c.length-u[0].length;if(a(c.slice(d))!=l[0])return;return{from:r(s,d),to:o}}if(!(i.line+(l.length-1)>e.lastLine())){var c=e.getLine(i.line),d=c.length-u[0].length;if(a(c.slice(d))==l[0]){for(var f=r(i.line,d),s=i.line+1,p=1;n>p;++p,++s)if(l[p]!=a(e.getLine(s)))return;if(a(e.getLine(s).slice(0,u[n].length))==l[n])return{from:f,to:r(s,u[n].length)}}}}}}}function i(e,t,i){if(e.length==t.length)return i;for(var r=Math.min(i,e.length);;){var n=e.slice(0,r).toLowerCase().length;if(i>n)++r;else{if(!(n>i))return r;--r}}}var r=e.Pos;t.prototype={findNext:function(){return this.find(!1)},findPrevious:function(){return this.find(!0)},find:function(e){function t(e){var t=r(e,0);i.pos={from:t,to:t};i.atOccurrence=!1;return!1}for(var i=this,n=this.doc.clipPos(e?this.pos.from:this.pos.to);;){if(this.pos=this.matches(e,n)){this.atOccurrence=!0;return this.pos.match||!0}if(e){if(!n.line)return t(0);n=r(n.line-1,this.doc.getLine(n.line-1).length)
}else{var o=this.doc.lineCount();if(n.line==o-1)return t(o);n=r(n.line+1,0)}}},from:function(){return this.atOccurrence?this.pos.from:void 0},to:function(){return this.atOccurrence?this.pos.to:void 0},replace:function(t){if(this.atOccurrence){var i=e.splitLines(t);this.doc.replaceRange(i,this.pos.from,this.pos.to);this.pos.to=r(this.pos.from.line+i.length-1,i[i.length-1].length+(1==i.length?this.pos.from.ch:0))}}};e.defineExtension("getSearchCursor",function(e,i,r){return new t(this.doc,e,i,r)});e.defineDocExtension("getSearchCursor",function(e,i,r){return new t(this,e,i,r)});e.defineExtension("selectMatches",function(t,i){for(var r,n=[],o=this.getSearchCursor(t,this.getCursor("from"),i);(r=o.findNext())&&!(e.cmpPos(o.to(),this.getCursor("to"))>0);)n.push({anchor:o.from(),head:o.to()});n.length&&this.setSelections(n,0)})})},{"../../lib/codemirror":15}],15:[function(t,i,r){(function(t){if("object"==typeof r&&"object"==typeof i)i.exports=t();else{if("function"==typeof e&&e.amd)return e([],t);this.CodeMirror=t()}})(function(){"use strict";function e(i,r){if(!(this instanceof e))return new e(i,r);this.options=r=r?yo(r):{};yo(Us,r,!1);f(r);var n=r.value;"string"==typeof n&&(n=new ua(n,r.mode));this.doc=n;var o=this.display=new t(i,n);o.wrapper.CodeMirror=this;u(this);a(this);r.lineWrapping&&(this.display.wrapper.className+=" CodeMirror-wrap");r.autofocus&&!Es&&Oi(this);g(this);this.state={keyMaps:[],overlays:[],modeGen:0,overwrite:!1,focused:!1,suppressEdits:!1,pasteIncoming:!1,cutIncoming:!1,draggingText:!1,highlight:new go,keySeq:null};ns&&11>os&&setTimeout(Ao(bi,this,!0),20);wi(this);Go();ni(this);this.curOp.forceUpdate=!0;Gn(this,n);r.autofocus&&!Es||wo()==o.input?setTimeout(Ao(rr,this),20):nr(this);for(var s in Vs)Vs.hasOwnProperty(s)&&Vs[s](this,r[s],Fs);T(this);for(var l=0;l<qs.length;++l)qs[l](this);si(this);ss&&r.lineWrapping&&"optimizelegibility"==getComputedStyle(o.lineDiv).textRendering&&(o.lineDiv.style.textRendering="auto")}function t(e,t){var i=this,r=i.input=bo("textarea",null,null,"position: absolute; padding: 0; width: 1px; height: 1em; outline: none");ss?r.style.width="1000px":r.setAttribute("wrap","off");hs&&(r.style.border="1px solid black");r.setAttribute("autocorrect","off");r.setAttribute("autocapitalize","off");r.setAttribute("spellcheck","false");i.inputDiv=bo("div",[r],null,"overflow: hidden; position: relative; width: 3px; height: 0px;");i.scrollbarFiller=bo("div",null,"CodeMirror-scrollbar-filler");i.scrollbarFiller.setAttribute("not-content","true");i.gutterFiller=bo("div",null,"CodeMirror-gutter-filler");i.gutterFiller.setAttribute("not-content","true");i.lineDiv=bo("div",null,"CodeMirror-code");i.selectionDiv=bo("div",null,null,"position: relative; z-index: 1");i.cursorDiv=bo("div",null,"CodeMirror-cursors");i.measure=bo("div",null,"CodeMirror-measure");i.lineMeasure=bo("div",null,"CodeMirror-measure");i.lineSpace=bo("div",[i.measure,i.lineMeasure,i.selectionDiv,i.cursorDiv,i.lineDiv],null,"position: relative; outline: none");i.mover=bo("div",[bo("div",[i.lineSpace],"CodeMirror-lines")],null,"position: relative");i.sizer=bo("div",[i.mover],"CodeMirror-sizer");i.sizerWidth=null;i.heightForcer=bo("div",null,null,"position: absolute; height: "+xa+"px; width: 1px;");i.gutters=bo("div",null,"CodeMirror-gutters");i.lineGutter=null;i.scroller=bo("div",[i.sizer,i.heightForcer,i.gutters],"CodeMirror-scroll");i.scroller.setAttribute("tabIndex","-1");i.wrapper=bo("div",[i.inputDiv,i.scrollbarFiller,i.gutterFiller,i.scroller],"CodeMirror");if(ns&&8>os){i.gutters.style.zIndex=-1;i.scroller.style.paddingRight=0}hs&&(r.style.width="0px");ss||(i.scroller.draggable=!0);if(cs){i.inputDiv.style.height="1px";i.inputDiv.style.position="absolute"}e&&(e.appendChild?e.appendChild(i.wrapper):e(i.wrapper));i.viewFrom=i.viewTo=t.first;i.reportedViewFrom=i.reportedViewTo=t.first;i.view=[];i.renderedView=null;i.externalMeasured=null;i.viewOffset=0;i.lastWrapHeight=i.lastWrapWidth=0;i.updateLineNumbers=null;i.nativeBarWidth=i.barHeight=i.barWidth=0;i.scrollbarsClipped=!1;i.lineNumWidth=i.lineNumInnerWidth=i.lineNumChars=null;i.prevInput="";i.alignWidgets=!1;i.pollingFast=!1;i.poll=new go;i.cachedCharWidth=i.cachedTextHeight=i.cachedPaddingH=null;i.inaccurateSelection=!1;i.maxLine=null;i.maxLineLength=0;i.maxLineChanged=!1;i.wheelDX=i.wheelDY=i.wheelStartX=i.wheelStartY=null;i.shift=!1;i.selForContextMenu=null}function i(t){t.doc.mode=e.getMode(t.options,t.doc.modeOption);r(t)}function r(e){e.doc.iter(function(e){e.stateAfter&&(e.stateAfter=null);e.styles&&(e.styles=null)});e.doc.frontier=e.doc.first;yt(e,100);e.state.modeGen++;e.curOp&&xi(e)}function n(e){if(e.options.lineWrapping){_a(e.display.wrapper,"CodeMirror-wrap");e.display.sizer.style.minWidth="";e.display.sizerWidth=null}else{wa(e.display.wrapper,"CodeMirror-wrap");d(e)}s(e);xi(e);qt(e);setTimeout(function(){v(e)},100)}function o(e){var t=ii(e.display),i=e.options.lineWrapping,r=i&&Math.max(5,e.display.scroller.clientWidth/ri(e.display)-3);return function(n){if(un(e.doc,n))return 0;var o=0;if(n.widgets)for(var s=0;s<n.widgets.length;s++)n.widgets[s].height&&(o+=n.widgets[s].height);return i?o+(Math.ceil(n.text.length/r)||1)*t:o+t}}function s(e){var t=e.doc,i=o(e);t.iter(function(e){var t=i(e);t!=e.height&&Fn(e,t)})}function a(e){e.display.wrapper.className=e.display.wrapper.className.replace(/\s*cm-s-\S+/g,"")+e.options.theme.replace(/(^|\s)\s*/g," cm-s-");qt(e)}function l(e){u(e);xi(e);setTimeout(function(){L(e)},20)}function u(e){var t=e.display.gutters,i=e.options.gutters;Oo(t);for(var r=0;r<i.length;++r){var n=i[r],o=t.appendChild(bo("div",null,"CodeMirror-gutter "+n));if("CodeMirror-linenumbers"==n){e.display.lineGutter=o;o.style.width=(e.display.lineNumWidth||1)+"px"}}t.style.display=r?"":"none";p(e)}function p(e){var t=e.display.gutters.offsetWidth;e.display.sizer.style.marginLeft=t+"px"}function c(e){if(0==e.height)return 0;for(var t,i=e.text.length,r=e;t=tn(r);){var n=t.find(0,!0);r=n.from.line;i+=n.from.ch-n.to.ch}r=e;for(;t=rn(r);){var n=t.find(0,!0);i-=r.text.length-n.from.ch;r=n.to.line;i+=r.text.length-n.to.ch}return i}function d(e){var t=e.display,i=e.doc;t.maxLine=Bn(i,i.first);t.maxLineLength=c(t.maxLine);t.maxLineChanged=!0;i.iter(function(e){var i=c(e);if(i>t.maxLineLength){t.maxLineLength=i;t.maxLine=e}})}function f(e){var t=Lo(e.gutters,"CodeMirror-linenumbers");if(-1==t&&e.lineNumbers)e.gutters=e.gutters.concat(["CodeMirror-linenumbers"]);else if(t>-1&&!e.lineNumbers){e.gutters=e.gutters.slice(0);e.gutters.splice(t,1)}}function h(e){var t=e.display,i=t.gutters.offsetWidth,r=Math.round(e.doc.height+bt(e.display));return{clientHeight:t.scroller.clientHeight,viewHeight:t.wrapper.clientHeight,scrollWidth:t.scroller.scrollWidth,clientWidth:t.scroller.clientWidth,viewWidth:t.wrapper.clientWidth,barLeft:e.options.fixedGutter?i:0,docHeight:r,scrollHeight:r+Pt(e)+t.barHeight,nativeBarWidth:t.nativeBarWidth,gutterWidth:i}}function E(e,t,i){this.cm=i;var r=this.vert=bo("div",[bo("div",null,null,"min-width: 1px")],"CodeMirror-vscrollbar"),n=this.horiz=bo("div",[bo("div",null,null,"height: 100%; min-height: 1px")],"CodeMirror-hscrollbar");e(r);e(n);Ea(r,"scroll",function(){r.clientHeight&&t(r.scrollTop,"vertical")});Ea(n,"scroll",function(){n.clientWidth&&t(n.scrollLeft,"horizontal")});this.checkedOverlay=!1;ns&&8>os&&(this.horiz.style.minHeight=this.vert.style.minWidth="18px")}function m(){}function g(t){if(t.display.scrollbars){t.display.scrollbars.clear();t.display.scrollbars.addClass&&wa(t.display.wrapper,t.display.scrollbars.addClass)}t.display.scrollbars=new e.scrollbarModel[t.options.scrollbarStyle](function(e){t.display.wrapper.insertBefore(e,t.display.scrollbarFiller);Ea(e,"mousedown",function(){t.state.focused&&setTimeout(Ao(Oi,t),0)});e.setAttribute("not-content","true")},function(e,i){"horizontal"==i?zi(t,e):qi(t,e)},t);t.display.scrollbars.addClass&&_a(t.display.wrapper,t.display.scrollbars.addClass)}function v(e,t){t||(t=h(e));var i=e.display.barWidth,r=e.display.barHeight;x(e,t);for(var n=0;4>n&&i!=e.display.barWidth||r!=e.display.barHeight;n++){i!=e.display.barWidth&&e.options.lineWrapping&&P(e);x(e,h(e));i=e.display.barWidth;r=e.display.barHeight}}function x(e,t){var i=e.display,r=i.scrollbars.update(t);i.sizer.style.paddingRight=(i.barWidth=r.right)+"px";i.sizer.style.paddingBottom=(i.barHeight=r.bottom)+"px";if(r.right&&r.bottom){i.scrollbarFiller.style.display="block";i.scrollbarFiller.style.height=r.bottom+"px";i.scrollbarFiller.style.width=r.right+"px"}else i.scrollbarFiller.style.display="";if(r.bottom&&e.options.coverGutterNextToScrollbar&&e.options.fixedGutter){i.gutterFiller.style.display="block";i.gutterFiller.style.height=r.bottom+"px";i.gutterFiller.style.width=t.gutterWidth+"px"}else i.gutterFiller.style.display=""}function N(e,t,i){var r=i&&null!=i.top?Math.max(0,i.top):e.scroller.scrollTop;r=Math.floor(r-Rt(e));var n=i&&null!=i.bottom?i.bottom:r+e.wrapper.clientHeight,o=jn(t,r),s=jn(t,n);if(i&&i.ensure){var a=i.ensure.from.line,l=i.ensure.to.line;if(o>a){o=a;s=jn(t,Wn(Bn(t,a))+e.wrapper.clientHeight)}else if(Math.min(l,t.lastLine())>=s){o=jn(t,Wn(Bn(t,l))-e.wrapper.clientHeight);s=l}}return{from:o,to:Math.max(s,o+1)}}function L(e){var t=e.display,i=t.view;if(t.alignWidgets||t.gutters.firstChild&&e.options.fixedGutter){for(var r=y(t)-t.scroller.scrollLeft+e.doc.scrollLeft,n=t.gutters.offsetWidth,o=r+"px",s=0;s<i.length;s++)if(!i[s].hidden){e.options.fixedGutter&&i[s].gutter&&(i[s].gutter.style.left=o);var a=i[s].alignable;if(a)for(var l=0;l<a.length;l++)a[l].style.left=o}e.options.fixedGutter&&(t.gutters.style.left=r+n+"px")}}function T(e){if(!e.options.lineNumbers)return!1;var t=e.doc,i=I(e.options,t.first+t.size-1),r=e.display;if(i.length!=r.lineNumChars){var n=r.measure.appendChild(bo("div",[bo("div",i)],"CodeMirror-linenumber CodeMirror-gutter-elt")),o=n.firstChild.offsetWidth,s=n.offsetWidth-o;r.lineGutter.style.width="";r.lineNumInnerWidth=Math.max(o,r.lineGutter.offsetWidth-s);r.lineNumWidth=r.lineNumInnerWidth+s;r.lineNumChars=r.lineNumInnerWidth?i.length:-1;r.lineGutter.style.width=r.lineNumWidth+"px";p(e);return!0}return!1}function I(e,t){return String(e.lineNumberFormatter(t+e.firstLineNumber))}function y(e){return e.scroller.getBoundingClientRect().left-e.sizer.getBoundingClientRect().left}function A(e,t,i){var r=e.display;this.viewport=t;this.visible=N(r,e.doc,t);this.editorIsHidden=!r.wrapper.offsetWidth;this.wrapperHeight=r.wrapper.clientHeight;this.wrapperWidth=r.wrapper.clientWidth;this.oldDisplayWidth=Dt(e);this.force=i;this.dims=w(e)}function S(e){var t=e.display;if(!t.scrollbarsClipped&&t.scroller.offsetWidth){t.nativeBarWidth=t.scroller.offsetWidth-t.scroller.clientWidth;t.heightForcer.style.height=Pt(e)+"px";t.sizer.style.marginBottom=-t.nativeBarWidth+"px";t.sizer.style.borderRightWidth=Pt(e)+"px";t.scrollbarsClipped=!0}}function C(e,t){var i=e.display,r=e.doc;if(t.editorIsHidden){Li(e);return!1}if(!t.force&&t.visible.from>=i.viewFrom&&t.visible.to<=i.viewTo&&(null==i.updateLineNumbers||i.updateLineNumbers>=i.viewTo)&&i.renderedView==i.view&&0==Ai(e))return!1;if(T(e)){Li(e);t.dims=w(e)}var n=r.first+r.size,o=Math.max(t.visible.from-e.options.viewportMargin,r.first),s=Math.min(n,t.visible.to+e.options.viewportMargin);i.viewFrom<o&&o-i.viewFrom<20&&(o=Math.max(r.first,i.viewFrom));i.viewTo>s&&i.viewTo-s<20&&(s=Math.min(n,i.viewTo));if(Ts){o=an(e.doc,o);s=ln(e.doc,s)}var a=o!=i.viewFrom||s!=i.viewTo||i.lastWrapHeight!=t.wrapperHeight||i.lastWrapWidth!=t.wrapperWidth;yi(e,o,s);i.viewOffset=Wn(Bn(e.doc,i.viewFrom));e.display.mover.style.top=i.viewOffset+"px";var l=Ai(e);if(!a&&0==l&&!t.force&&i.renderedView==i.view&&(null==i.updateLineNumbers||i.updateLineNumbers>=i.viewTo))return!1;var u=wo();l>4&&(i.lineDiv.style.display="none");_(e,i.updateLineNumbers,t.dims);l>4&&(i.lineDiv.style.display="");i.renderedView=i.view;u&&wo()!=u&&u.offsetHeight&&u.focus();Oo(i.cursorDiv);Oo(i.selectionDiv);i.gutters.style.height=0;if(a){i.lastWrapHeight=t.wrapperHeight;i.lastWrapWidth=t.wrapperWidth;yt(e,400)}i.updateLineNumbers=null;return!0}function R(e,t){for(var i=t.force,r=t.viewport,n=!0;;n=!1){if(n&&e.options.lineWrapping&&t.oldDisplayWidth!=Dt(e))i=!0;else{i=!1;r&&null!=r.top&&(r={top:Math.min(e.doc.height+bt(e.display)-wt(e),r.top)});t.visible=N(e.display,e.doc,r);if(t.visible.from>=e.display.viewFrom&&t.visible.to<=e.display.viewTo)break}if(!C(e,t))break;P(e);var o=h(e);Nt(e);O(e,o);v(e,o)}po(e,"update",e);if(e.display.viewFrom!=e.display.reportedViewFrom||e.display.viewTo!=e.display.reportedViewTo){po(e,"viewportChange",e,e.display.viewFrom,e.display.viewTo);e.display.reportedViewFrom=e.display.viewFrom;e.display.reportedViewTo=e.display.viewTo}}function b(e,t){var i=new A(e,t);if(C(e,i)){P(e);R(e,i);var r=h(e);Nt(e);O(e,r);v(e,r)}}function O(e,t){e.display.sizer.style.minHeight=t.docHeight+"px";var i=t.docHeight+e.display.barHeight;e.display.heightForcer.style.top=i+"px";e.display.gutters.style.height=Math.max(i+Pt(e),t.clientHeight)+"px"}function P(e){for(var t=e.display,i=t.lineDiv.offsetTop,r=0;r<t.view.length;r++){var n,o=t.view[r];if(!o.hidden){if(ns&&8>os){var s=o.node.offsetTop+o.node.offsetHeight;n=s-i;i=s}else{var a=o.node.getBoundingClientRect();n=a.bottom-a.top}var l=o.line.height-n;2>n&&(n=ii(t));if(l>.001||-.001>l){Fn(o.line,n);D(o.line);if(o.rest)for(var u=0;u<o.rest.length;u++)D(o.rest[u])}}}}function D(e){if(e.widgets)for(var t=0;t<e.widgets.length;++t)e.widgets[t].height=e.widgets[t].node.offsetHeight}function w(e){for(var t=e.display,i={},r={},n=t.gutters.clientLeft,o=t.gutters.firstChild,s=0;o;o=o.nextSibling,++s){i[e.options.gutters[s]]=o.offsetLeft+o.clientLeft+n;r[e.options.gutters[s]]=o.clientWidth}return{fixedPos:y(t),gutterTotalWidth:t.gutters.offsetWidth,gutterLeft:i,gutterWidth:r,wrapperWidth:t.wrapper.clientWidth}}function _(e,t,i){function r(t){var i=t.nextSibling;ss&&ms&&e.display.currentWheelTarget==t?t.style.display="none":t.parentNode.removeChild(t);return i}for(var n=e.display,o=e.options.lineNumbers,s=n.lineDiv,a=s.firstChild,l=n.view,u=n.viewFrom,p=0;p<l.length;p++){var c=l[p];if(c.hidden);else if(c.node){for(;a!=c.node;)a=r(a);var d=o&&null!=t&&u>=t&&c.lineNumber;if(c.changes){Lo(c.changes,"gutter")>-1&&(d=!1);M(e,c,u,i)}if(d){Oo(c.lineNumber);c.lineNumber.appendChild(document.createTextNode(I(e.options,u)))}a=c.node.nextSibling}else{var f=j(e,c,u,i);s.insertBefore(f,a)}u+=c.size}for(;a;)a=r(a)}function M(e,t,i,r){for(var n=0;n<t.changes.length;n++){var o=t.changes[n];"text"==o?U(e,t):"gutter"==o?F(e,t,i,r):"class"==o?V(t):"widget"==o&&H(t,r)}t.changes=null}function k(e){if(e.node==e.text){e.node=bo("div",null,null,"position: relative");e.text.parentNode&&e.text.parentNode.replaceChild(e.node,e.text);e.node.appendChild(e.text);ns&&8>os&&(e.node.style.zIndex=2)}return e.node}function G(e){var t=e.bgClass?e.bgClass+" "+(e.line.bgClass||""):e.line.bgClass;t&&(t+=" CodeMirror-linebackground");if(e.background)if(t)e.background.className=t;else{e.background.parentNode.removeChild(e.background);e.background=null}else if(t){var i=k(e);e.background=i.insertBefore(bo("div",null,t),i.firstChild)}}function B(e,t){var i=e.display.externalMeasured;if(i&&i.line==t.line){e.display.externalMeasured=null;t.measure=i.measure;return i.built}return An(e,t)}function U(e,t){var i=t.text.className,r=B(e,t);t.text==t.node&&(t.node=r.pre);t.text.parentNode.replaceChild(r.pre,t.text);t.text=r.pre;if(r.bgClass!=t.bgClass||r.textClass!=t.textClass){t.bgClass=r.bgClass;t.textClass=r.textClass;V(t)}else i&&(t.text.className=i)}function V(e){G(e);e.line.wrapClass?k(e).className=e.line.wrapClass:e.node!=e.text&&(e.node.className="");var t=e.textClass?e.textClass+" "+(e.line.textClass||""):e.line.textClass;e.text.className=t||""}function F(e,t,i,r){if(t.gutter){t.node.removeChild(t.gutter);t.gutter=null}var n=t.line.gutterMarkers;if(e.options.lineNumbers||n){var o=k(t),s=t.gutter=o.insertBefore(bo("div",null,"CodeMirror-gutter-wrapper","left: "+(e.options.fixedGutter?r.fixedPos:-r.gutterTotalWidth)+"px; width: "+r.gutterTotalWidth+"px"),t.text);t.line.gutterClass&&(s.className+=" "+t.line.gutterClass);!e.options.lineNumbers||n&&n["CodeMirror-linenumbers"]||(t.lineNumber=s.appendChild(bo("div",I(e.options,i),"CodeMirror-linenumber CodeMirror-gutter-elt","left: "+r.gutterLeft["CodeMirror-linenumbers"]+"px; width: "+e.display.lineNumInnerWidth+"px")));if(n)for(var a=0;a<e.options.gutters.length;++a){var l=e.options.gutters[a],u=n.hasOwnProperty(l)&&n[l];u&&s.appendChild(bo("div",[u],"CodeMirror-gutter-elt","left: "+r.gutterLeft[l]+"px; width: "+r.gutterWidth[l]+"px"))}}}function H(e,t){e.alignable&&(e.alignable=null);for(var i,r=e.node.firstChild;r;r=i){var i=r.nextSibling;"CodeMirror-linewidget"==r.className&&e.node.removeChild(r)}W(e,t)}function j(e,t,i,r){var n=B(e,t);t.text=t.node=n.pre;n.bgClass&&(t.bgClass=n.bgClass);n.textClass&&(t.textClass=n.textClass);V(t);F(e,t,i,r);W(t,r);return t.node}function W(e,t){q(e.line,e,t,!0);if(e.rest)for(var i=0;i<e.rest.length;i++)q(e.rest[i],e,t,!1)}function q(e,t,i,r){if(e.widgets)for(var n=k(t),o=0,s=e.widgets;o<s.length;++o){var a=s[o],l=bo("div",[a.node],"CodeMirror-linewidget");a.handleMouseEvents||l.setAttribute("cm-ignore-events","true");z(a,l,t,i);r&&a.above?n.insertBefore(l,t.gutter||t.text):n.appendChild(l);po(a,"redraw")}}function z(e,t,i,r){if(e.noHScroll){(i.alignable||(i.alignable=[])).push(t);var n=r.wrapperWidth;t.style.left=r.fixedPos+"px";if(!e.coverGutter){n-=r.gutterTotalWidth;t.style.paddingLeft=r.gutterTotalWidth+"px"}t.style.width=n+"px"}if(e.coverGutter){t.style.zIndex=5;t.style.position="relative";e.noHScroll||(t.style.marginLeft=-r.gutterTotalWidth+"px")}}function X(e){return Is(e.line,e.ch)}function Y(e,t){return ys(e,t)<0?t:e}function K(e,t){return ys(e,t)<0?e:t}function $(e,t){this.ranges=e;this.primIndex=t}function Q(e,t){this.anchor=e;this.head=t}function Z(e,t){var i=e[t];e.sort(function(e,t){return ys(e.from(),t.from())});t=Lo(e,i);for(var r=1;r<e.length;r++){var n=e[r],o=e[r-1];if(ys(o.to(),n.from())>=0){var s=K(o.from(),n.from()),a=Y(o.to(),n.to()),l=o.empty()?n.from()==n.head:o.from()==o.head;t>=r&&--t;e.splice(--r,2,new Q(l?a:s,l?s:a))}}return new $(e,t)}function J(e,t){return new $([new Q(e,t||e)],0)}function et(e,t){return Math.max(e.first,Math.min(t,e.first+e.size-1))}function tt(e,t){if(t.line<e.first)return Is(e.first,0);var i=e.first+e.size-1;return t.line>i?Is(i,Bn(e,i).text.length):it(t,Bn(e,t.line).text.length)}function it(e,t){var i=e.ch;return null==i||i>t?Is(e.line,t):0>i?Is(e.line,0):e}function rt(e,t){return t>=e.first&&t<e.first+e.size}function nt(e,t){for(var i=[],r=0;r<t.length;r++)i[r]=tt(e,t[r]);return i}function ot(e,t,i,r){if(e.cm&&e.cm.display.shift||e.extend){var n=t.anchor;if(r){var o=ys(i,n)<0;if(o!=ys(r,n)<0){n=i;i=r}else o!=ys(i,r)<0&&(i=r)}return new Q(n,i)}return new Q(r||i,i)}function st(e,t,i,r){dt(e,new $([ot(e,e.sel.primary(),t,i)],0),r)}function at(e,t,i){for(var r=[],n=0;n<e.sel.ranges.length;n++)r[n]=ot(e,e.sel.ranges[n],t[n],null);var o=Z(r,e.sel.primIndex);dt(e,o,i)}function lt(e,t,i,r){var n=e.sel.ranges.slice(0);n[t]=i;dt(e,Z(n,e.sel.primIndex),r)}function ut(e,t,i,r){dt(e,J(t,i),r)}function pt(e,t){var i={ranges:t.ranges,update:function(t){this.ranges=[];for(var i=0;i<t.length;i++)this.ranges[i]=new Q(tt(e,t[i].anchor),tt(e,t[i].head))}};ga(e,"beforeSelectionChange",e,i);e.cm&&ga(e.cm,"beforeSelectionChange",e.cm,i);return i.ranges!=t.ranges?Z(i.ranges,i.ranges.length-1):t}function ct(e,t,i){var r=e.history.done,n=No(r);if(n&&n.ranges){r[r.length-1]=t;ft(e,t,i)}else dt(e,t,i)}function dt(e,t,i){ft(e,t,i);Zn(e,e.sel,e.cm?e.cm.curOp.id:0/0,i)}function ft(e,t,i){(Eo(e,"beforeSelectionChange")||e.cm&&Eo(e.cm,"beforeSelectionChange"))&&(t=pt(e,t));var r=i&&i.bias||(ys(t.primary().head,e.sel.primary().head)<0?-1:1);ht(e,mt(e,t,r,!0));i&&i.scroll===!1||!e.cm||yr(e.cm)}function ht(e,t){if(!t.equals(e.sel)){e.sel=t;if(e.cm){e.cm.curOp.updateInput=e.cm.curOp.selectionChanged=!0;ho(e.cm)}po(e,"cursorActivity",e)}}function Et(e){ht(e,mt(e,e.sel,null,!1),La)}function mt(e,t,i,r){for(var n,o=0;o<t.ranges.length;o++){var s=t.ranges[o],a=gt(e,s.anchor,i,r),l=gt(e,s.head,i,r);if(n||a!=s.anchor||l!=s.head){n||(n=t.ranges.slice(0,o));n[o]=new Q(a,l)}}return n?Z(n,t.primIndex):t}function gt(e,t,i,r){var n=!1,o=t,s=i||1;e.cantEdit=!1;e:for(;;){var a=Bn(e,o.line);if(a.markedSpans)for(var l=0;l<a.markedSpans.length;++l){var u=a.markedSpans[l],p=u.marker;if((null==u.from||(p.inclusiveLeft?u.from<=o.ch:u.from<o.ch))&&(null==u.to||(p.inclusiveRight?u.to>=o.ch:u.to>o.ch))){if(r){ga(p,"beforeCursorEnter");if(p.explicitlyCleared){if(a.markedSpans){--l;continue}break}}if(!p.atomic)continue;var c=p.find(0>s?-1:1);if(0==ys(c,o)){c.ch+=s;c.ch<0?c=c.line>e.first?tt(e,Is(c.line-1)):null:c.ch>a.text.length&&(c=c.line<e.first+e.size-1?Is(c.line+1,0):null);if(!c){if(n){if(!r)return gt(e,t,i,!0);e.cantEdit=!0;return Is(e.first,0)}n=!0;c=t;s=-s}}o=c;continue e}}return o}}function vt(e){for(var t=e.display,i=e.doc,r={},n=r.cursors=document.createDocumentFragment(),o=r.selection=document.createDocumentFragment(),s=0;s<i.sel.ranges.length;s++){var a=i.sel.ranges[s],l=a.empty();(l||e.options.showCursorWhenSelecting)&&Lt(e,a,n);l||Tt(e,a,o)}if(e.options.moveInputWithCursor){var u=Qt(e,i.sel.primary().head,"div"),p=t.wrapper.getBoundingClientRect(),c=t.lineDiv.getBoundingClientRect();r.teTop=Math.max(0,Math.min(t.wrapper.clientHeight-10,u.top+c.top-p.top));r.teLeft=Math.max(0,Math.min(t.wrapper.clientWidth-10,u.left+c.left-p.left))}return r}function xt(e,t){Po(e.display.cursorDiv,t.cursors);Po(e.display.selectionDiv,t.selection);if(null!=t.teTop){e.display.inputDiv.style.top=t.teTop+"px";e.display.inputDiv.style.left=t.teLeft+"px"}}function Nt(e){xt(e,vt(e))}function Lt(e,t,i){var r=Qt(e,t.head,"div",null,null,!e.options.singleCursorHeightPerLine),n=i.appendChild(bo("div"," ","CodeMirror-cursor"));n.style.left=r.left+"px";n.style.top=r.top+"px";n.style.height=Math.max(0,r.bottom-r.top)*e.options.cursorHeight+"px";if(r.other){var o=i.appendChild(bo("div"," ","CodeMirror-cursor CodeMirror-secondarycursor"));o.style.display="";o.style.left=r.other.left+"px";o.style.top=r.other.top+"px";o.style.height=.85*(r.other.bottom-r.other.top)+"px"}}function Tt(e,t,i){function r(e,t,i,r){0>t&&(t=0);t=Math.round(t);r=Math.round(r);a.appendChild(bo("div",null,"CodeMirror-selected","position: absolute; left: "+e+"px; top: "+t+"px; width: "+(null==i?p-e:i)+"px; height: "+(r-t)+"px"))}function n(t,i,n){function o(i,r){return $t(e,Is(t,i),"div",c,r)}var a,l,c=Bn(s,t),d=c.text.length;Ho(qn(c),i||0,null==n?d:n,function(e,t,s){var c,f,h,E=o(e,"left");if(e==t){c=E;f=h=E.left}else{c=o(t-1,"right");if("rtl"==s){var m=E;E=c;c=m}f=E.left;h=c.right}null==i&&0==e&&(f=u);if(c.top-E.top>3){r(f,E.top,null,E.bottom);f=u;E.bottom<c.top&&r(f,E.bottom,null,c.top)}null==n&&t==d&&(h=p);(!a||E.top<a.top||E.top==a.top&&E.left<a.left)&&(a=E);(!l||c.bottom>l.bottom||c.bottom==l.bottom&&c.right>l.right)&&(l=c);u+1>f&&(f=u);r(f,c.top,h-f,c.bottom)});return{start:a,end:l}}var o=e.display,s=e.doc,a=document.createDocumentFragment(),l=Ot(e.display),u=l.left,p=Math.max(o.sizerWidth,Dt(e)-o.sizer.offsetLeft)-l.right,c=t.from(),d=t.to();if(c.line==d.line)n(c.line,c.ch,d.ch);else{var f=Bn(s,c.line),h=Bn(s,d.line),E=on(f)==on(h),m=n(c.line,c.ch,E?f.text.length+1:null).end,g=n(d.line,E?0:null,d.ch).start;if(E)if(m.top<g.top-2){r(m.right,m.top,null,m.bottom);r(u,g.top,g.left,g.bottom)}else r(m.right,m.top,g.left-m.right,m.bottom);m.bottom<g.top&&r(u,m.bottom,null,g.top)}i.appendChild(a)}function It(e){if(e.state.focused){var t=e.display;clearInterval(t.blinker);var i=!0;t.cursorDiv.style.visibility="";e.options.cursorBlinkRate>0?t.blinker=setInterval(function(){t.cursorDiv.style.visibility=(i=!i)?"":"hidden"},e.options.cursorBlinkRate):e.options.cursorBlinkRate<0&&(t.cursorDiv.style.visibility="hidden")}}function yt(e,t){e.doc.mode.startState&&e.doc.frontier<e.display.viewTo&&e.state.highlight.set(t,Ao(At,e))}function At(e){var t=e.doc;t.frontier<t.first&&(t.frontier=t.first);if(!(t.frontier>=e.display.viewTo)){var i=+new Date+e.options.workTime,r=Xs(t.mode,Ct(e,t.frontier)),n=[];t.iter(t.frontier,Math.min(t.first+t.size,e.display.viewTo+500),function(o){if(t.frontier>=e.display.viewFrom){var s=o.styles,a=Ln(e,o,r,!0);o.styles=a.styles;var l=o.styleClasses,u=a.classes;u?o.styleClasses=u:l&&(o.styleClasses=null);for(var p=!s||s.length!=o.styles.length||l!=u&&(!l||!u||l.bgClass!=u.bgClass||l.textClass!=u.textClass),c=0;!p&&c<s.length;++c)p=s[c]!=o.styles[c];p&&n.push(t.frontier);o.stateAfter=Xs(t.mode,r)}else{In(e,o.text,r);o.stateAfter=t.frontier%5==0?Xs(t.mode,r):null}++t.frontier;if(+new Date>i){yt(e,e.options.workDelay);return!0}});n.length&&fi(e,function(){for(var t=0;t<n.length;t++)Ni(e,n[t],"text")})}}function St(e,t,i){for(var r,n,o=e.doc,s=i?-1:t-(e.doc.mode.innerMode?1e3:100),a=t;a>s;--a){if(a<=o.first)return o.first;var l=Bn(o,a-1);if(l.stateAfter&&(!i||a<=o.frontier))return a;var u=ya(l.text,null,e.options.tabSize);if(null==n||r>u){n=a-1;r=u}}return n}function Ct(e,t,i){var r=e.doc,n=e.display;if(!r.mode.startState)return!0;var o=St(e,t,i),s=o>r.first&&Bn(r,o-1).stateAfter;s=s?Xs(r.mode,s):Ys(r.mode);r.iter(o,t,function(i){In(e,i.text,s);var a=o==t-1||o%5==0||o>=n.viewFrom&&o<n.viewTo;i.stateAfter=a?Xs(r.mode,s):null;++o});i&&(r.frontier=o);return s}function Rt(e){return e.lineSpace.offsetTop}function bt(e){return e.mover.offsetHeight-e.lineSpace.offsetHeight}function Ot(e){if(e.cachedPaddingH)return e.cachedPaddingH;var t=Po(e.measure,bo("pre","x")),i=window.getComputedStyle?window.getComputedStyle(t):t.currentStyle,r={left:parseInt(i.paddingLeft),right:parseInt(i.paddingRight)};isNaN(r.left)||isNaN(r.right)||(e.cachedPaddingH=r);return r}function Pt(e){return xa-e.display.nativeBarWidth}function Dt(e){return e.display.scroller.clientWidth-Pt(e)-e.display.barWidth}function wt(e){return e.display.scroller.clientHeight-Pt(e)-e.display.barHeight}function _t(e,t,i){var r=e.options.lineWrapping,n=r&&Dt(e);if(!t.measure.heights||r&&t.measure.width!=n){var o=t.measure.heights=[];if(r){t.measure.width=n;for(var s=t.text.firstChild.getClientRects(),a=0;a<s.length-1;a++){var l=s[a],u=s[a+1];Math.abs(l.bottom-u.bottom)>2&&o.push((l.bottom+u.top)/2-i.top)}}o.push(i.bottom-i.top)}}function Mt(e,t,i){if(e.line==t)return{map:e.measure.map,cache:e.measure.cache};for(var r=0;r<e.rest.length;r++)if(e.rest[r]==t)return{map:e.measure.maps[r],cache:e.measure.caches[r]};for(var r=0;r<e.rest.length;r++)if(Hn(e.rest[r])>i)return{map:e.measure.maps[r],cache:e.measure.caches[r],before:!0}}function kt(e,t){t=on(t);var i=Hn(t),r=e.display.externalMeasured=new gi(e.doc,t,i);r.lineN=i;var n=r.built=An(e,r);r.text=n.pre;Po(e.display.lineMeasure,n.pre);return r}function Gt(e,t,i,r){return Vt(e,Ut(e,t),i,r)}function Bt(e,t){if(t>=e.display.viewFrom&&t<e.display.viewTo)return e.display.view[Ti(e,t)];var i=e.display.externalMeasured;return i&&t>=i.lineN&&t<i.lineN+i.size?i:void 0}function Ut(e,t){var i=Hn(t),r=Bt(e,i);r&&!r.text?r=null:r&&r.changes&&M(e,r,i,w(e));r||(r=kt(e,t));var n=Mt(r,t,i);return{line:t,view:r,rect:null,map:n.map,cache:n.cache,before:n.before,hasHeights:!1}}function Vt(e,t,i,r,n){t.before&&(i=-1);var o,s=i+(r||"");if(t.cache.hasOwnProperty(s))o=t.cache[s];else{t.rect||(t.rect=t.view.text.getBoundingClientRect());if(!t.hasHeights){_t(e,t.view,t.rect);t.hasHeights=!0}o=Ft(e,t,i,r);o.bogus||(t.cache[s]=o)}return{left:o.left,right:o.right,top:n?o.rtop:o.top,bottom:n?o.rbottom:o.bottom}}function Ft(e,t,i,r){for(var n,o,s,a,l=t.map,u=0;u<l.length;u+=3){var p=l[u],c=l[u+1];if(p>i){o=0;s=1;a="left"}else if(c>i){o=i-p;s=o+1}else if(u==l.length-3||i==c&&l[u+3]>i){s=c-p;o=s-1;i>=c&&(a="right")}if(null!=o){n=l[u+2];p==c&&r==(n.insertLeft?"left":"right")&&(a=r);if("left"==r&&0==o)for(;u&&l[u-2]==l[u-3]&&l[u-1].insertLeft;){n=l[(u-=3)+2];a="left"}if("right"==r&&o==c-p)for(;u<l.length-3&&l[u+3]==l[u+4]&&!l[u+5].insertLeft;){n=l[(u+=3)+2];a="right"}break}}var d;if(3==n.nodeType){for(var u=0;4>u;u++){for(;o&&Ro(t.line.text.charAt(p+o));)--o;for(;c>p+s&&Ro(t.line.text.charAt(p+s));)++s;if(ns&&9>os&&0==o&&s==c-p)d=n.parentNode.getBoundingClientRect();else if(ns&&e.options.lineWrapping){var f=Ca(n,o,s).getClientRects();d=f.length?f["right"==r?f.length-1:0]:Rs}else d=Ca(n,o,s).getBoundingClientRect()||Rs;if(d.left||d.right||0==o)break;s=o;o-=1;a="right"}ns&&11>os&&(d=Ht(e.display.measure,d))}else{o>0&&(a=r="right");var f;d=e.options.lineWrapping&&(f=n.getClientRects()).length>1?f["right"==r?f.length-1:0]:n.getBoundingClientRect()}if(ns&&9>os&&!o&&(!d||!d.left&&!d.right)){var h=n.parentNode.getClientRects()[0];d=h?{left:h.left,right:h.left+ri(e.display),top:h.top,bottom:h.bottom}:Rs}for(var E=d.top-t.rect.top,m=d.bottom-t.rect.top,g=(E+m)/2,v=t.view.measure.heights,u=0;u<v.length-1&&!(g<v[u]);u++);var x=u?v[u-1]:0,N=v[u],L={left:("right"==a?d.right:d.left)-t.rect.left,right:("left"==a?d.left:d.right)-t.rect.left,top:x,bottom:N};d.left||d.right||(L.bogus=!0);if(!e.options.singleCursorHeightPerLine){L.rtop=E;L.rbottom=m}return L}function Ht(e,t){if(!window.screen||null==screen.logicalXDPI||screen.logicalXDPI==screen.deviceXDPI||!Fo(e))return t;var i=screen.logicalXDPI/screen.deviceXDPI,r=screen.logicalYDPI/screen.deviceYDPI;return{left:t.left*i,right:t.right*i,top:t.top*r,bottom:t.bottom*r}}function jt(e){if(e.measure){e.measure.cache={};e.measure.heights=null;if(e.rest)for(var t=0;t<e.rest.length;t++)e.measure.caches[t]={}}}function Wt(e){e.display.externalMeasure=null;Oo(e.display.lineMeasure);for(var t=0;t<e.display.view.length;t++)jt(e.display.view[t])}function qt(e){Wt(e);e.display.cachedCharWidth=e.display.cachedTextHeight=e.display.cachedPaddingH=null;e.options.lineWrapping||(e.display.maxLineChanged=!0);e.display.lineNumChars=null}function zt(){return window.pageXOffset||(document.documentElement||document.body).scrollLeft}function Xt(){return window.pageYOffset||(document.documentElement||document.body).scrollTop}function Yt(e,t,i,r){if(t.widgets)for(var n=0;n<t.widgets.length;++n)if(t.widgets[n].above){var o=dn(t.widgets[n]);i.top+=o;i.bottom+=o}if("line"==r)return i;r||(r="local");var s=Wn(t);"local"==r?s+=Rt(e.display):s-=e.display.viewOffset;if("page"==r||"window"==r){var a=e.display.lineSpace.getBoundingClientRect();s+=a.top+("window"==r?0:Xt());var l=a.left+("window"==r?0:zt());i.left+=l;i.right+=l}i.top+=s;i.bottom+=s;return i}function Kt(e,t,i){if("div"==i)return t;var r=t.left,n=t.top;if("page"==i){r-=zt();n-=Xt()}else if("local"==i||!i){var o=e.display.sizer.getBoundingClientRect();r+=o.left;n+=o.top}var s=e.display.lineSpace.getBoundingClientRect();return{left:r-s.left,top:n-s.top}}function $t(e,t,i,r,n){r||(r=Bn(e.doc,t.line));return Yt(e,r,Gt(e,r,t.ch,n),i)}function Qt(e,t,i,r,n,o){function s(t,s){var a=Vt(e,n,t,s?"right":"left",o);s?a.left=a.right:a.right=a.left;return Yt(e,r,a,i)}function a(e,t){var i=l[t],r=i.level%2;if(e==jo(i)&&t&&i.level<l[t-1].level){i=l[--t];e=Wo(i)-(i.level%2?0:1);r=!0}else if(e==Wo(i)&&t<l.length-1&&i.level<l[t+1].level){i=l[++t];e=jo(i)-i.level%2;r=!1}return r&&e==i.to&&e>i.from?s(e-1):s(e,r)}r=r||Bn(e.doc,t.line);n||(n=Ut(e,r));var l=qn(r),u=t.ch;if(!l)return s(u);var p=Qo(l,u),c=a(u,p);null!=Ha&&(c.other=a(u,Ha));return c}function Zt(e,t){var i=0,t=tt(e.doc,t);e.options.lineWrapping||(i=ri(e.display)*t.ch);var r=Bn(e.doc,t.line),n=Wn(r)+Rt(e.display);return{left:i,right:i,top:n,bottom:n+r.height}}function Jt(e,t,i,r){var n=Is(e,t);n.xRel=r;i&&(n.outside=!0);return n}function ei(e,t,i){var r=e.doc;i+=e.display.viewOffset;if(0>i)return Jt(r.first,0,!0,-1);var n=jn(r,i),o=r.first+r.size-1;if(n>o)return Jt(r.first+r.size-1,Bn(r,o).text.length,!0,1);0>t&&(t=0);for(var s=Bn(r,n);;){var a=ti(e,s,n,t,i),l=rn(s),u=l&&l.find(0,!0);if(!l||!(a.ch>u.from.ch||a.ch==u.from.ch&&a.xRel>0))return a;n=Hn(s=u.to.line)}}function ti(e,t,i,r,n){function o(r){var n=Qt(e,Is(i,r),"line",t,u);a=!0;if(s>n.bottom)return n.left-l;if(s<n.top)return n.left+l;a=!1;
return n.left}var s=n-Wn(t),a=!1,l=2*e.display.wrapper.clientWidth,u=Ut(e,t),p=qn(t),c=t.text.length,d=qo(t),f=zo(t),h=o(d),E=a,m=o(f),g=a;if(r>m)return Jt(i,f,g,1);for(;;){if(p?f==d||f==Jo(t,d,1):1>=f-d){for(var v=h>r||m-r>=r-h?d:f,x=r-(v==d?h:m);Ro(t.text.charAt(v));)++v;var N=Jt(i,v,v==d?E:g,-1>x?-1:x>1?1:0);return N}var L=Math.ceil(c/2),T=d+L;if(p){T=d;for(var I=0;L>I;++I)T=Jo(t,T,1)}var y=o(T);if(y>r){f=T;m=y;(g=a)&&(m+=1e3);c=L}else{d=T;h=y;E=a;c-=L}}}function ii(e){if(null!=e.cachedTextHeight)return e.cachedTextHeight;if(null==As){As=bo("pre");for(var t=0;49>t;++t){As.appendChild(document.createTextNode("x"));As.appendChild(bo("br"))}As.appendChild(document.createTextNode("x"))}Po(e.measure,As);var i=As.offsetHeight/50;i>3&&(e.cachedTextHeight=i);Oo(e.measure);return i||1}function ri(e){if(null!=e.cachedCharWidth)return e.cachedCharWidth;var t=bo("span","xxxxxxxxxx"),i=bo("pre",[t]);Po(e.measure,i);var r=t.getBoundingClientRect(),n=(r.right-r.left)/10;n>2&&(e.cachedCharWidth=n);return n||10}function ni(e){e.curOp={cm:e,viewChanged:!1,startHeight:e.doc.height,forceUpdate:!1,updateInput:null,typing:!1,changeObjs:null,cursorActivityHandlers:null,cursorActivityCalled:0,selectionChanged:!1,updateMaxLine:!1,scrollLeft:null,scrollTop:null,scrollToPos:null,id:++Os};bs?bs.ops.push(e.curOp):e.curOp.ownsGroup=bs={ops:[e.curOp],delayedCallbacks:[]}}function oi(e){var t=e.delayedCallbacks,i=0;do{for(;i<t.length;i++)t[i]();for(var r=0;r<e.ops.length;r++){var n=e.ops[r];if(n.cursorActivityHandlers)for(;n.cursorActivityCalled<n.cursorActivityHandlers.length;)n.cursorActivityHandlers[n.cursorActivityCalled++](n.cm)}}while(i<t.length)}function si(e){var t=e.curOp,i=t.ownsGroup;if(i)try{oi(i)}finally{bs=null;for(var r=0;r<i.ops.length;r++)i.ops[r].cm.curOp=null;ai(i)}}function ai(e){for(var t=e.ops,i=0;i<t.length;i++)li(t[i]);for(var i=0;i<t.length;i++)ui(t[i]);for(var i=0;i<t.length;i++)pi(t[i]);for(var i=0;i<t.length;i++)ci(t[i]);for(var i=0;i<t.length;i++)di(t[i])}function li(e){var t=e.cm,i=t.display;S(t);e.updateMaxLine&&d(t);e.mustUpdate=e.viewChanged||e.forceUpdate||null!=e.scrollTop||e.scrollToPos&&(e.scrollToPos.from.line<i.viewFrom||e.scrollToPos.to.line>=i.viewTo)||i.maxLineChanged&&t.options.lineWrapping;e.update=e.mustUpdate&&new A(t,e.mustUpdate&&{top:e.scrollTop,ensure:e.scrollToPos},e.forceUpdate)}function ui(e){e.updatedDisplay=e.mustUpdate&&C(e.cm,e.update)}function pi(e){var t=e.cm,i=t.display;e.updatedDisplay&&P(t);e.barMeasure=h(t);if(i.maxLineChanged&&!t.options.lineWrapping){e.adjustWidthTo=Gt(t,i.maxLine,i.maxLine.text.length).left+3;t.display.sizerWidth=e.adjustWidthTo;e.barMeasure.scrollWidth=Math.max(i.scroller.clientWidth,i.sizer.offsetLeft+e.adjustWidthTo+Pt(t)+t.display.barWidth);e.maxScrollLeft=Math.max(0,i.sizer.offsetLeft+e.adjustWidthTo-Dt(t))}(e.updatedDisplay||e.selectionChanged)&&(e.newSelectionNodes=vt(t))}function ci(e){var t=e.cm;if(null!=e.adjustWidthTo){t.display.sizer.style.minWidth=e.adjustWidthTo+"px";e.maxScrollLeft<t.doc.scrollLeft&&zi(t,Math.min(t.display.scroller.scrollLeft,e.maxScrollLeft),!0);t.display.maxLineChanged=!1}e.newSelectionNodes&&xt(t,e.newSelectionNodes);e.updatedDisplay&&O(t,e.barMeasure);(e.updatedDisplay||e.startHeight!=t.doc.height)&&v(t,e.barMeasure);e.selectionChanged&&It(t);t.state.focused&&e.updateInput&&bi(t,e.typing)}function di(e){var t=e.cm,i=t.display,r=t.doc;e.updatedDisplay&&R(t,e.update);null==i.wheelStartX||null==e.scrollTop&&null==e.scrollLeft&&!e.scrollToPos||(i.wheelStartX=i.wheelStartY=null);if(null!=e.scrollTop&&(i.scroller.scrollTop!=e.scrollTop||e.forceScroll)){r.scrollTop=Math.max(0,Math.min(i.scroller.scrollHeight-i.scroller.clientHeight,e.scrollTop));i.scrollbars.setScrollTop(r.scrollTop);i.scroller.scrollTop=r.scrollTop}if(null!=e.scrollLeft&&(i.scroller.scrollLeft!=e.scrollLeft||e.forceScroll)){r.scrollLeft=Math.max(0,Math.min(i.scroller.scrollWidth-Dt(t),e.scrollLeft));i.scrollbars.setScrollLeft(r.scrollLeft);i.scroller.scrollLeft=r.scrollLeft;L(t)}if(e.scrollToPos){var n=Nr(t,tt(r,e.scrollToPos.from),tt(r,e.scrollToPos.to),e.scrollToPos.margin);e.scrollToPos.isCursor&&t.state.focused&&xr(t,n)}var o=e.maybeHiddenMarkers,s=e.maybeUnhiddenMarkers;if(o)for(var a=0;a<o.length;++a)o[a].lines.length||ga(o[a],"hide");if(s)for(var a=0;a<s.length;++a)s[a].lines.length&&ga(s[a],"unhide");i.wrapper.offsetHeight&&(r.scrollTop=t.display.scroller.scrollTop);e.changeObjs&&ga(t,"changes",t,e.changeObjs)}function fi(e,t){if(e.curOp)return t();ni(e);try{return t()}finally{si(e)}}function hi(e,t){return function(){if(e.curOp)return t.apply(e,arguments);ni(e);try{return t.apply(e,arguments)}finally{si(e)}}}function Ei(e){return function(){if(this.curOp)return e.apply(this,arguments);ni(this);try{return e.apply(this,arguments)}finally{si(this)}}}function mi(e){return function(){var t=this.cm;if(!t||t.curOp)return e.apply(this,arguments);ni(t);try{return e.apply(this,arguments)}finally{si(t)}}}function gi(e,t,i){this.line=t;this.rest=sn(t);this.size=this.rest?Hn(No(this.rest))-i+1:1;this.node=this.text=null;this.hidden=un(e,t)}function vi(e,t,i){for(var r,n=[],o=t;i>o;o=r){var s=new gi(e.doc,Bn(e.doc,o),o);r=o+s.size;n.push(s)}return n}function xi(e,t,i,r){null==t&&(t=e.doc.first);null==i&&(i=e.doc.first+e.doc.size);r||(r=0);var n=e.display;r&&i<n.viewTo&&(null==n.updateLineNumbers||n.updateLineNumbers>t)&&(n.updateLineNumbers=t);e.curOp.viewChanged=!0;if(t>=n.viewTo)Ts&&an(e.doc,t)<n.viewTo&&Li(e);else if(i<=n.viewFrom)if(Ts&&ln(e.doc,i+r)>n.viewFrom)Li(e);else{n.viewFrom+=r;n.viewTo+=r}else if(t<=n.viewFrom&&i>=n.viewTo)Li(e);else if(t<=n.viewFrom){var o=Ii(e,i,i+r,1);if(o){n.view=n.view.slice(o.index);n.viewFrom=o.lineN;n.viewTo+=r}else Li(e)}else if(i>=n.viewTo){var o=Ii(e,t,t,-1);if(o){n.view=n.view.slice(0,o.index);n.viewTo=o.lineN}else Li(e)}else{var s=Ii(e,t,t,-1),a=Ii(e,i,i+r,1);if(s&&a){n.view=n.view.slice(0,s.index).concat(vi(e,s.lineN,a.lineN)).concat(n.view.slice(a.index));n.viewTo+=r}else Li(e)}var l=n.externalMeasured;l&&(i<l.lineN?l.lineN+=r:t<l.lineN+l.size&&(n.externalMeasured=null))}function Ni(e,t,i){e.curOp.viewChanged=!0;var r=e.display,n=e.display.externalMeasured;n&&t>=n.lineN&&t<n.lineN+n.size&&(r.externalMeasured=null);if(!(t<r.viewFrom||t>=r.viewTo)){var o=r.view[Ti(e,t)];if(null!=o.node){var s=o.changes||(o.changes=[]);-1==Lo(s,i)&&s.push(i)}}}function Li(e){e.display.viewFrom=e.display.viewTo=e.doc.first;e.display.view=[];e.display.viewOffset=0}function Ti(e,t){if(t>=e.display.viewTo)return null;t-=e.display.viewFrom;if(0>t)return null;for(var i=e.display.view,r=0;r<i.length;r++){t-=i[r].size;if(0>t)return r}}function Ii(e,t,i,r){var n,o=Ti(e,t),s=e.display.view;if(!Ts||i==e.doc.first+e.doc.size)return{index:o,lineN:i};for(var a=0,l=e.display.viewFrom;o>a;a++)l+=s[a].size;if(l!=t){if(r>0){if(o==s.length-1)return null;n=l+s[o].size-t;o++}else n=l-t;t+=n;i+=n}for(;an(e.doc,i)!=i;){if(o==(0>r?0:s.length-1))return null;i+=r*s[o-(0>r?1:0)].size;o+=r}return{index:o,lineN:i}}function yi(e,t,i){var r=e.display,n=r.view;if(0==n.length||t>=r.viewTo||i<=r.viewFrom){r.view=vi(e,t,i);r.viewFrom=t}else{r.viewFrom>t?r.view=vi(e,t,r.viewFrom).concat(r.view):r.viewFrom<t&&(r.view=r.view.slice(Ti(e,t)));r.viewFrom=t;r.viewTo<i?r.view=r.view.concat(vi(e,r.viewTo,i)):r.viewTo>i&&(r.view=r.view.slice(0,Ti(e,i)))}r.viewTo=i}function Ai(e){for(var t=e.display.view,i=0,r=0;r<t.length;r++){var n=t[r];n.hidden||n.node&&!n.changes||++i}return i}function Si(e){e.display.pollingFast||e.display.poll.set(e.options.pollInterval,function(){Ri(e);e.state.focused&&Si(e)})}function Ci(e){function t(){var r=Ri(e);if(r||i){e.display.pollingFast=!1;Si(e)}else{i=!0;e.display.poll.set(60,t)}}var i=!1;e.display.pollingFast=!0;e.display.poll.set(20,t)}function Ri(e){var t=e.display.input,i=e.display.prevInput,r=e.doc;if(!e.state.focused||Ba(t)&&!i||Di(e)||e.options.disableInput||e.state.keySeq)return!1;if(e.state.pasteIncoming&&e.state.fakedLastChar){t.value=t.value.substring(0,t.value.length-1);e.state.fakedLastChar=!1}var n=t.value;if(n==i&&!e.somethingSelected())return!1;if(ns&&os>=9&&e.display.inputHasSelection===n||ms&&/[\uf700-\uf7ff]/.test(n)){bi(e);return!1}var o=!e.curOp;o&&ni(e);e.display.shift=!1;8203!=n.charCodeAt(0)||r.sel!=e.display.selForContextMenu||i||(i="");for(var s=0,a=Math.min(i.length,n.length);a>s&&i.charCodeAt(s)==n.charCodeAt(s);)++s;var l=n.slice(s),u=Ga(l),p=null;e.state.pasteIncoming&&r.sel.ranges.length>1&&(Ps&&Ps.join("\n")==l?p=r.sel.ranges.length%Ps.length==0&&To(Ps,Ga):u.length==r.sel.ranges.length&&(p=To(u,function(e){return[e]})));for(var c=r.sel.ranges.length-1;c>=0;c--){var d=r.sel.ranges[c],f=d.from(),h=d.to();s<i.length?f=Is(f.line,f.ch-(i.length-s)):e.state.overwrite&&d.empty()&&!e.state.pasteIncoming&&(h=Is(h.line,Math.min(Bn(r,h.line).text.length,h.ch+No(u).length)));var E=e.curOp.updateInput,m={from:f,to:h,text:p?p[c%p.length]:u,origin:e.state.pasteIncoming?"paste":e.state.cutIncoming?"cut":"+input"};dr(e.doc,m);po(e,"inputRead",e,m);if(l&&!e.state.pasteIncoming&&e.options.electricChars&&e.options.smartIndent&&d.head.ch<100&&(!c||r.sel.ranges[c-1].head.line!=d.head.line)){var g=e.getModeAt(d.head),v=Bs(m);if(g.electricChars){for(var x=0;x<g.electricChars.length;x++)if(l.indexOf(g.electricChars.charAt(x))>-1){Sr(e,v.line,"smart");break}}else g.electricInput&&g.electricInput.test(Bn(r,v.line).text.slice(0,v.ch))&&Sr(e,v.line,"smart")}}yr(e);e.curOp.updateInput=E;e.curOp.typing=!0;n.length>1e3||n.indexOf("\n")>-1?t.value=e.display.prevInput="":e.display.prevInput=n;o&&si(e);e.state.pasteIncoming=e.state.cutIncoming=!1;return!0}function bi(e,t){if(!e.display.contextMenuPending){var i,r,n=e.doc;if(e.somethingSelected()){e.display.prevInput="";var o=n.sel.primary();i=Ua&&(o.to().line-o.from().line>100||(r=e.getSelection()).length>1e3);var s=i?"-":r||e.getSelection();e.display.input.value=s;e.state.focused&&Sa(e.display.input);ns&&os>=9&&(e.display.inputHasSelection=s)}else if(!t){e.display.prevInput=e.display.input.value="";ns&&os>=9&&(e.display.inputHasSelection=null)}e.display.inaccurateSelection=i}}function Oi(e){"nocursor"==e.options.readOnly||Es&&wo()==e.display.input||e.display.input.focus()}function Pi(e){if(!e.state.focused){Oi(e);rr(e)}}function Di(e){return e.options.readOnly||e.doc.cantEdit}function wi(e){function t(t){fo(e,t)||ha(t)}function i(t){if(e.somethingSelected()){Ps=e.getSelections();if(r.inaccurateSelection){r.prevInput="";r.inaccurateSelection=!1;r.input.value=Ps.join("\n");Sa(r.input)}}else{for(var i=[],n=[],o=0;o<e.doc.sel.ranges.length;o++){var s=e.doc.sel.ranges[o].head.line,a={anchor:Is(s,0),head:Is(s+1,0)};n.push(a);i.push(e.getRange(a.anchor,a.head))}if("cut"==t.type)e.setSelections(n,null,La);else{r.prevInput="";r.input.value=i.join("\n");Sa(r.input)}Ps=i}"cut"==t.type&&(e.state.cutIncoming=!0)}var r=e.display;Ea(r.scroller,"mousedown",hi(e,Gi));ns&&11>os?Ea(r.scroller,"dblclick",hi(e,function(t){if(!fo(e,t)){var i=ki(e,t);if(i&&!Hi(e,t)&&!Mi(e.display,t)){da(t);var r=e.findWordAt(i);st(e.doc,r.anchor,r.head)}}})):Ea(r.scroller,"dblclick",function(t){fo(e,t)||da(t)});Ea(r.lineSpace,"selectstart",function(e){Mi(r,e)||da(e)});Ns||Ea(r.scroller,"contextmenu",function(t){or(e,t)});Ea(r.scroller,"scroll",function(){if(r.scroller.clientHeight){qi(e,r.scroller.scrollTop);zi(e,r.scroller.scrollLeft,!0);ga(e,"scroll",e)}});Ea(r.scroller,"mousewheel",function(t){Xi(e,t)});Ea(r.scroller,"DOMMouseScroll",function(t){Xi(e,t)});Ea(r.wrapper,"scroll",function(){r.wrapper.scrollTop=r.wrapper.scrollLeft=0});Ea(r.input,"keyup",function(t){tr.call(e,t)});Ea(r.input,"input",function(){ns&&os>=9&&e.display.inputHasSelection&&(e.display.inputHasSelection=null);Ri(e)});Ea(r.input,"keydown",hi(e,Ji));Ea(r.input,"keypress",hi(e,ir));Ea(r.input,"focus",Ao(rr,e));Ea(r.input,"blur",Ao(nr,e));if(e.options.dragDrop){Ea(r.scroller,"dragstart",function(t){Wi(e,t)});Ea(r.scroller,"dragenter",t);Ea(r.scroller,"dragover",t);Ea(r.scroller,"drop",hi(e,ji))}Ea(r.scroller,"paste",function(t){if(!Mi(r,t)){e.state.pasteIncoming=!0;Oi(e);Ci(e)}});Ea(r.input,"paste",function(){if(ss&&!e.state.fakedLastChar&&!(new Date-e.state.lastMiddleDown<200)){var t=r.input.selectionStart,i=r.input.selectionEnd;r.input.value+="$";r.input.selectionEnd=i;r.input.selectionStart=t;e.state.fakedLastChar=!0}e.state.pasteIncoming=!0;Ci(e)});Ea(r.input,"cut",i);Ea(r.input,"copy",i);cs&&Ea(r.sizer,"mouseup",function(){wo()==r.input&&r.input.blur();Oi(e)})}function _i(e){var t=e.display;if(t.lastWrapHeight!=t.wrapper.clientHeight||t.lastWrapWidth!=t.wrapper.clientWidth){t.cachedCharWidth=t.cachedTextHeight=t.cachedPaddingH=null;t.scrollbarsClipped=!1;e.setSize()}}function Mi(e,t){for(var i=lo(t);i!=e.wrapper;i=i.parentNode)if(!i||1==i.nodeType&&"true"==i.getAttribute("cm-ignore-events")||i.parentNode==e.sizer&&i!=e.mover)return!0}function ki(e,t,i,r){var n=e.display;if(!i&&"true"==lo(t).getAttribute("not-content"))return null;var o,s,a=n.lineSpace.getBoundingClientRect();try{o=t.clientX-a.left;s=t.clientY-a.top}catch(t){return null}var l,u=ei(e,o,s);if(r&&1==u.xRel&&(l=Bn(e.doc,u.line).text).length==u.ch){var p=ya(l,l.length,e.options.tabSize)-l.length;u=Is(u.line,Math.max(0,Math.round((o-Ot(e.display).left)/ri(e.display))-p))}return u}function Gi(e){if(!fo(this,e)){var t=this,i=t.display;i.shift=e.shiftKey;if(Mi(i,e)){if(!ss){i.scroller.draggable=!1;setTimeout(function(){i.scroller.draggable=!0},100)}}else if(!Hi(t,e)){var r=ki(t,e);window.focus();switch(uo(e)){case 1:r?Bi(t,e,r):lo(e)==i.scroller&&da(e);break;case 2:ss&&(t.state.lastMiddleDown=+new Date);r&&st(t.doc,r);setTimeout(Ao(Oi,t),20);da(e);break;case 3:Ns&&or(t,e)}}}}function Bi(e,t,i){setTimeout(Ao(Pi,e),0);var r,n=+new Date;if(Cs&&Cs.time>n-400&&0==ys(Cs.pos,i))r="triple";else if(Ss&&Ss.time>n-400&&0==ys(Ss.pos,i)){r="double";Cs={time:n,pos:i}}else{r="single";Ss={time:n,pos:i}}var o,s=e.doc.sel,a=ms?t.metaKey:t.ctrlKey;e.options.dragDrop&&ka&&!Di(e)&&"single"==r&&(o=s.contains(i))>-1&&!s.ranges[o].empty()?Ui(e,t,i,a):Vi(e,t,i,r,a)}function Ui(e,t,i,r){var n=e.display,o=hi(e,function(s){ss&&(n.scroller.draggable=!1);e.state.draggingText=!1;ma(document,"mouseup",o);ma(n.scroller,"drop",o);if(Math.abs(t.clientX-s.clientX)+Math.abs(t.clientY-s.clientY)<10){da(s);r||st(e.doc,i);Oi(e);ns&&9==os&&setTimeout(function(){document.body.focus();Oi(e)},20)}});ss&&(n.scroller.draggable=!0);e.state.draggingText=o;n.scroller.dragDrop&&n.scroller.dragDrop();Ea(document,"mouseup",o);Ea(n.scroller,"drop",o)}function Vi(e,t,i,r,n){function o(t){if(0!=ys(m,t)){m=t;if("rect"==r){for(var n=[],o=e.options.tabSize,s=ya(Bn(u,i.line).text,i.ch,o),a=ya(Bn(u,t.line).text,t.ch,o),l=Math.min(s,a),f=Math.max(s,a),h=Math.min(i.line,t.line),E=Math.min(e.lastLine(),Math.max(i.line,t.line));E>=h;h++){var g=Bn(u,h).text,v=vo(g,l,o);l==f?n.push(new Q(Is(h,v),Is(h,v))):g.length>v&&n.push(new Q(Is(h,v),Is(h,vo(g,f,o))))}n.length||n.push(new Q(i,i));dt(u,Z(d.ranges.slice(0,c).concat(n),c),{origin:"*mouse",scroll:!1});e.scrollIntoView(t)}else{var x=p,N=x.anchor,L=t;if("single"!=r){if("double"==r)var T=e.findWordAt(t);else var T=new Q(Is(t.line,0),tt(u,Is(t.line+1,0)));if(ys(T.anchor,N)>0){L=T.head;N=K(x.from(),T.anchor)}else{L=T.anchor;N=Y(x.to(),T.head)}}var n=d.ranges.slice(0);n[c]=new Q(tt(u,N),L);dt(u,Z(n,c),Ta)}}}function s(t){var i=++v,n=ki(e,t,!0,"rect"==r);if(n)if(0!=ys(n,m)){Pi(e);o(n);var a=N(l,u);(n.line>=a.to||n.line<a.from)&&setTimeout(hi(e,function(){v==i&&s(t)}),150)}else{var p=t.clientY<g.top?-20:t.clientY>g.bottom?20:0;p&&setTimeout(hi(e,function(){if(v==i){l.scroller.scrollTop+=p;s(t)}}),50)}}function a(t){v=1/0;da(t);Oi(e);ma(document,"mousemove",x);ma(document,"mouseup",L);u.history.lastSelOrigin=null}var l=e.display,u=e.doc;da(t);var p,c,d=u.sel,f=d.ranges;if(n&&!t.shiftKey){c=u.sel.contains(i);p=c>-1?f[c]:new Q(i,i)}else p=u.sel.primary();if(t.altKey){r="rect";n||(p=new Q(i,i));i=ki(e,t,!0,!0);c=-1}else if("double"==r){var h=e.findWordAt(i);p=e.display.shift||u.extend?ot(u,p,h.anchor,h.head):h}else if("triple"==r){var E=new Q(Is(i.line,0),tt(u,Is(i.line+1,0)));p=e.display.shift||u.extend?ot(u,p,E.anchor,E.head):E}else p=ot(u,p,i);if(n)if(-1==c){c=f.length;dt(u,Z(f.concat([p]),c),{scroll:!1,origin:"*mouse"})}else if(f.length>1&&f[c].empty()&&"single"==r){dt(u,Z(f.slice(0,c).concat(f.slice(c+1)),0));d=u.sel}else lt(u,c,p,Ta);else{c=0;dt(u,new $([p],0),Ta);d=u.sel}var m=i,g=l.wrapper.getBoundingClientRect(),v=0,x=hi(e,function(e){uo(e)?s(e):a(e)}),L=hi(e,a);Ea(document,"mousemove",x);Ea(document,"mouseup",L)}function Fi(e,t,i,r,n){try{var o=t.clientX,s=t.clientY}catch(t){return!1}if(o>=Math.floor(e.display.gutters.getBoundingClientRect().right))return!1;r&&da(t);var a=e.display,l=a.lineDiv.getBoundingClientRect();if(s>l.bottom||!Eo(e,i))return ao(t);s-=l.top-a.viewOffset;for(var u=0;u<e.options.gutters.length;++u){var p=a.gutters.childNodes[u];if(p&&p.getBoundingClientRect().right>=o){var c=jn(e.doc,s),d=e.options.gutters[u];n(e,i,e,c,d,t);return ao(t)}}}function Hi(e,t){return Fi(e,t,"gutterClick",!0,po)}function ji(e){var t=this;if(!fo(t,e)&&!Mi(t.display,e)){da(e);ns&&(Ds=+new Date);var i=ki(t,e,!0),r=e.dataTransfer.files;if(i&&!Di(t))if(r&&r.length&&window.FileReader&&window.File)for(var n=r.length,o=Array(n),s=0,a=function(e,r){var a=new FileReader;a.onload=hi(t,function(){o[r]=a.result;if(++s==n){i=tt(t.doc,i);var e={from:i,to:i,text:Ga(o.join("\n")),origin:"paste"};dr(t.doc,e);ct(t.doc,J(i,Bs(e)))}});a.readAsText(e)},l=0;n>l;++l)a(r[l],l);else{if(t.state.draggingText&&t.doc.sel.contains(i)>-1){t.state.draggingText(e);setTimeout(Ao(Oi,t),20);return}try{var o=e.dataTransfer.getData("Text");if(o){if(t.state.draggingText&&!(ms?e.metaKey:e.ctrlKey))var u=t.listSelections();ft(t.doc,J(i,i));if(u)for(var l=0;l<u.length;++l)vr(t.doc,"",u[l].anchor,u[l].head,"drag");t.replaceSelection(o,"around","paste");Oi(t)}}catch(e){}}}}function Wi(e,t){if(ns&&(!e.state.draggingText||+new Date-Ds<100))ha(t);else if(!fo(e,t)&&!Mi(e.display,t)){t.dataTransfer.setData("Text",e.getSelection());if(t.dataTransfer.setDragImage&&!ps){var i=bo("img",null,null,"position: fixed; left: 0; top: 0;");i.src="data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";if(us){i.width=i.height=1;e.display.wrapper.appendChild(i);i._top=i.offsetTop}t.dataTransfer.setDragImage(i,0,0);us&&i.parentNode.removeChild(i)}}}function qi(e,t){if(!(Math.abs(e.doc.scrollTop-t)<2)){e.doc.scrollTop=t;ts||b(e,{top:t});e.display.scroller.scrollTop!=t&&(e.display.scroller.scrollTop=t);e.display.scrollbars.setScrollTop(t);ts&&b(e);yt(e,100)}}function zi(e,t,i){if(!(i?t==e.doc.scrollLeft:Math.abs(e.doc.scrollLeft-t)<2)){t=Math.min(t,e.display.scroller.scrollWidth-e.display.scroller.clientWidth);e.doc.scrollLeft=t;L(e);e.display.scroller.scrollLeft!=t&&(e.display.scroller.scrollLeft=t);e.display.scrollbars.setScrollLeft(t)}}function Xi(e,t){var i=Ms(t),r=i.x,n=i.y,o=e.display,s=o.scroller;if(r&&s.scrollWidth>s.clientWidth||n&&s.scrollHeight>s.clientHeight){if(n&&ms&&ss)e:for(var a=t.target,l=o.view;a!=s;a=a.parentNode)for(var u=0;u<l.length;u++)if(l[u].node==a){e.display.currentWheelTarget=a;break e}if(!r||ts||us||null==_s){if(n&&null!=_s){var p=n*_s,c=e.doc.scrollTop,d=c+o.wrapper.clientHeight;0>p?c=Math.max(0,c+p-50):d=Math.min(e.doc.height,d+p+50);b(e,{top:c,bottom:d})}if(20>ws)if(null==o.wheelStartX){o.wheelStartX=s.scrollLeft;o.wheelStartY=s.scrollTop;o.wheelDX=r;o.wheelDY=n;setTimeout(function(){if(null!=o.wheelStartX){var e=s.scrollLeft-o.wheelStartX,t=s.scrollTop-o.wheelStartY,i=t&&o.wheelDY&&t/o.wheelDY||e&&o.wheelDX&&e/o.wheelDX;o.wheelStartX=o.wheelStartY=null;if(i){_s=(_s*ws+i)/(ws+1);++ws}}},200)}else{o.wheelDX+=r;o.wheelDY+=n}}else{n&&qi(e,Math.max(0,Math.min(s.scrollTop+n*_s,s.scrollHeight-s.clientHeight)));zi(e,Math.max(0,Math.min(s.scrollLeft+r*_s,s.scrollWidth-s.clientWidth)));da(t);o.wheelStartX=null}}}function Yi(e,t,i){if("string"==typeof t){t=Ks[t];if(!t)return!1}e.display.pollingFast&&Ri(e)&&(e.display.pollingFast=!1);var r=e.display.shift,n=!1;try{Di(e)&&(e.state.suppressEdits=!0);i&&(e.display.shift=!1);n=t(e)!=Na}finally{e.display.shift=r;e.state.suppressEdits=!1}return n}function Ki(e,t,i){for(var r=0;r<e.state.keyMaps.length;r++){var n=Qs(t,e.state.keyMaps[r],i,e);if(n)return n}return e.options.extraKeys&&Qs(t,e.options.extraKeys,i,e)||Qs(t,e.options.keyMap,i,e)}function $i(e,t,i,r){var n=e.state.keySeq;if(n){if(Zs(t))return"handled";ks.set(50,function(){if(e.state.keySeq==n){e.state.keySeq=null;bi(e)}});t=n+" "+t}var o=Ki(e,t,r);"multi"==o&&(e.state.keySeq=t);"handled"==o&&po(e,"keyHandled",e,t,i);if("handled"==o||"multi"==o){da(i);It(e)}if(n&&!o&&/\'$/.test(t)){da(i);return!0}return!!o}function Qi(e,t){var i=Js(t,!0);return i?t.shiftKey&&!e.state.keySeq?$i(e,"Shift-"+i,t,function(t){return Yi(e,t,!0)})||$i(e,i,t,function(t){return("string"==typeof t?/^go[A-Z]/.test(t):t.motion)?Yi(e,t):void 0}):$i(e,i,t,function(t){return Yi(e,t)}):!1}function Zi(e,t,i){return $i(e,"'"+i+"'",t,function(t){return Yi(e,t,!0)})}function Ji(e){var t=this;Pi(t);if(!fo(t,e)){ns&&11>os&&27==e.keyCode&&(e.returnValue=!1);var i=e.keyCode;t.display.shift=16==i||e.shiftKey;var r=Qi(t,e);if(us){Gs=r?i:null;!r&&88==i&&!Ua&&(ms?e.metaKey:e.ctrlKey)&&t.replaceSelection("",null,"cut")}18!=i||/\bCodeMirror-crosshair\b/.test(t.display.lineDiv.className)||er(t)}}function er(e){function t(e){if(18==e.keyCode||!e.altKey){wa(i,"CodeMirror-crosshair");ma(document,"keyup",t);ma(document,"mouseover",t)}}var i=e.display.lineDiv;_a(i,"CodeMirror-crosshair");Ea(document,"keyup",t);Ea(document,"mouseover",t)}function tr(e){16==e.keyCode&&(this.doc.sel.shift=!1);fo(this,e)}function ir(e){var t=this;if(!(fo(t,e)||e.ctrlKey&&!e.altKey||ms&&e.metaKey)){var i=e.keyCode,r=e.charCode;if(us&&i==Gs){Gs=null;da(e)}else if(!(us&&(!e.which||e.which<10)||cs)||!Qi(t,e)){var n=String.fromCharCode(null==r?i:r);if(!Zi(t,e,n)){ns&&os>=9&&(t.display.inputHasSelection=null);Ci(t)}}}}function rr(e){if("nocursor"!=e.options.readOnly){if(!e.state.focused){ga(e,"focus",e);e.state.focused=!0;_a(e.display.wrapper,"CodeMirror-focused");if(!e.curOp&&e.display.selForContextMenu!=e.doc.sel){bi(e);ss&&setTimeout(Ao(bi,e,!0),0)}}Si(e);It(e)}}function nr(e){if(e.state.focused){ga(e,"blur",e);e.state.focused=!1;wa(e.display.wrapper,"CodeMirror-focused")}clearInterval(e.display.blinker);setTimeout(function(){e.state.focused||(e.display.shift=!1)},150)}function or(e,t){function i(){if(null!=n.input.selectionStart){var t=e.somethingSelected(),i=n.input.value=""+(t?n.input.value:"");n.prevInput=t?"":"";n.input.selectionStart=1;n.input.selectionEnd=i.length;n.selForContextMenu=e.doc.sel}}function r(){n.contextMenuPending=!1;n.inputDiv.style.position="relative";n.input.style.cssText=l;ns&&9>os&&n.scrollbars.setScrollTop(n.scroller.scrollTop=s);Si(e);if(null!=n.input.selectionStart){(!ns||ns&&9>os)&&i();var t=0,r=function(){n.selForContextMenu==e.doc.sel&&0==n.input.selectionStart?hi(e,Ks.selectAll)(e):t++<10?n.detectingSelectAll=setTimeout(r,500):bi(e)};n.detectingSelectAll=setTimeout(r,200)}}if(!fo(e,t,"contextmenu")){var n=e.display;if(!Mi(n,t)&&!sr(e,t)){var o=ki(e,t),s=n.scroller.scrollTop;if(o&&!us){var a=e.options.resetSelectionOnContextMenu;a&&-1==e.doc.sel.contains(o)&&hi(e,dt)(e.doc,J(o),La);var l=n.input.style.cssText;n.inputDiv.style.position="absolute";n.input.style.cssText="position: fixed; width: 30px; height: 30px; top: "+(t.clientY-5)+"px; left: "+(t.clientX-5)+"px; z-index: 1000; background: "+(ns?"rgba(255, 255, 255, .05)":"transparent")+"; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);";if(ss)var u=window.scrollY;Oi(e);ss&&window.scrollTo(null,u);bi(e);e.somethingSelected()||(n.input.value=n.prevInput=" ");n.contextMenuPending=!0;n.selForContextMenu=e.doc.sel;clearTimeout(n.detectingSelectAll);ns&&os>=9&&i();if(Ns){ha(t);var p=function(){ma(window,"mouseup",p);setTimeout(r,20)};Ea(window,"mouseup",p)}else setTimeout(r,50)}}}}function sr(e,t){return Eo(e,"gutterContextMenu")?Fi(e,t,"gutterContextMenu",!1,ga):!1}function ar(e,t){if(ys(e,t.from)<0)return e;if(ys(e,t.to)<=0)return Bs(t);var i=e.line+t.text.length-(t.to.line-t.from.line)-1,r=e.ch;e.line==t.to.line&&(r+=Bs(t).ch-t.to.ch);return Is(i,r)}function lr(e,t){for(var i=[],r=0;r<e.sel.ranges.length;r++){var n=e.sel.ranges[r];i.push(new Q(ar(n.anchor,t),ar(n.head,t)))}return Z(i,e.sel.primIndex)}function ur(e,t,i){return e.line==t.line?Is(i.line,e.ch-t.ch+i.ch):Is(i.line+(e.line-t.line),e.ch)}function pr(e,t,i){for(var r=[],n=Is(e.first,0),o=n,s=0;s<t.length;s++){var a=t[s],l=ur(a.from,n,o),u=ur(Bs(a),n,o);n=a.to;o=u;if("around"==i){var p=e.sel.ranges[s],c=ys(p.head,p.anchor)<0;r[s]=new Q(c?u:l,c?l:u)}else r[s]=new Q(l,l)}return new $(r,e.sel.primIndex)}function cr(e,t,i){var r={canceled:!1,from:t.from,to:t.to,text:t.text,origin:t.origin,cancel:function(){this.canceled=!0}};i&&(r.update=function(t,i,r,n){t&&(this.from=tt(e,t));i&&(this.to=tt(e,i));r&&(this.text=r);void 0!==n&&(this.origin=n)});ga(e,"beforeChange",e,r);e.cm&&ga(e.cm,"beforeChange",e.cm,r);return r.canceled?null:{from:r.from,to:r.to,text:r.text,origin:r.origin}}function dr(e,t,i){if(e.cm){if(!e.cm.curOp)return hi(e.cm,dr)(e,t,i);if(e.cm.state.suppressEdits)return}if(Eo(e,"beforeChange")||e.cm&&Eo(e.cm,"beforeChange")){t=cr(e,t,!0);if(!t)return}var r=Ls&&!i&&Yr(e,t.from,t.to);if(r)for(var n=r.length-1;n>=0;--n)fr(e,{from:r[n].from,to:r[n].to,text:n?[""]:t.text});else fr(e,t)}function fr(e,t){if(1!=t.text.length||""!=t.text[0]||0!=ys(t.from,t.to)){var i=lr(e,t);$n(e,t,i,e.cm?e.cm.curOp.id:0/0);mr(e,t,i,qr(e,t));var r=[];kn(e,function(e,i){if(!i&&-1==Lo(r,e.history)){so(e.history,t);r.push(e.history)}mr(e,t,null,qr(e,t))})}}function hr(e,t,i){if(!e.cm||!e.cm.state.suppressEdits){for(var r,n=e.history,o=e.sel,s="undo"==t?n.done:n.undone,a="undo"==t?n.undone:n.done,l=0;l<s.length;l++){r=s[l];if(i?r.ranges&&!r.equals(e.sel):!r.ranges)break}if(l!=s.length){n.lastOrigin=n.lastSelOrigin=null;for(;;){r=s.pop();if(!r.ranges)break;Jn(r,a);if(i&&!r.equals(e.sel)){dt(e,r,{clearRedo:!1});return}o=r}var u=[];Jn(o,a);a.push({changes:u,generation:n.generation});n.generation=r.generation||++n.maxGeneration;for(var p=Eo(e,"beforeChange")||e.cm&&Eo(e.cm,"beforeChange"),l=r.changes.length-1;l>=0;--l){var c=r.changes[l];c.origin=t;if(p&&!cr(e,c,!1)){s.length=0;return}u.push(Xn(e,c));var d=l?lr(e,c):No(s);mr(e,c,d,Xr(e,c));!l&&e.cm&&e.cm.scrollIntoView({from:c.from,to:Bs(c)});var f=[];kn(e,function(e,t){if(!t&&-1==Lo(f,e.history)){so(e.history,c);f.push(e.history)}mr(e,c,null,Xr(e,c))})}}}}function Er(e,t){if(0!=t){e.first+=t;e.sel=new $(To(e.sel.ranges,function(e){return new Q(Is(e.anchor.line+t,e.anchor.ch),Is(e.head.line+t,e.head.ch))}),e.sel.primIndex);if(e.cm){xi(e.cm,e.first,e.first-t,t);for(var i=e.cm.display,r=i.viewFrom;r<i.viewTo;r++)Ni(e.cm,r,"gutter")}}}function mr(e,t,i,r){if(e.cm&&!e.cm.curOp)return hi(e.cm,mr)(e,t,i,r);if(t.to.line<e.first)Er(e,t.text.length-1-(t.to.line-t.from.line));else if(!(t.from.line>e.lastLine())){if(t.from.line<e.first){var n=t.text.length-1-(e.first-t.from.line);Er(e,n);t={from:Is(e.first,0),to:Is(t.to.line+n,t.to.ch),text:[No(t.text)],origin:t.origin}}var o=e.lastLine();t.to.line>o&&(t={from:t.from,to:Is(o,Bn(e,o).text.length),text:[t.text[0]],origin:t.origin});t.removed=Un(e,t.from,t.to);i||(i=lr(e,t));e.cm?gr(e.cm,t,r):wn(e,t,r);ft(e,i,La)}}function gr(e,t,i){var r=e.doc,n=e.display,s=t.from,a=t.to,l=!1,u=s.line;if(!e.options.lineWrapping){u=Hn(on(Bn(r,s.line)));r.iter(u,a.line+1,function(e){if(e==n.maxLine){l=!0;return!0}})}r.sel.contains(t.from,t.to)>-1&&ho(e);wn(r,t,i,o(e));if(!e.options.lineWrapping){r.iter(u,s.line+t.text.length,function(e){var t=c(e);if(t>n.maxLineLength){n.maxLine=e;n.maxLineLength=t;n.maxLineChanged=!0;l=!1}});l&&(e.curOp.updateMaxLine=!0)}r.frontier=Math.min(r.frontier,s.line);yt(e,400);var p=t.text.length-(a.line-s.line)-1;t.full?xi(e):s.line!=a.line||1!=t.text.length||Dn(e.doc,t)?xi(e,s.line,a.line+1,p):Ni(e,s.line,"text");var d=Eo(e,"changes"),f=Eo(e,"change");if(f||d){var h={from:s,to:a,text:t.text,removed:t.removed,origin:t.origin};f&&po(e,"change",e,h);d&&(e.curOp.changeObjs||(e.curOp.changeObjs=[])).push(h)}e.display.selForContextMenu=null}function vr(e,t,i,r,n){r||(r=i);if(ys(r,i)<0){var o=r;r=i;i=o}"string"==typeof t&&(t=Ga(t));dr(e,{from:i,to:r,text:t,origin:n})}function xr(e,t){if(!fo(e,"scrollCursorIntoView")){var i=e.display,r=i.sizer.getBoundingClientRect(),n=null;t.top+r.top<0?n=!0:t.bottom+r.top>(window.innerHeight||document.documentElement.clientHeight)&&(n=!1);if(null!=n&&!fs){var o=bo("div","",null,"position: absolute; top: "+(t.top-i.viewOffset-Rt(e.display))+"px; height: "+(t.bottom-t.top+Pt(e)+i.barHeight)+"px; left: "+t.left+"px; width: 2px;");e.display.lineSpace.appendChild(o);o.scrollIntoView(n);e.display.lineSpace.removeChild(o)}}}function Nr(e,t,i,r){null==r&&(r=0);for(var n=0;5>n;n++){var o=!1,s=Qt(e,t),a=i&&i!=t?Qt(e,i):s,l=Tr(e,Math.min(s.left,a.left),Math.min(s.top,a.top)-r,Math.max(s.left,a.left),Math.max(s.bottom,a.bottom)+r),u=e.doc.scrollTop,p=e.doc.scrollLeft;if(null!=l.scrollTop){qi(e,l.scrollTop);Math.abs(e.doc.scrollTop-u)>1&&(o=!0)}if(null!=l.scrollLeft){zi(e,l.scrollLeft);Math.abs(e.doc.scrollLeft-p)>1&&(o=!0)}if(!o)break}return s}function Lr(e,t,i,r,n){var o=Tr(e,t,i,r,n);null!=o.scrollTop&&qi(e,o.scrollTop);null!=o.scrollLeft&&zi(e,o.scrollLeft)}function Tr(e,t,i,r,n){var o=e.display,s=ii(e.display);0>i&&(i=0);var a=e.curOp&&null!=e.curOp.scrollTop?e.curOp.scrollTop:o.scroller.scrollTop,l=wt(e),u={};n-i>l&&(n=i+l);var p=e.doc.height+bt(o),c=s>i,d=n>p-s;if(a>i)u.scrollTop=c?0:i;else if(n>a+l){var f=Math.min(i,(d?p:n)-l);f!=a&&(u.scrollTop=f)}var h=e.curOp&&null!=e.curOp.scrollLeft?e.curOp.scrollLeft:o.scroller.scrollLeft,E=Dt(e)-(e.options.fixedGutter?o.gutters.offsetWidth:0),m=r-t>E;m&&(r=t+E);10>t?u.scrollLeft=0:h>t?u.scrollLeft=Math.max(0,t-(m?0:10)):r>E+h-3&&(u.scrollLeft=r+(m?0:10)-E);return u}function Ir(e,t,i){(null!=t||null!=i)&&Ar(e);null!=t&&(e.curOp.scrollLeft=(null==e.curOp.scrollLeft?e.doc.scrollLeft:e.curOp.scrollLeft)+t);null!=i&&(e.curOp.scrollTop=(null==e.curOp.scrollTop?e.doc.scrollTop:e.curOp.scrollTop)+i)}function yr(e){Ar(e);var t=e.getCursor(),i=t,r=t;if(!e.options.lineWrapping){i=t.ch?Is(t.line,t.ch-1):t;r=Is(t.line,t.ch+1)}e.curOp.scrollToPos={from:i,to:r,margin:e.options.cursorScrollMargin,isCursor:!0}}function Ar(e){var t=e.curOp.scrollToPos;if(t){e.curOp.scrollToPos=null;var i=Zt(e,t.from),r=Zt(e,t.to),n=Tr(e,Math.min(i.left,r.left),Math.min(i.top,r.top)-t.margin,Math.max(i.right,r.right),Math.max(i.bottom,r.bottom)+t.margin);e.scrollTo(n.scrollLeft,n.scrollTop)}}function Sr(e,t,i,r){var n,o=e.doc;null==i&&(i="add");"smart"==i&&(o.mode.indent?n=Ct(e,t):i="prev");var s=e.options.tabSize,a=Bn(o,t),l=ya(a.text,null,s);a.stateAfter&&(a.stateAfter=null);var u,p=a.text.match(/^\s*/)[0];if(r||/\S/.test(a.text)){if("smart"==i){u=o.mode.indent(n,a.text.slice(p.length),a.text);if(u==Na||u>150){if(!r)return;i="prev"}}}else{u=0;i="not"}"prev"==i?u=t>o.first?ya(Bn(o,t-1).text,null,s):0:"add"==i?u=l+e.options.indentUnit:"subtract"==i?u=l-e.options.indentUnit:"number"==typeof i&&(u=l+i);u=Math.max(0,u);var c="",d=0;if(e.options.indentWithTabs)for(var f=Math.floor(u/s);f;--f){d+=s;c+=" "}u>d&&(c+=xo(u-d));if(c!=p)vr(o,c,Is(t,0),Is(t,p.length),"+input");else for(var f=0;f<o.sel.ranges.length;f++){var h=o.sel.ranges[f];if(h.head.line==t&&h.head.ch<p.length){var d=Is(t,p.length);lt(o,f,new Q(d,d));break}}a.stateAfter=null}function Cr(e,t,i,r){var n=t,o=t;"number"==typeof t?o=Bn(e,et(e,t)):n=Hn(t);if(null==n)return null;r(o,n)&&e.cm&&Ni(e.cm,n,i);return o}function Rr(e,t){for(var i=e.doc.sel.ranges,r=[],n=0;n<i.length;n++){for(var o=t(i[n]);r.length&&ys(o.from,No(r).to)<=0;){var s=r.pop();if(ys(s.from,o.from)<0){o.from=s.from;break}}r.push(o)}fi(e,function(){for(var t=r.length-1;t>=0;t--)vr(e.doc,"",r[t].from,r[t].to,"+delete");yr(e)})}function br(e,t,i,r,n){function o(){var t=a+i;if(t<e.first||t>=e.first+e.size)return c=!1;
a=t;return p=Bn(e,t)}function s(e){var t=(n?Jo:es)(p,l,i,!0);if(null==t){if(e||!o())return c=!1;l=n?(0>i?zo:qo)(p):0>i?p.text.length:0}else l=t;return!0}var a=t.line,l=t.ch,u=i,p=Bn(e,a),c=!0;if("char"==r)s();else if("column"==r)s(!0);else if("word"==r||"group"==r)for(var d=null,f="group"==r,h=e.cm&&e.cm.getHelper(t,"wordChars"),E=!0;!(0>i)||s(!E);E=!1){var m=p.text.charAt(l)||"\n",g=So(m,h)?"w":f&&"\n"==m?"n":!f||/\s/.test(m)?null:"p";!f||E||g||(g="s");if(d&&d!=g){if(0>i){i=1;s()}break}g&&(d=g);if(i>0&&!s(!E))break}var v=gt(e,Is(a,l),u,!0);c||(v.hitSide=!0);return v}function Or(e,t,i,r){var n,o=e.doc,s=t.left;if("page"==r){var a=Math.min(e.display.wrapper.clientHeight,window.innerHeight||document.documentElement.clientHeight);n=t.top+i*(a-(0>i?1.5:.5)*ii(e.display))}else"line"==r&&(n=i>0?t.bottom+3:t.top-3);for(;;){var l=ei(e,s,n);if(!l.outside)break;if(0>i?0>=n:n>=o.height){l.hitSide=!0;break}n+=5*i}return l}function Pr(t,i,r,n){e.defaults[t]=i;r&&(Vs[t]=n?function(e,t,i){i!=Fs&&r(e,t,i)}:r)}function Dr(e){for(var t,i,r,n,o=e.split(/-(?!$)/),e=o[o.length-1],s=0;s<o.length-1;s++){var a=o[s];if(/^(cmd|meta|m)$/i.test(a))n=!0;else if(/^a(lt)?$/i.test(a))t=!0;else if(/^(c|ctrl|control)$/i.test(a))i=!0;else{if(!/^s(hift)$/i.test(a))throw new Error("Unrecognized modifier name: "+a);r=!0}}t&&(e="Alt-"+e);i&&(e="Ctrl-"+e);n&&(e="Cmd-"+e);r&&(e="Shift-"+e);return e}function wr(e){return"string"==typeof e?$s[e]:e}function _r(e,t,i,r,n){if(r&&r.shared)return Mr(e,t,i,r,n);if(e.cm&&!e.cm.curOp)return hi(e.cm,_r)(e,t,i,r,n);var o=new ta(e,n),s=ys(t,i);r&&yo(r,o,!1);if(s>0||0==s&&o.clearWhenEmpty!==!1)return o;if(o.replacedWith){o.collapsed=!0;o.widgetNode=bo("span",[o.replacedWith],"CodeMirror-widget");r.handleMouseEvents||o.widgetNode.setAttribute("cm-ignore-events","true");r.insertLeft&&(o.widgetNode.insertLeft=!0)}if(o.collapsed){if(nn(e,t.line,t,i,o)||t.line!=i.line&&nn(e,i.line,t,i,o))throw new Error("Inserting collapsed marker partially overlapping an existing one");Ts=!0}o.addToHistory&&$n(e,{from:t,to:i,origin:"markText"},e.sel,0/0);var a,l=t.line,u=e.cm;e.iter(l,i.line+1,function(e){u&&o.collapsed&&!u.options.lineWrapping&&on(e)==u.display.maxLine&&(a=!0);o.collapsed&&l!=t.line&&Fn(e,0);Hr(e,new Ur(o,l==t.line?t.ch:null,l==i.line?i.ch:null));++l});o.collapsed&&e.iter(t.line,i.line+1,function(t){un(e,t)&&Fn(t,0)});o.clearOnEnter&&Ea(o,"beforeCursorEnter",function(){o.clear()});if(o.readOnly){Ls=!0;(e.history.done.length||e.history.undone.length)&&e.clearHistory()}if(o.collapsed){o.id=++ia;o.atomic=!0}if(u){a&&(u.curOp.updateMaxLine=!0);if(o.collapsed)xi(u,t.line,i.line+1);else if(o.className||o.title||o.startStyle||o.endStyle||o.css)for(var p=t.line;p<=i.line;p++)Ni(u,p,"text");o.atomic&&Et(u.doc);po(u,"markerAdded",u,o)}return o}function Mr(e,t,i,r,n){r=yo(r);r.shared=!1;var o=[_r(e,t,i,r,n)],s=o[0],a=r.widgetNode;kn(e,function(e){a&&(r.widgetNode=a.cloneNode(!0));o.push(_r(e,tt(e,t),tt(e,i),r,n));for(var l=0;l<e.linked.length;++l)if(e.linked[l].isParent)return;s=No(o)});return new ra(o,s)}function kr(e){return e.findMarks(Is(e.first,0),e.clipPos(Is(e.lastLine())),function(e){return e.parent})}function Gr(e,t){for(var i=0;i<t.length;i++){var r=t[i],n=r.find(),o=e.clipPos(n.from),s=e.clipPos(n.to);if(ys(o,s)){var a=_r(e,o,s,r.primary,r.primary.type);r.markers.push(a);a.parent=r}}}function Br(e){for(var t=0;t<e.length;t++){var i=e[t],r=[i.primary.doc];kn(i.primary.doc,function(e){r.push(e)});for(var n=0;n<i.markers.length;n++){var o=i.markers[n];if(-1==Lo(r,o.doc)){o.parent=null;i.markers.splice(n--,1)}}}}function Ur(e,t,i){this.marker=e;this.from=t;this.to=i}function Vr(e,t){if(e)for(var i=0;i<e.length;++i){var r=e[i];if(r.marker==t)return r}}function Fr(e,t){for(var i,r=0;r<e.length;++r)e[r]!=t&&(i||(i=[])).push(e[r]);return i}function Hr(e,t){e.markedSpans=e.markedSpans?e.markedSpans.concat([t]):[t];t.marker.attachLine(e)}function jr(e,t,i){if(e)for(var r,n=0;n<e.length;++n){var o=e[n],s=o.marker,a=null==o.from||(s.inclusiveLeft?o.from<=t:o.from<t);if(a||o.from==t&&"bookmark"==s.type&&(!i||!o.marker.insertLeft)){var l=null==o.to||(s.inclusiveRight?o.to>=t:o.to>t);(r||(r=[])).push(new Ur(s,o.from,l?null:o.to))}}return r}function Wr(e,t,i){if(e)for(var r,n=0;n<e.length;++n){var o=e[n],s=o.marker,a=null==o.to||(s.inclusiveRight?o.to>=t:o.to>t);if(a||o.from==t&&"bookmark"==s.type&&(!i||o.marker.insertLeft)){var l=null==o.from||(s.inclusiveLeft?o.from<=t:o.from<t);(r||(r=[])).push(new Ur(s,l?null:o.from-t,null==o.to?null:o.to-t))}}return r}function qr(e,t){if(t.full)return null;var i=rt(e,t.from.line)&&Bn(e,t.from.line).markedSpans,r=rt(e,t.to.line)&&Bn(e,t.to.line).markedSpans;if(!i&&!r)return null;var n=t.from.ch,o=t.to.ch,s=0==ys(t.from,t.to),a=jr(i,n,s),l=Wr(r,o,s),u=1==t.text.length,p=No(t.text).length+(u?n:0);if(a)for(var c=0;c<a.length;++c){var d=a[c];if(null==d.to){var f=Vr(l,d.marker);f?u&&(d.to=null==f.to?null:f.to+p):d.to=n}}if(l)for(var c=0;c<l.length;++c){var d=l[c];null!=d.to&&(d.to+=p);if(null==d.from){var f=Vr(a,d.marker);if(!f){d.from=p;u&&(a||(a=[])).push(d)}}else{d.from+=p;u&&(a||(a=[])).push(d)}}a&&(a=zr(a));l&&l!=a&&(l=zr(l));var h=[a];if(!u){var E,m=t.text.length-2;if(m>0&&a)for(var c=0;c<a.length;++c)null==a[c].to&&(E||(E=[])).push(new Ur(a[c].marker,null,null));for(var c=0;m>c;++c)h.push(E);h.push(l)}return h}function zr(e){for(var t=0;t<e.length;++t){var i=e[t];null!=i.from&&i.from==i.to&&i.marker.clearWhenEmpty!==!1&&e.splice(t--,1)}return e.length?e:null}function Xr(e,t){var i=io(e,t),r=qr(e,t);if(!i)return r;if(!r)return i;for(var n=0;n<i.length;++n){var o=i[n],s=r[n];if(o&&s)e:for(var a=0;a<s.length;++a){for(var l=s[a],u=0;u<o.length;++u)if(o[u].marker==l.marker)continue e;o.push(l)}else s&&(i[n]=s)}return i}function Yr(e,t,i){var r=null;e.iter(t.line,i.line+1,function(e){if(e.markedSpans)for(var t=0;t<e.markedSpans.length;++t){var i=e.markedSpans[t].marker;!i.readOnly||r&&-1!=Lo(r,i)||(r||(r=[])).push(i)}});if(!r)return null;for(var n=[{from:t,to:i}],o=0;o<r.length;++o)for(var s=r[o],a=s.find(0),l=0;l<n.length;++l){var u=n[l];if(!(ys(u.to,a.from)<0||ys(u.from,a.to)>0)){var p=[l,1],c=ys(u.from,a.from),d=ys(u.to,a.to);(0>c||!s.inclusiveLeft&&!c)&&p.push({from:u.from,to:a.from});(d>0||!s.inclusiveRight&&!d)&&p.push({from:a.to,to:u.to});n.splice.apply(n,p);l+=p.length-1}}return n}function Kr(e){var t=e.markedSpans;if(t){for(var i=0;i<t.length;++i)t[i].marker.detachLine(e);e.markedSpans=null}}function $r(e,t){if(t){for(var i=0;i<t.length;++i)t[i].marker.attachLine(e);e.markedSpans=t}}function Qr(e){return e.inclusiveLeft?-1:0}function Zr(e){return e.inclusiveRight?1:0}function Jr(e,t){var i=e.lines.length-t.lines.length;if(0!=i)return i;var r=e.find(),n=t.find(),o=ys(r.from,n.from)||Qr(e)-Qr(t);if(o)return-o;var s=ys(r.to,n.to)||Zr(e)-Zr(t);return s?s:t.id-e.id}function en(e,t){var i,r=Ts&&e.markedSpans;if(r)for(var n,o=0;o<r.length;++o){n=r[o];n.marker.collapsed&&null==(t?n.from:n.to)&&(!i||Jr(i,n.marker)<0)&&(i=n.marker)}return i}function tn(e){return en(e,!0)}function rn(e){return en(e,!1)}function nn(e,t,i,r,n){var o=Bn(e,t),s=Ts&&o.markedSpans;if(s)for(var a=0;a<s.length;++a){var l=s[a];if(l.marker.collapsed){var u=l.marker.find(0),p=ys(u.from,i)||Qr(l.marker)-Qr(n),c=ys(u.to,r)||Zr(l.marker)-Zr(n);if(!(p>=0&&0>=c||0>=p&&c>=0)&&(0>=p&&(ys(u.to,i)>0||l.marker.inclusiveRight&&n.inclusiveLeft)||p>=0&&(ys(u.from,r)<0||l.marker.inclusiveLeft&&n.inclusiveRight)))return!0}}}function on(e){for(var t;t=tn(e);)e=t.find(-1,!0).line;return e}function sn(e){for(var t,i;t=rn(e);){e=t.find(1,!0).line;(i||(i=[])).push(e)}return i}function an(e,t){var i=Bn(e,t),r=on(i);return i==r?t:Hn(r)}function ln(e,t){if(t>e.lastLine())return t;var i,r=Bn(e,t);if(!un(e,r))return t;for(;i=rn(r);)r=i.find(1,!0).line;return Hn(r)+1}function un(e,t){var i=Ts&&t.markedSpans;if(i)for(var r,n=0;n<i.length;++n){r=i[n];if(r.marker.collapsed){if(null==r.from)return!0;if(!r.marker.widgetNode&&0==r.from&&r.marker.inclusiveLeft&&pn(e,t,r))return!0}}}function pn(e,t,i){if(null==i.to){var r=i.marker.find(1,!0);return pn(e,r.line,Vr(r.line.markedSpans,i.marker))}if(i.marker.inclusiveRight&&i.to==t.text.length)return!0;for(var n,o=0;o<t.markedSpans.length;++o){n=t.markedSpans[o];if(n.marker.collapsed&&!n.marker.widgetNode&&n.from==i.to&&(null==n.to||n.to!=i.from)&&(n.marker.inclusiveLeft||i.marker.inclusiveRight)&&pn(e,t,n))return!0}}function cn(e,t,i){Wn(t)<(e.curOp&&e.curOp.scrollTop||e.doc.scrollTop)&&Ir(e,null,i)}function dn(e){if(null!=e.height)return e.height;if(!Do(document.body,e.node)){var t="position: relative;";e.coverGutter&&(t+="margin-left: -"+e.cm.display.gutters.offsetWidth+"px;");e.noHScroll&&(t+="width: "+e.cm.display.wrapper.clientWidth+"px;");Po(e.cm.display.measure,bo("div",[e.node],null,t))}return e.height=e.node.offsetHeight}function fn(e,t,i,r){var n=new na(e,i,r);n.noHScroll&&(e.display.alignWidgets=!0);Cr(e.doc,t,"widget",function(t){var i=t.widgets||(t.widgets=[]);null==n.insertAt?i.push(n):i.splice(Math.min(i.length-1,Math.max(0,n.insertAt)),0,n);n.line=t;if(!un(e.doc,t)){var r=Wn(t)<e.doc.scrollTop;Fn(t,t.height+dn(n));r&&Ir(e,null,n.height);e.curOp.forceUpdate=!0}return!0});return n}function hn(e,t,i,r){e.text=t;e.stateAfter&&(e.stateAfter=null);e.styles&&(e.styles=null);null!=e.order&&(e.order=null);Kr(e);$r(e,i);var n=r?r(e):1;n!=e.height&&Fn(e,n)}function En(e){e.parent=null;Kr(e)}function mn(e,t){if(e)for(;;){var i=e.match(/(?:^|\s+)line-(background-)?(\S+)/);if(!i)break;e=e.slice(0,i.index)+e.slice(i.index+i[0].length);var r=i[1]?"bgClass":"textClass";null==t[r]?t[r]=i[2]:new RegExp("(?:^|s)"+i[2]+"(?:$|s)").test(t[r])||(t[r]+=" "+i[2])}return e}function gn(t,i){if(t.blankLine)return t.blankLine(i);if(t.innerMode){var r=e.innerMode(t,i);return r.mode.blankLine?r.mode.blankLine(r.state):void 0}}function vn(t,i,r,n){for(var o=0;10>o;o++){n&&(n[0]=e.innerMode(t,r).mode);var s=t.token(i,r);if(i.pos>i.start)return s}throw new Error("Mode "+t.name+" failed to advance stream.")}function xn(e,t,i,r){function n(e){return{start:c.start,end:c.pos,string:c.current(),type:o||null,state:e?Xs(s.mode,p):p}}var o,s=e.doc,a=s.mode;t=tt(s,t);var l,u=Bn(s,t.line),p=Ct(e,t.line,i),c=new ea(u.text,e.options.tabSize);r&&(l=[]);for(;(r||c.pos<t.ch)&&!c.eol();){c.start=c.pos;o=vn(a,c,p);r&&l.push(n(!0))}return r?l:n()}function Nn(e,t,i,r,n,o,s){var a=i.flattenSpans;null==a&&(a=e.options.flattenSpans);var l,u=0,p=null,c=new ea(t,e.options.tabSize),d=e.options.addModeClass&&[null];""==t&&mn(gn(i,r),o);for(;!c.eol();){if(c.pos>e.options.maxHighlightLength){a=!1;s&&In(e,t,r,c.pos);c.pos=t.length;l=null}else l=mn(vn(i,c,r,d),o);if(d){var f=d[0].name;f&&(l="m-"+(l?f+" "+l:f))}if(!a||p!=l){for(;u<c.start;){u=Math.min(c.start,u+5e4);n(u,p)}p=l}c.start=c.pos}for(;u<c.pos;){var h=Math.min(c.pos,u+5e4);n(h,p);u=h}}function Ln(e,t,i,r){var n=[e.state.modeGen],o={};Nn(e,t.text,e.doc.mode,i,function(e,t){n.push(e,t)},o,r);for(var s=0;s<e.state.overlays.length;++s){var a=e.state.overlays[s],l=1,u=0;Nn(e,t.text,a.mode,!0,function(e,t){for(var i=l;e>u;){var r=n[l];r>e&&n.splice(l,1,e,n[l+1],r);l+=2;u=Math.min(e,r)}if(t)if(a.opaque){n.splice(i,l-i,e,"cm-overlay "+t);l=i+2}else for(;l>i;i+=2){var o=n[i+1];n[i+1]=(o?o+" ":"")+"cm-overlay "+t}},o)}return{styles:n,classes:o.bgClass||o.textClass?o:null}}function Tn(e,t,i){if(!t.styles||t.styles[0]!=e.state.modeGen){var r=Ln(e,t,t.stateAfter=Ct(e,Hn(t)));t.styles=r.styles;r.classes?t.styleClasses=r.classes:t.styleClasses&&(t.styleClasses=null);i===e.doc.frontier&&e.doc.frontier++}return t.styles}function In(e,t,i,r){var n=e.doc.mode,o=new ea(t,e.options.tabSize);o.start=o.pos=r||0;""==t&&gn(n,i);for(;!o.eol()&&o.pos<=e.options.maxHighlightLength;){vn(n,o,i);o.start=o.pos}}function yn(e,t){if(!e||/^\s*$/.test(e))return null;var i=t.addModeClass?aa:sa;return i[e]||(i[e]=e.replace(/\S+/g,"cm-$&"))}function An(e,t){var i=bo("span",null,null,ss?"padding-right: .1px":null),r={pre:bo("pre",[i]),content:i,col:0,pos:0,cm:e};t.measure={};for(var n=0;n<=(t.rest?t.rest.length:0);n++){var o,s=n?t.rest[n-1]:t.line;r.pos=0;r.addToken=Cn;(ns||ss)&&e.getOption("lineWrapping")&&(r.addToken=Rn(r.addToken));Vo(e.display.measure)&&(o=qn(s))&&(r.addToken=bn(r.addToken,o));r.map=[];var a=t!=e.display.externalMeasured&&Hn(s);Pn(s,r,Tn(e,s,a));if(s.styleClasses){s.styleClasses.bgClass&&(r.bgClass=Mo(s.styleClasses.bgClass,r.bgClass||""));s.styleClasses.textClass&&(r.textClass=Mo(s.styleClasses.textClass,r.textClass||""))}0==r.map.length&&r.map.push(0,0,r.content.appendChild(Uo(e.display.measure)));if(0==n){t.measure.map=r.map;t.measure.cache={}}else{(t.measure.maps||(t.measure.maps=[])).push(r.map);(t.measure.caches||(t.measure.caches=[])).push({})}}ss&&/\bcm-tab\b/.test(r.content.lastChild.className)&&(r.content.className="cm-tab-wrap-hack");ga(e,"renderLine",e,t.line,r.pre);r.pre.className&&(r.textClass=Mo(r.pre.className,r.textClass||""));return r}function Sn(e){var t=bo("span","•","cm-invalidchar");t.title="\\u"+e.charCodeAt(0).toString(16);return t}function Cn(e,t,i,r,n,o,s){if(t){var a=e.cm.options.specialChars,l=!1;if(a.test(t))for(var u=document.createDocumentFragment(),p=0;;){a.lastIndex=p;var c=a.exec(t),d=c?c.index-p:t.length-p;if(d){var f=document.createTextNode(t.slice(p,p+d));u.appendChild(ns&&9>os?bo("span",[f]):f);e.map.push(e.pos,e.pos+d,f);e.col+=d;e.pos+=d}if(!c)break;p+=d+1;if(" "==c[0]){var h=e.cm.options.tabSize,E=h-e.col%h,f=u.appendChild(bo("span",xo(E),"cm-tab"));e.col+=E}else{var f=e.cm.options.specialCharPlaceholder(c[0]);u.appendChild(ns&&9>os?bo("span",[f]):f);e.col+=1}e.map.push(e.pos,e.pos+1,f);e.pos++}else{e.col+=t.length;var u=document.createTextNode(t);e.map.push(e.pos,e.pos+t.length,u);ns&&9>os&&(l=!0);e.pos+=t.length}if(i||r||n||l||s){var m=i||"";r&&(m+=r);n&&(m+=n);var g=bo("span",[u],m,s);o&&(g.title=o);return e.content.appendChild(g)}e.content.appendChild(u)}}function Rn(e){function t(e){for(var t=" ",i=0;i<e.length-2;++i)t+=i%2?" ":" ";t+=" ";return t}return function(i,r,n,o,s,a){e(i,r.replace(/ {3,}/g,t),n,o,s,a)}}function bn(e,t){return function(i,r,n,o,s,a){n=n?n+" cm-force-border":"cm-force-border";for(var l=i.pos,u=l+r.length;;){for(var p=0;p<t.length;p++){var c=t[p];if(c.to>l&&c.from<=l)break}if(c.to>=u)return e(i,r,n,o,s,a);e(i,r.slice(0,c.to-l),n,o,null,a);o=null;r=r.slice(c.to-l);l=c.to}}}function On(e,t,i,r){var n=!r&&i.widgetNode;if(n){e.map.push(e.pos,e.pos+t,n);e.content.appendChild(n)}e.pos+=t}function Pn(e,t,i){var r=e.markedSpans,n=e.text,o=0;if(r)for(var s,a,l,u,p,c,d,f=n.length,h=0,E=1,m="",g=0;;){if(g==h){l=u=p=c=a="";d=null;g=1/0;for(var v=[],x=0;x<r.length;++x){var N=r[x],L=N.marker;if(N.from<=h&&(null==N.to||N.to>h)){if(null!=N.to&&g>N.to){g=N.to;u=""}L.className&&(l+=" "+L.className);L.css&&(a=L.css);L.startStyle&&N.from==h&&(p+=" "+L.startStyle);L.endStyle&&N.to==g&&(u+=" "+L.endStyle);L.title&&!c&&(c=L.title);L.collapsed&&(!d||Jr(d.marker,L)<0)&&(d=N)}else N.from>h&&g>N.from&&(g=N.from);"bookmark"==L.type&&N.from==h&&L.widgetNode&&v.push(L)}if(d&&(d.from||0)==h){On(t,(null==d.to?f+1:d.to)-h,d.marker,null==d.from);if(null==d.to)return}if(!d&&v.length)for(var x=0;x<v.length;++x)On(t,0,v[x])}if(h>=f)break;for(var T=Math.min(f,g);;){if(m){var I=h+m.length;if(!d){var y=I>T?m.slice(0,T-h):m;t.addToken(t,y,s?s+l:l,p,h+y.length==g?u:"",c,a)}if(I>=T){m=m.slice(T-h);h=T;break}h=I;p=""}m=n.slice(o,o=i[E++]);s=yn(i[E++],t.cm.options)}}else for(var E=1;E<i.length;E+=2)t.addToken(t,n.slice(o,o=i[E]),yn(i[E+1],t.cm.options))}function Dn(e,t){return 0==t.from.ch&&0==t.to.ch&&""==No(t.text)&&(!e.cm||e.cm.options.wholeLineUpdateBefore)}function wn(e,t,i,r){function n(e){return i?i[e]:null}function o(e,i,n){hn(e,i,n,r);po(e,"change",e,t)}function s(e,t){for(var i=e,o=[];t>i;++i)o.push(new oa(u[i],n(i),r));return o}var a=t.from,l=t.to,u=t.text,p=Bn(e,a.line),c=Bn(e,l.line),d=No(u),f=n(u.length-1),h=l.line-a.line;if(t.full){e.insert(0,s(0,u.length));e.remove(u.length,e.size-u.length)}else if(Dn(e,t)){var E=s(0,u.length-1);o(c,c.text,f);h&&e.remove(a.line,h);E.length&&e.insert(a.line,E)}else if(p==c)if(1==u.length)o(p,p.text.slice(0,a.ch)+d+p.text.slice(l.ch),f);else{var E=s(1,u.length-1);E.push(new oa(d+p.text.slice(l.ch),f,r));o(p,p.text.slice(0,a.ch)+u[0],n(0));e.insert(a.line+1,E)}else if(1==u.length){o(p,p.text.slice(0,a.ch)+u[0]+c.text.slice(l.ch),n(0));e.remove(a.line+1,h)}else{o(p,p.text.slice(0,a.ch)+u[0],n(0));o(c,d+c.text.slice(l.ch),f);var E=s(1,u.length-1);h>1&&e.remove(a.line+1,h-1);e.insert(a.line+1,E)}po(e,"change",e,t)}function _n(e){this.lines=e;this.parent=null;for(var t=0,i=0;t<e.length;++t){e[t].parent=this;i+=e[t].height}this.height=i}function Mn(e){this.children=e;for(var t=0,i=0,r=0;r<e.length;++r){var n=e[r];t+=n.chunkSize();i+=n.height;n.parent=this}this.size=t;this.height=i;this.parent=null}function kn(e,t,i){function r(e,n,o){if(e.linked)for(var s=0;s<e.linked.length;++s){var a=e.linked[s];if(a.doc!=n){var l=o&&a.sharedHist;if(!i||l){t(a.doc,l);r(a.doc,e,l)}}}}r(e,null,!0)}function Gn(e,t){if(t.cm)throw new Error("This document is already in use.");e.doc=t;t.cm=e;s(e);i(e);e.options.lineWrapping||d(e);e.options.mode=t.modeOption;xi(e)}function Bn(e,t){t-=e.first;if(0>t||t>=e.size)throw new Error("There is no line "+(t+e.first)+" in the document.");for(var i=e;!i.lines;)for(var r=0;;++r){var n=i.children[r],o=n.chunkSize();if(o>t){i=n;break}t-=o}return i.lines[t]}function Un(e,t,i){var r=[],n=t.line;e.iter(t.line,i.line+1,function(e){var o=e.text;n==i.line&&(o=o.slice(0,i.ch));n==t.line&&(o=o.slice(t.ch));r.push(o);++n});return r}function Vn(e,t,i){var r=[];e.iter(t,i,function(e){r.push(e.text)});return r}function Fn(e,t){var i=t-e.height;if(i)for(var r=e;r;r=r.parent)r.height+=i}function Hn(e){if(null==e.parent)return null;for(var t=e.parent,i=Lo(t.lines,e),r=t.parent;r;t=r,r=r.parent)for(var n=0;r.children[n]!=t;++n)i+=r.children[n].chunkSize();return i+t.first}function jn(e,t){var i=e.first;e:do{for(var r=0;r<e.children.length;++r){var n=e.children[r],o=n.height;if(o>t){e=n;continue e}t-=o;i+=n.chunkSize()}return i}while(!e.lines);for(var r=0;r<e.lines.length;++r){var s=e.lines[r],a=s.height;if(a>t)break;t-=a}return i+r}function Wn(e){e=on(e);for(var t=0,i=e.parent,r=0;r<i.lines.length;++r){var n=i.lines[r];if(n==e)break;t+=n.height}for(var o=i.parent;o;i=o,o=i.parent)for(var r=0;r<o.children.length;++r){var s=o.children[r];if(s==i)break;t+=s.height}return t}function qn(e){var t=e.order;null==t&&(t=e.order=ja(e.text));return t}function zn(e){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=e||1}function Xn(e,t){var i={from:X(t.from),to:Bs(t),text:Un(e,t.from,t.to)};eo(e,i,t.from.line,t.to.line+1);kn(e,function(e){eo(e,i,t.from.line,t.to.line+1)},!0);return i}function Yn(e){for(;e.length;){var t=No(e);if(!t.ranges)break;e.pop()}}function Kn(e,t){if(t){Yn(e.done);return No(e.done)}if(e.done.length&&!No(e.done).ranges)return No(e.done);if(e.done.length>1&&!e.done[e.done.length-2].ranges){e.done.pop();return No(e.done)}}function $n(e,t,i,r){var n=e.history;n.undone.length=0;var o,s=+new Date;if((n.lastOp==r||n.lastOrigin==t.origin&&t.origin&&("+"==t.origin.charAt(0)&&e.cm&&n.lastModTime>s-e.cm.options.historyEventDelay||"*"==t.origin.charAt(0)))&&(o=Kn(n,n.lastOp==r))){var a=No(o.changes);0==ys(t.from,t.to)&&0==ys(t.from,a.to)?a.to=Bs(t):o.changes.push(Xn(e,t))}else{var l=No(n.done);l&&l.ranges||Jn(e.sel,n.done);o={changes:[Xn(e,t)],generation:n.generation};n.done.push(o);for(;n.done.length>n.undoDepth;){n.done.shift();n.done[0].ranges||n.done.shift()}}n.done.push(i);n.generation=++n.maxGeneration;n.lastModTime=n.lastSelTime=s;n.lastOp=n.lastSelOp=r;n.lastOrigin=n.lastSelOrigin=t.origin;a||ga(e,"historyAdded")}function Qn(e,t,i,r){var n=t.charAt(0);return"*"==n||"+"==n&&i.ranges.length==r.ranges.length&&i.somethingSelected()==r.somethingSelected()&&new Date-e.history.lastSelTime<=(e.cm?e.cm.options.historyEventDelay:500)}function Zn(e,t,i,r){var n=e.history,o=r&&r.origin;i==n.lastSelOp||o&&n.lastSelOrigin==o&&(n.lastModTime==n.lastSelTime&&n.lastOrigin==o||Qn(e,o,No(n.done),t))?n.done[n.done.length-1]=t:Jn(t,n.done);n.lastSelTime=+new Date;n.lastSelOrigin=o;n.lastSelOp=i;r&&r.clearRedo!==!1&&Yn(n.undone)}function Jn(e,t){var i=No(t);i&&i.ranges&&i.equals(e)||t.push(e)}function eo(e,t,i,r){var n=t["spans_"+e.id],o=0;e.iter(Math.max(e.first,i),Math.min(e.first+e.size,r),function(i){i.markedSpans&&((n||(n=t["spans_"+e.id]={}))[o]=i.markedSpans);++o})}function to(e){if(!e)return null;for(var t,i=0;i<e.length;++i)e[i].marker.explicitlyCleared?t||(t=e.slice(0,i)):t&&t.push(e[i]);return t?t.length?t:null:e}function io(e,t){var i=t["spans_"+e.id];if(!i)return null;for(var r=0,n=[];r<t.text.length;++r)n.push(to(i[r]));return n}function ro(e,t,i){for(var r=0,n=[];r<e.length;++r){var o=e[r];if(o.ranges)n.push(i?$.prototype.deepCopy.call(o):o);else{var s=o.changes,a=[];n.push({changes:a});for(var l=0;l<s.length;++l){var u,p=s[l];a.push({from:p.from,to:p.to,text:p.text});if(t)for(var c in p)if((u=c.match(/^spans_(\d+)$/))&&Lo(t,Number(u[1]))>-1){No(a)[c]=p[c];delete p[c]}}}}return n}function no(e,t,i,r){if(i<e.line)e.line+=r;else if(t<e.line){e.line=t;e.ch=0}}function oo(e,t,i,r){for(var n=0;n<e.length;++n){var o=e[n],s=!0;if(o.ranges){if(!o.copied){o=e[n]=o.deepCopy();o.copied=!0}for(var a=0;a<o.ranges.length;a++){no(o.ranges[a].anchor,t,i,r);no(o.ranges[a].head,t,i,r)}}else{for(var a=0;a<o.changes.length;++a){var l=o.changes[a];if(i<l.from.line){l.from=Is(l.from.line+r,l.from.ch);l.to=Is(l.to.line+r,l.to.ch)}else if(t<=l.to.line){s=!1;break}}if(!s){e.splice(0,n+1);n=0}}}}function so(e,t){var i=t.from.line,r=t.to.line,n=t.text.length-(r-i)-1;oo(e.done,i,r,n);oo(e.undone,i,r,n)}function ao(e){return null!=e.defaultPrevented?e.defaultPrevented:0==e.returnValue}function lo(e){return e.target||e.srcElement}function uo(e){var t=e.which;null==t&&(1&e.button?t=1:2&e.button?t=3:4&e.button&&(t=2));ms&&e.ctrlKey&&1==t&&(t=3);return t}function po(e,t){function i(e){return function(){e.apply(null,o)}}var r=e._handlers&&e._handlers[t];if(r){var n,o=Array.prototype.slice.call(arguments,2);if(bs)n=bs.delayedCallbacks;else if(va)n=va;else{n=va=[];setTimeout(co,0)}for(var s=0;s<r.length;++s)n.push(i(r[s]))}}function co(){var e=va;va=null;for(var t=0;t<e.length;++t)e[t]()}function fo(e,t,i){"string"==typeof t&&(t={type:t,preventDefault:function(){this.defaultPrevented=!0}});ga(e,i||t.type,e,t);return ao(t)||t.codemirrorIgnore}function ho(e){var t=e._handlers&&e._handlers.cursorActivity;if(t)for(var i=e.curOp.cursorActivityHandlers||(e.curOp.cursorActivityHandlers=[]),r=0;r<t.length;++r)-1==Lo(i,t[r])&&i.push(t[r])}function Eo(e,t){var i=e._handlers&&e._handlers[t];return i&&i.length>0}function mo(e){e.prototype.on=function(e,t){Ea(this,e,t)};e.prototype.off=function(e,t){ma(this,e,t)}}function go(){this.id=null}function vo(e,t,i){for(var r=0,n=0;;){var o=e.indexOf(" ",r);-1==o&&(o=e.length);var s=o-r;if(o==e.length||n+s>=t)return r+Math.min(s,t-n);n+=o-r;n+=i-n%i;r=o+1;if(n>=t)return r}}function xo(e){for(;Aa.length<=e;)Aa.push(No(Aa)+" ");return Aa[e]}function No(e){return e[e.length-1]}function Lo(e,t){for(var i=0;i<e.length;++i)if(e[i]==t)return i;return-1}function To(e,t){for(var i=[],r=0;r<e.length;r++)i[r]=t(e[r],r);return i}function Io(e,t){var i;if(Object.create)i=Object.create(e);else{var r=function(){};r.prototype=e;i=new r}t&&yo(t,i);return i}function yo(e,t,i){t||(t={});for(var r in e)!e.hasOwnProperty(r)||i===!1&&t.hasOwnProperty(r)||(t[r]=e[r]);return t}function Ao(e){var t=Array.prototype.slice.call(arguments,1);return function(){return e.apply(null,t)}}function So(e,t){return t?t.source.indexOf("\\w")>-1&&ba(e)?!0:t.test(e):ba(e)}function Co(e){for(var t in e)if(e.hasOwnProperty(t)&&e[t])return!1;return!0}function Ro(e){return e.charCodeAt(0)>=768&&Oa.test(e)}function bo(e,t,i,r){var n=document.createElement(e);i&&(n.className=i);r&&(n.style.cssText=r);if("string"==typeof t)n.appendChild(document.createTextNode(t));else if(t)for(var o=0;o<t.length;++o)n.appendChild(t[o]);return n}function Oo(e){for(var t=e.childNodes.length;t>0;--t)e.removeChild(e.firstChild);return e}function Po(e,t){return Oo(e).appendChild(t)}function Do(e,t){if(e.contains)return e.contains(t);for(;t=t.parentNode;)if(t==e)return!0}function wo(){return document.activeElement}function _o(e){return new RegExp("(^|\\s)"+e+"(?:$|\\s)\\s*")}function Mo(e,t){for(var i=e.split(" "),r=0;r<i.length;r++)i[r]&&!_o(i[r]).test(t)&&(t+=" "+i[r]);return t}function ko(e){if(document.body.getElementsByClassName)for(var t=document.body.getElementsByClassName("CodeMirror"),i=0;i<t.length;i++){var r=t[i].CodeMirror;r&&e(r)}}function Go(){if(!Ma){Bo();Ma=!0}}function Bo(){var e;Ea(window,"resize",function(){null==e&&(e=setTimeout(function(){e=null;ko(_i)},100))});Ea(window,"blur",function(){ko(nr)})}function Uo(e){if(null==Pa){var t=bo("span","");Po(e,bo("span",[t,document.createTextNode("x")]));0!=e.firstChild.offsetHeight&&(Pa=t.offsetWidth<=1&&t.offsetHeight>2&&!(ns&&8>os))}return Pa?bo("span",""):bo("span"," ",null,"display: inline-block; width: 1px; margin-right: -1px")}function Vo(e){if(null!=Da)return Da;var t=Po(e,document.createTextNode("AخA")),i=Ca(t,0,1).getBoundingClientRect();if(!i||i.left==i.right)return!1;var r=Ca(t,1,2).getBoundingClientRect();return Da=r.right-i.right<3}function Fo(e){if(null!=Va)return Va;var t=Po(e,bo("span","x")),i=t.getBoundingClientRect(),r=Ca(t,0,1).getBoundingClientRect();return Va=Math.abs(i.left-r.left)>1}function Ho(e,t,i,r){if(!e)return r(t,i,"ltr");for(var n=!1,o=0;o<e.length;++o){var s=e[o];if(s.from<i&&s.to>t||t==i&&s.to==t){r(Math.max(s.from,t),Math.min(s.to,i),1==s.level?"rtl":"ltr");n=!0}}n||r(t,i,"ltr")}function jo(e){return e.level%2?e.to:e.from}function Wo(e){return e.level%2?e.from:e.to}function qo(e){var t=qn(e);return t?jo(t[0]):0}function zo(e){var t=qn(e);return t?Wo(No(t)):e.text.length}function Xo(e,t){var i=Bn(e.doc,t),r=on(i);r!=i&&(t=Hn(r));var n=qn(r),o=n?n[0].level%2?zo(r):qo(r):0;return Is(t,o)}function Yo(e,t){for(var i,r=Bn(e.doc,t);i=rn(r);){r=i.find(1,!0).line;t=null}var n=qn(r),o=n?n[0].level%2?qo(r):zo(r):r.text.length;return Is(null==t?Hn(r):t,o)}function Ko(e,t){var i=Xo(e,t.line),r=Bn(e.doc,i.line),n=qn(r);if(!n||0==n[0].level){var o=Math.max(0,r.text.search(/\S/)),s=t.line==i.line&&t.ch<=o&&t.ch;return Is(i.line,s?0:o)}return i}function $o(e,t,i){var r=e[0].level;return t==r?!0:i==r?!1:i>t}function Qo(e,t){Ha=null;for(var i,r=0;r<e.length;++r){var n=e[r];if(n.from<t&&n.to>t)return r;if(n.from==t||n.to==t){if(null!=i){if($o(e,n.level,e[i].level)){n.from!=n.to&&(Ha=i);return r}n.from!=n.to&&(Ha=r);return i}i=r}}return i}function Zo(e,t,i,r){if(!r)return t+i;do t+=i;while(t>0&&Ro(e.text.charAt(t)));return t}function Jo(e,t,i,r){var n=qn(e);if(!n)return es(e,t,i,r);for(var o=Qo(n,t),s=n[o],a=Zo(e,t,s.level%2?-i:i,r);;){if(a>s.from&&a<s.to)return a;if(a==s.from||a==s.to){if(Qo(n,a)==o)return a;s=n[o+=i];return i>0==s.level%2?s.to:s.from}s=n[o+=i];if(!s)return null;a=i>0==s.level%2?Zo(e,s.to,-1,r):Zo(e,s.from,1,r)}}function es(e,t,i,r){var n=t+i;if(r)for(;n>0&&Ro(e.text.charAt(n));)n+=i;return 0>n||n>e.text.length?null:n}var ts=/gecko\/\d/i.test(navigator.userAgent),is=/MSIE \d/.test(navigator.userAgent),rs=/Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent),ns=is||rs,os=ns&&(is?document.documentMode||6:rs[1]),ss=/WebKit\//.test(navigator.userAgent),as=ss&&/Qt\/\d+\.\d+/.test(navigator.userAgent),ls=/Chrome\//.test(navigator.userAgent),us=/Opera\//.test(navigator.userAgent),ps=/Apple Computer/.test(navigator.vendor),cs=/KHTML\//.test(navigator.userAgent),ds=/Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent),fs=/PhantomJS/.test(navigator.userAgent),hs=/AppleWebKit/.test(navigator.userAgent)&&/Mobile\/\w+/.test(navigator.userAgent),Es=hs||/Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent),ms=hs||/Mac/.test(navigator.platform),gs=/win/i.test(navigator.platform),vs=us&&navigator.userAgent.match(/Version\/(\d*\.\d*)/);vs&&(vs=Number(vs[1]));if(vs&&vs>=15){us=!1;ss=!0}var xs=ms&&(as||us&&(null==vs||12.11>vs)),Ns=ts||ns&&os>=9,Ls=!1,Ts=!1;E.prototype=yo({update:function(e){var t=e.scrollWidth>e.clientWidth+1,i=e.scrollHeight>e.clientHeight+1,r=e.nativeBarWidth;if(i){this.vert.style.display="block";this.vert.style.bottom=t?r+"px":"0";var n=e.viewHeight-(t?r:0);this.vert.firstChild.style.height=Math.max(0,e.scrollHeight-e.clientHeight+n)+"px"}else{this.vert.style.display="";this.vert.firstChild.style.height="0"}if(t){this.horiz.style.display="block";this.horiz.style.right=i?r+"px":"0";this.horiz.style.left=e.barLeft+"px";var o=e.viewWidth-e.barLeft-(i?r:0);this.horiz.firstChild.style.width=e.scrollWidth-e.clientWidth+o+"px"}else{this.horiz.style.display="";this.horiz.firstChild.style.width="0"}if(!this.checkedOverlay&&e.clientHeight>0){0==r&&this.overlayHack();this.checkedOverlay=!0}return{right:i?r:0,bottom:t?r:0}},setScrollLeft:function(e){this.horiz.scrollLeft!=e&&(this.horiz.scrollLeft=e)},setScrollTop:function(e){this.vert.scrollTop!=e&&(this.vert.scrollTop=e)},overlayHack:function(){var e=ms&&!ds?"12px":"18px";this.horiz.style.minHeight=this.vert.style.minWidth=e;var t=this,i=function(e){lo(e)!=t.vert&&lo(e)!=t.horiz&&hi(t.cm,Gi)(e)};Ea(this.vert,"mousedown",i);Ea(this.horiz,"mousedown",i)},clear:function(){var e=this.horiz.parentNode;e.removeChild(this.horiz);e.removeChild(this.vert)}},E.prototype);m.prototype=yo({update:function(){return{bottom:0,right:0}},setScrollLeft:function(){},setScrollTop:function(){},clear:function(){}},m.prototype);e.scrollbarModel={"native":E,"null":m};var Is=e.Pos=function(e,t){if(!(this instanceof Is))return new Is(e,t);this.line=e;this.ch=t},ys=e.cmpPos=function(e,t){return e.line-t.line||e.ch-t.ch};$.prototype={primary:function(){return this.ranges[this.primIndex]},equals:function(e){if(e==this)return!0;if(e.primIndex!=this.primIndex||e.ranges.length!=this.ranges.length)return!1;for(var t=0;t<this.ranges.length;t++){var i=this.ranges[t],r=e.ranges[t];if(0!=ys(i.anchor,r.anchor)||0!=ys(i.head,r.head))return!1}return!0},deepCopy:function(){for(var e=[],t=0;t<this.ranges.length;t++)e[t]=new Q(X(this.ranges[t].anchor),X(this.ranges[t].head));return new $(e,this.primIndex)},somethingSelected:function(){for(var e=0;e<this.ranges.length;e++)if(!this.ranges[e].empty())return!0;return!1},contains:function(e,t){t||(t=e);for(var i=0;i<this.ranges.length;i++){var r=this.ranges[i];if(ys(t,r.from())>=0&&ys(e,r.to())<=0)return i}return-1}};Q.prototype={from:function(){return K(this.anchor,this.head)},to:function(){return Y(this.anchor,this.head)},empty:function(){return this.head.line==this.anchor.line&&this.head.ch==this.anchor.ch}};var As,Ss,Cs,Rs={left:0,right:0,top:0,bottom:0},bs=null,Os=0,Ps=null,Ds=0,ws=0,_s=null;ns?_s=-.53:ts?_s=15:ls?_s=-.7:ps&&(_s=-1/3);var Ms=function(e){var t=e.wheelDeltaX,i=e.wheelDeltaY;null==t&&e.detail&&e.axis==e.HORIZONTAL_AXIS&&(t=e.detail);null==i&&e.detail&&e.axis==e.VERTICAL_AXIS?i=e.detail:null==i&&(i=e.wheelDelta);return{x:t,y:i}};e.wheelEventPixels=function(e){var t=Ms(e);t.x*=_s;t.y*=_s;return t};var ks=new go,Gs=null,Bs=e.changeEnd=function(e){return e.text?Is(e.from.line+e.text.length-1,No(e.text).length+(1==e.text.length?e.from.ch:0)):e.to};e.prototype={constructor:e,focus:function(){window.focus();Oi(this);Ci(this)},setOption:function(e,t){var i=this.options,r=i[e];if(i[e]!=t||"mode"==e){i[e]=t;Vs.hasOwnProperty(e)&&hi(this,Vs[e])(this,t,r)}},getOption:function(e){return this.options[e]},getDoc:function(){return this.doc},addKeyMap:function(e,t){this.state.keyMaps[t?"push":"unshift"](wr(e))},removeKeyMap:function(e){for(var t=this.state.keyMaps,i=0;i<t.length;++i)if(t[i]==e||t[i].name==e){t.splice(i,1);return!0}},addOverlay:Ei(function(t,i){var r=t.token?t:e.getMode(this.options,t);if(r.startState)throw new Error("Overlays may not be stateful.");this.state.overlays.push({mode:r,modeSpec:t,opaque:i&&i.opaque});
this.state.modeGen++;xi(this)}),removeOverlay:Ei(function(e){for(var t=this.state.overlays,i=0;i<t.length;++i){var r=t[i].modeSpec;if(r==e||"string"==typeof e&&r.name==e){t.splice(i,1);this.state.modeGen++;xi(this);return}}}),indentLine:Ei(function(e,t,i){"string"!=typeof t&&"number"!=typeof t&&(t=null==t?this.options.smartIndent?"smart":"prev":t?"add":"subtract");rt(this.doc,e)&&Sr(this,e,t,i)}),indentSelection:Ei(function(e){for(var t=this.doc.sel.ranges,i=-1,r=0;r<t.length;r++){var n=t[r];if(n.empty()){if(n.head.line>i){Sr(this,n.head.line,e,!0);i=n.head.line;r==this.doc.sel.primIndex&&yr(this)}}else{var o=n.from(),s=n.to(),a=Math.max(i,o.line);i=Math.min(this.lastLine(),s.line-(s.ch?0:1))+1;for(var l=a;i>l;++l)Sr(this,l,e);var u=this.doc.sel.ranges;0==o.ch&&t.length==u.length&&u[r].from().ch>0&<(this.doc,r,new Q(o,u[r].to()),La)}}}),getTokenAt:function(e,t){return xn(this,e,t)},getLineTokens:function(e,t){return xn(this,Is(e),t,!0)},getTokenTypeAt:function(e){e=tt(this.doc,e);var t,i=Tn(this,Bn(this.doc,e.line)),r=0,n=(i.length-1)/2,o=e.ch;if(0==o)t=i[2];else for(;;){var s=r+n>>1;if((s?i[2*s-1]:0)>=o)n=s;else{if(!(i[2*s+1]<o)){t=i[2*s+2];break}r=s+1}}var a=t?t.indexOf("cm-overlay "):-1;return 0>a?t:0==a?null:t.slice(0,a-1)},getModeAt:function(t){var i=this.doc.mode;return i.innerMode?e.innerMode(i,this.getTokenAt(t).state).mode:i},getHelper:function(e,t){return this.getHelpers(e,t)[0]},getHelpers:function(e,t){var i=[];if(!zs.hasOwnProperty(t))return zs;var r=zs[t],n=this.getModeAt(e);if("string"==typeof n[t])r[n[t]]&&i.push(r[n[t]]);else if(n[t])for(var o=0;o<n[t].length;o++){var s=r[n[t][o]];s&&i.push(s)}else n.helperType&&r[n.helperType]?i.push(r[n.helperType]):r[n.name]&&i.push(r[n.name]);for(var o=0;o<r._global.length;o++){var a=r._global[o];a.pred(n,this)&&-1==Lo(i,a.val)&&i.push(a.val)}return i},getStateAfter:function(e,t){var i=this.doc;e=et(i,null==e?i.first+i.size-1:e);return Ct(this,e+1,t)},cursorCoords:function(e,t){var i,r=this.doc.sel.primary();i=null==e?r.head:"object"==typeof e?tt(this.doc,e):e?r.from():r.to();return Qt(this,i,t||"page")},charCoords:function(e,t){return $t(this,tt(this.doc,e),t||"page")},coordsChar:function(e,t){e=Kt(this,e,t||"page");return ei(this,e.left,e.top)},lineAtHeight:function(e,t){e=Kt(this,{top:e,left:0},t||"page").top;return jn(this.doc,e+this.display.viewOffset)},heightAtLine:function(e,t){var i=!1,r=this.doc.first+this.doc.size-1;if(e<this.doc.first)e=this.doc.first;else if(e>r){e=r;i=!0}var n=Bn(this.doc,e);return Yt(this,n,{top:0,left:0},t||"page").top+(i?this.doc.height-Wn(n):0)},defaultTextHeight:function(){return ii(this.display)},defaultCharWidth:function(){return ri(this.display)},setGutterMarker:Ei(function(e,t,i){return Cr(this.doc,e,"gutter",function(e){var r=e.gutterMarkers||(e.gutterMarkers={});r[t]=i;!i&&Co(r)&&(e.gutterMarkers=null);return!0})}),clearGutter:Ei(function(e){var t=this,i=t.doc,r=i.first;i.iter(function(i){if(i.gutterMarkers&&i.gutterMarkers[e]){i.gutterMarkers[e]=null;Ni(t,r,"gutter");Co(i.gutterMarkers)&&(i.gutterMarkers=null)}++r})}),addLineWidget:Ei(function(e,t,i){return fn(this,e,t,i)}),removeLineWidget:function(e){e.clear()},lineInfo:function(e){if("number"==typeof e){if(!rt(this.doc,e))return null;var t=e;e=Bn(this.doc,e);if(!e)return null}else{var t=Hn(e);if(null==t)return null}return{line:t,handle:e,text:e.text,gutterMarkers:e.gutterMarkers,textClass:e.textClass,bgClass:e.bgClass,wrapClass:e.wrapClass,widgets:e.widgets}},getViewport:function(){return{from:this.display.viewFrom,to:this.display.viewTo}},addWidget:function(e,t,i,r,n){var o=this.display;e=Qt(this,tt(this.doc,e));var s=e.bottom,a=e.left;t.style.position="absolute";t.setAttribute("cm-ignore-events","true");o.sizer.appendChild(t);if("over"==r)s=e.top;else if("above"==r||"near"==r){var l=Math.max(o.wrapper.clientHeight,this.doc.height),u=Math.max(o.sizer.clientWidth,o.lineSpace.clientWidth);("above"==r||e.bottom+t.offsetHeight>l)&&e.top>t.offsetHeight?s=e.top-t.offsetHeight:e.bottom+t.offsetHeight<=l&&(s=e.bottom);a+t.offsetWidth>u&&(a=u-t.offsetWidth)}t.style.top=s+"px";t.style.left=t.style.right="";if("right"==n){a=o.sizer.clientWidth-t.offsetWidth;t.style.right="0px"}else{"left"==n?a=0:"middle"==n&&(a=(o.sizer.clientWidth-t.offsetWidth)/2);t.style.left=a+"px"}i&&Lr(this,a,s,a+t.offsetWidth,s+t.offsetHeight)},triggerOnKeyDown:Ei(Ji),triggerOnKeyPress:Ei(ir),triggerOnKeyUp:tr,execCommand:function(e){return Ks.hasOwnProperty(e)?Ks[e](this):void 0},findPosH:function(e,t,i,r){var n=1;if(0>t){n=-1;t=-t}for(var o=0,s=tt(this.doc,e);t>o;++o){s=br(this.doc,s,n,i,r);if(s.hitSide)break}return s},moveH:Ei(function(e,t){var i=this;i.extendSelectionsBy(function(r){return i.display.shift||i.doc.extend||r.empty()?br(i.doc,r.head,e,t,i.options.rtlMoveVisually):0>e?r.from():r.to()},Ia)}),deleteH:Ei(function(e,t){var i=this.doc.sel,r=this.doc;i.somethingSelected()?r.replaceSelection("",null,"+delete"):Rr(this,function(i){var n=br(r,i.head,e,t,!1);return 0>e?{from:n,to:i.head}:{from:i.head,to:n}})}),findPosV:function(e,t,i,r){var n=1,o=r;if(0>t){n=-1;t=-t}for(var s=0,a=tt(this.doc,e);t>s;++s){var l=Qt(this,a,"div");null==o?o=l.left:l.left=o;a=Or(this,l,n,i);if(a.hitSide)break}return a},moveV:Ei(function(e,t){var i=this,r=this.doc,n=[],o=!i.display.shift&&!r.extend&&r.sel.somethingSelected();r.extendSelectionsBy(function(s){if(o)return 0>e?s.from():s.to();var a=Qt(i,s.head,"div");null!=s.goalColumn&&(a.left=s.goalColumn);n.push(a.left);var l=Or(i,a,e,t);"page"==t&&s==r.sel.primary()&&Ir(i,null,$t(i,l,"div").top-a.top);return l},Ia);if(n.length)for(var s=0;s<r.sel.ranges.length;s++)r.sel.ranges[s].goalColumn=n[s]}),findWordAt:function(e){var t=this.doc,i=Bn(t,e.line).text,r=e.ch,n=e.ch;if(i){var o=this.getHelper(e,"wordChars");(e.xRel<0||n==i.length)&&r?--r:++n;for(var s=i.charAt(r),a=So(s,o)?function(e){return So(e,o)}:/\s/.test(s)?function(e){return/\s/.test(e)}:function(e){return!/\s/.test(e)&&!So(e)};r>0&&a(i.charAt(r-1));)--r;for(;n<i.length&&a(i.charAt(n));)++n}return new Q(Is(e.line,r),Is(e.line,n))},toggleOverwrite:function(e){if(null==e||e!=this.state.overwrite){(this.state.overwrite=!this.state.overwrite)?_a(this.display.cursorDiv,"CodeMirror-overwrite"):wa(this.display.cursorDiv,"CodeMirror-overwrite");ga(this,"overwriteToggle",this,this.state.overwrite)}},hasFocus:function(){return wo()==this.display.input},scrollTo:Ei(function(e,t){(null!=e||null!=t)&&Ar(this);null!=e&&(this.curOp.scrollLeft=e);null!=t&&(this.curOp.scrollTop=t)}),getScrollInfo:function(){var e=this.display.scroller;return{left:e.scrollLeft,top:e.scrollTop,height:e.scrollHeight-Pt(this)-this.display.barHeight,width:e.scrollWidth-Pt(this)-this.display.barWidth,clientHeight:wt(this),clientWidth:Dt(this)}},scrollIntoView:Ei(function(e,t){if(null==e){e={from:this.doc.sel.primary().head,to:null};null==t&&(t=this.options.cursorScrollMargin)}else"number"==typeof e?e={from:Is(e,0),to:null}:null==e.from&&(e={from:e,to:null});e.to||(e.to=e.from);e.margin=t||0;if(null!=e.from.line){Ar(this);this.curOp.scrollToPos=e}else{var i=Tr(this,Math.min(e.from.left,e.to.left),Math.min(e.from.top,e.to.top)-e.margin,Math.max(e.from.right,e.to.right),Math.max(e.from.bottom,e.to.bottom)+e.margin);this.scrollTo(i.scrollLeft,i.scrollTop)}}),setSize:Ei(function(e,t){function i(e){return"number"==typeof e||/^\d+$/.test(String(e))?e+"px":e}var r=this;null!=e&&(r.display.wrapper.style.width=i(e));null!=t&&(r.display.wrapper.style.height=i(t));r.options.lineWrapping&&Wt(this);var n=r.display.viewFrom;r.doc.iter(n,r.display.viewTo,function(e){if(e.widgets)for(var t=0;t<e.widgets.length;t++)if(e.widgets[t].noHScroll){Ni(r,n,"widget");break}++n});r.curOp.forceUpdate=!0;ga(r,"refresh",this)}),operation:function(e){return fi(this,e)},refresh:Ei(function(){var e=this.display.cachedTextHeight;xi(this);this.curOp.forceUpdate=!0;qt(this);this.scrollTo(this.doc.scrollLeft,this.doc.scrollTop);p(this);(null==e||Math.abs(e-ii(this.display))>.5)&&s(this);ga(this,"refresh",this)}),swapDoc:Ei(function(e){var t=this.doc;t.cm=null;Gn(this,e);qt(this);bi(this);this.scrollTo(e.scrollLeft,e.scrollTop);this.curOp.forceScroll=!0;po(this,"swapDoc",this,t);return t}),getInputField:function(){return this.display.input},getWrapperElement:function(){return this.display.wrapper},getScrollerElement:function(){return this.display.scroller},getGutterElement:function(){return this.display.gutters}};mo(e);var Us=e.defaults={},Vs=e.optionHandlers={},Fs=e.Init={toString:function(){return"CodeMirror.Init"}};Pr("value","",function(e,t){e.setValue(t)},!0);Pr("mode",null,function(e,t){e.doc.modeOption=t;i(e)},!0);Pr("indentUnit",2,i,!0);Pr("indentWithTabs",!1);Pr("smartIndent",!0);Pr("tabSize",4,function(e){r(e);qt(e);xi(e)},!0);Pr("specialChars",/[\t\u0000-\u0019\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g,function(e,t){e.options.specialChars=new RegExp(t.source+(t.test(" ")?"":"| "),"g");e.refresh()},!0);Pr("specialCharPlaceholder",Sn,function(e){e.refresh()},!0);Pr("electricChars",!0);Pr("rtlMoveVisually",!gs);Pr("wholeLineUpdateBefore",!0);Pr("theme","default",function(e){a(e);l(e)},!0);Pr("keyMap","default",function(t,i,r){var n=wr(i),o=r!=e.Init&&wr(r);o&&o.detach&&o.detach(t,n);n.attach&&n.attach(t,o||null)});Pr("extraKeys",null);Pr("lineWrapping",!1,n,!0);Pr("gutters",[],function(e){f(e.options);l(e)},!0);Pr("fixedGutter",!0,function(e,t){e.display.gutters.style.left=t?y(e.display)+"px":"0";e.refresh()},!0);Pr("coverGutterNextToScrollbar",!1,function(e){v(e)},!0);Pr("scrollbarStyle","native",function(e){g(e);v(e);e.display.scrollbars.setScrollTop(e.doc.scrollTop);e.display.scrollbars.setScrollLeft(e.doc.scrollLeft)},!0);Pr("lineNumbers",!1,function(e){f(e.options);l(e)},!0);Pr("firstLineNumber",1,l,!0);Pr("lineNumberFormatter",function(e){return e},l,!0);Pr("showCursorWhenSelecting",!1,Nt,!0);Pr("resetSelectionOnContextMenu",!0);Pr("readOnly",!1,function(e,t){if("nocursor"==t){nr(e);e.display.input.blur();e.display.disabled=!0}else{e.display.disabled=!1;t||bi(e)}});Pr("disableInput",!1,function(e,t){t||bi(e)},!0);Pr("dragDrop",!0);Pr("cursorBlinkRate",530);Pr("cursorScrollMargin",0);Pr("cursorHeight",1,Nt,!0);Pr("singleCursorHeightPerLine",!0,Nt,!0);Pr("workTime",100);Pr("workDelay",100);Pr("flattenSpans",!0,r,!0);Pr("addModeClass",!1,r,!0);Pr("pollInterval",100);Pr("undoDepth",200,function(e,t){e.doc.history.undoDepth=t});Pr("historyEventDelay",1250);Pr("viewportMargin",10,function(e){e.refresh()},!0);Pr("maxHighlightLength",1e4,r,!0);Pr("moveInputWithCursor",!0,function(e,t){t||(e.display.inputDiv.style.top=e.display.inputDiv.style.left=0)});Pr("tabindex",null,function(e,t){e.display.input.tabIndex=t||""});Pr("autofocus",null);var Hs=e.modes={},js=e.mimeModes={};e.defineMode=function(t,i){e.defaults.mode||"null"==t||(e.defaults.mode=t);arguments.length>2&&(i.dependencies=Array.prototype.slice.call(arguments,2));Hs[t]=i};e.defineMIME=function(e,t){js[e]=t};e.resolveMode=function(t){if("string"==typeof t&&js.hasOwnProperty(t))t=js[t];else if(t&&"string"==typeof t.name&&js.hasOwnProperty(t.name)){var i=js[t.name];"string"==typeof i&&(i={name:i});t=Io(i,t);t.name=i.name}else if("string"==typeof t&&/^[\w\-]+\/[\w\-]+\+xml$/.test(t))return e.resolveMode("application/xml");return"string"==typeof t?{name:t}:t||{name:"null"}};e.getMode=function(t,i){var i=e.resolveMode(i),r=Hs[i.name];if(!r)return e.getMode(t,"text/plain");var n=r(t,i);if(Ws.hasOwnProperty(i.name)){var o=Ws[i.name];for(var s in o)if(o.hasOwnProperty(s)){n.hasOwnProperty(s)&&(n["_"+s]=n[s]);n[s]=o[s]}}n.name=i.name;i.helperType&&(n.helperType=i.helperType);if(i.modeProps)for(var s in i.modeProps)n[s]=i.modeProps[s];return n};e.defineMode("null",function(){return{token:function(e){e.skipToEnd()}}});e.defineMIME("text/plain","null");var Ws=e.modeExtensions={};e.extendMode=function(e,t){var i=Ws.hasOwnProperty(e)?Ws[e]:Ws[e]={};yo(t,i)};e.defineExtension=function(t,i){e.prototype[t]=i};e.defineDocExtension=function(e,t){ua.prototype[e]=t};e.defineOption=Pr;var qs=[];e.defineInitHook=function(e){qs.push(e)};var zs=e.helpers={};e.registerHelper=function(t,i,r){zs.hasOwnProperty(t)||(zs[t]=e[t]={_global:[]});zs[t][i]=r};e.registerGlobalHelper=function(t,i,r,n){e.registerHelper(t,i,n);zs[t]._global.push({pred:r,val:n})};var Xs=e.copyState=function(e,t){if(t===!0)return t;if(e.copyState)return e.copyState(t);var i={};for(var r in t){var n=t[r];n instanceof Array&&(n=n.concat([]));i[r]=n}return i},Ys=e.startState=function(e,t,i){return e.startState?e.startState(t,i):!0};e.innerMode=function(e,t){for(;e.innerMode;){var i=e.innerMode(t);if(!i||i.mode==e)break;t=i.state;e=i.mode}return i||{mode:e,state:t}};var Ks=e.commands={selectAll:function(e){e.setSelection(Is(e.firstLine(),0),Is(e.lastLine()),La)},singleSelection:function(e){e.setSelection(e.getCursor("anchor"),e.getCursor("head"),La)},killLine:function(e){Rr(e,function(t){if(t.empty()){var i=Bn(e.doc,t.head.line).text.length;return t.head.ch==i&&t.head.line<e.lastLine()?{from:t.head,to:Is(t.head.line+1,0)}:{from:t.head,to:Is(t.head.line,i)}}return{from:t.from(),to:t.to()}})},deleteLine:function(e){Rr(e,function(t){return{from:Is(t.from().line,0),to:tt(e.doc,Is(t.to().line+1,0))}})},delLineLeft:function(e){Rr(e,function(e){return{from:Is(e.from().line,0),to:e.from()}})},delWrappedLineLeft:function(e){Rr(e,function(t){var i=e.charCoords(t.head,"div").top+5,r=e.coordsChar({left:0,top:i},"div");return{from:r,to:t.from()}})},delWrappedLineRight:function(e){Rr(e,function(t){var i=e.charCoords(t.head,"div").top+5,r=e.coordsChar({left:e.display.lineDiv.offsetWidth+100,top:i},"div");return{from:t.from(),to:r}})},undo:function(e){e.undo()},redo:function(e){e.redo()},undoSelection:function(e){e.undoSelection()},redoSelection:function(e){e.redoSelection()},goDocStart:function(e){e.extendSelection(Is(e.firstLine(),0))},goDocEnd:function(e){e.extendSelection(Is(e.lastLine()))},goLineStart:function(e){e.extendSelectionsBy(function(t){return Xo(e,t.head.line)},{origin:"+move",bias:1})},goLineStartSmart:function(e){e.extendSelectionsBy(function(t){return Ko(e,t.head)},{origin:"+move",bias:1})},goLineEnd:function(e){e.extendSelectionsBy(function(t){return Yo(e,t.head.line)},{origin:"+move",bias:-1})},goLineRight:function(e){e.extendSelectionsBy(function(t){var i=e.charCoords(t.head,"div").top+5;return e.coordsChar({left:e.display.lineDiv.offsetWidth+100,top:i},"div")},Ia)},goLineLeft:function(e){e.extendSelectionsBy(function(t){var i=e.charCoords(t.head,"div").top+5;return e.coordsChar({left:0,top:i},"div")},Ia)},goLineLeftSmart:function(e){e.extendSelectionsBy(function(t){var i=e.charCoords(t.head,"div").top+5,r=e.coordsChar({left:0,top:i},"div");return r.ch<e.getLine(r.line).search(/\S/)?Ko(e,t.head):r},Ia)},goLineUp:function(e){e.moveV(-1,"line")},goLineDown:function(e){e.moveV(1,"line")},goPageUp:function(e){e.moveV(-1,"page")},goPageDown:function(e){e.moveV(1,"page")},goCharLeft:function(e){e.moveH(-1,"char")},goCharRight:function(e){e.moveH(1,"char")},goColumnLeft:function(e){e.moveH(-1,"column")},goColumnRight:function(e){e.moveH(1,"column")},goWordLeft:function(e){e.moveH(-1,"word")},goGroupRight:function(e){e.moveH(1,"group")},goGroupLeft:function(e){e.moveH(-1,"group")},goWordRight:function(e){e.moveH(1,"word")},delCharBefore:function(e){e.deleteH(-1,"char")},delCharAfter:function(e){e.deleteH(1,"char")},delWordBefore:function(e){e.deleteH(-1,"word")},delWordAfter:function(e){e.deleteH(1,"word")},delGroupBefore:function(e){e.deleteH(-1,"group")},delGroupAfter:function(e){e.deleteH(1,"group")},indentAuto:function(e){e.indentSelection("smart")},indentMore:function(e){e.indentSelection("add")},indentLess:function(e){e.indentSelection("subtract")},insertTab:function(e){e.replaceSelection(" ")},insertSoftTab:function(e){for(var t=[],i=e.listSelections(),r=e.options.tabSize,n=0;n<i.length;n++){var o=i[n].from(),s=ya(e.getLine(o.line),o.ch,r);t.push(new Array(r-s%r+1).join(" "))}e.replaceSelections(t)},defaultTab:function(e){e.somethingSelected()?e.indentSelection("add"):e.execCommand("insertTab")},transposeChars:function(e){fi(e,function(){for(var t=e.listSelections(),i=[],r=0;r<t.length;r++){var n=t[r].head,o=Bn(e.doc,n.line).text;if(o){n.ch==o.length&&(n=new Is(n.line,n.ch-1));if(n.ch>0){n=new Is(n.line,n.ch+1);e.replaceRange(o.charAt(n.ch-1)+o.charAt(n.ch-2),Is(n.line,n.ch-2),n,"+transpose")}else if(n.line>e.doc.first){var s=Bn(e.doc,n.line-1).text;s&&e.replaceRange(o.charAt(0)+"\n"+s.charAt(s.length-1),Is(n.line-1,s.length-1),Is(n.line,1),"+transpose")}}i.push(new Q(n,n))}e.setSelections(i)})},newlineAndIndent:function(e){fi(e,function(){for(var t=e.listSelections().length,i=0;t>i;i++){var r=e.listSelections()[i];e.replaceRange("\n",r.anchor,r.head,"+input");e.indentLine(r.from().line+1,null,!0);yr(e)}})},toggleOverwrite:function(e){e.toggleOverwrite()}},$s=e.keyMap={};$s.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"};$s.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"};$s.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"};$s.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"]};$s["default"]=ms?$s.macDefault:$s.pcDefault;e.normalizeKeyMap=function(e){var t={};for(var i in e)if(e.hasOwnProperty(i)){var r=e[i];if(/^(name|fallthrough|(de|at)tach)$/.test(i))continue;if("..."==r){delete e[i];continue}for(var n=To(i.split(" "),Dr),o=0;o<n.length;o++){var s,a;if(o==n.length-1){a=i;s=r}else{a=n.slice(0,o+1).join(" ");s="..."}var l=t[a];if(l){if(l!=s)throw new Error("Inconsistent bindings for "+a)}else t[a]=s}delete e[i]}for(var u in t)e[u]=t[u];return e};var Qs=e.lookupKey=function(e,t,i,r){t=wr(t);var n=t.call?t.call(e,r):t[e];if(n===!1)return"nothing";if("..."===n)return"multi";if(null!=n&&i(n))return"handled";if(t.fallthrough){if("[object Array]"!=Object.prototype.toString.call(t.fallthrough))return Qs(e,t.fallthrough,i,r);for(var o=0;o<t.fallthrough.length;o++){var s=Qs(e,t.fallthrough[o],i,r);if(s)return s}}},Zs=e.isModifierKey=function(e){var t="string"==typeof e?e:Fa[e.keyCode];return"Ctrl"==t||"Alt"==t||"Shift"==t||"Mod"==t},Js=e.keyName=function(e,t){if(us&&34==e.keyCode&&e["char"])return!1;var i=Fa[e.keyCode],r=i;if(null==r||e.altGraphKey)return!1;e.altKey&&"Alt"!=i&&(r="Alt-"+r);(xs?e.metaKey:e.ctrlKey)&&"Ctrl"!=i&&(r="Ctrl-"+r);(xs?e.ctrlKey:e.metaKey)&&"Cmd"!=i&&(r="Cmd-"+r);!t&&e.shiftKey&&"Shift"!=i&&(r="Shift-"+r);return r};e.fromTextArea=function(t,i){function r(){t.value=u.getValue()}i||(i={});i.value=t.value;!i.tabindex&&t.tabindex&&(i.tabindex=t.tabindex);!i.placeholder&&t.placeholder&&(i.placeholder=t.placeholder);if(null==i.autofocus){var n=wo();i.autofocus=n==t||null!=t.getAttribute("autofocus")&&n==document.body}if(t.form){Ea(t.form,"submit",r);if(!i.leaveSubmitMethodAlone){var o=t.form,s=o.submit;try{var a=o.submit=function(){r();o.submit=s;o.submit();o.submit=a}}catch(l){}}}t.style.display="none";var u=e(function(e){t.parentNode.insertBefore(e,t.nextSibling)},i);u.save=r;u.getTextArea=function(){return t};u.toTextArea=function(){u.toTextArea=isNaN;r();t.parentNode.removeChild(u.getWrapperElement());t.style.display="";if(t.form){ma(t.form,"submit",r);"function"==typeof t.form.submit&&(t.form.submit=s)}};return u};var ea=e.StringStream=function(e,t){this.pos=this.start=0;this.string=e;this.tabSize=t||8;this.lastColumnPos=this.lastColumnValue=0;this.lineStart=0};ea.prototype={eol:function(){return this.pos>=this.string.length},sol:function(){return this.pos==this.lineStart},peek:function(){return this.string.charAt(this.pos)||void 0},next:function(){return this.pos<this.string.length?this.string.charAt(this.pos++):void 0},eat:function(e){var t=this.string.charAt(this.pos);if("string"==typeof e)var i=t==e;else var i=t&&(e.test?e.test(t):e(t));if(i){++this.pos;return t}},eatWhile:function(e){for(var t=this.pos;this.eat(e););return this.pos>t},eatSpace:function(){for(var e=this.pos;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++this.pos;return this.pos>e},skipToEnd:function(){this.pos=this.string.length},skipTo:function(e){var t=this.string.indexOf(e,this.pos);if(t>-1){this.pos=t;return!0}},backUp:function(e){this.pos-=e},column:function(){if(this.lastColumnPos<this.start){this.lastColumnValue=ya(this.string,this.start,this.tabSize,this.lastColumnPos,this.lastColumnValue);this.lastColumnPos=this.start}return this.lastColumnValue-(this.lineStart?ya(this.string,this.lineStart,this.tabSize):0)},indentation:function(){return ya(this.string,null,this.tabSize)-(this.lineStart?ya(this.string,this.lineStart,this.tabSize):0)},match:function(e,t,i){if("string"!=typeof e){var r=this.string.slice(this.pos).match(e);if(r&&r.index>0)return null;r&&t!==!1&&(this.pos+=r[0].length);return r}var n=function(e){return i?e.toLowerCase():e},o=this.string.substr(this.pos,e.length);if(n(o)==n(e)){t!==!1&&(this.pos+=e.length);return!0}},current:function(){return this.string.slice(this.start,this.pos)},hideFirstChars:function(e,t){this.lineStart+=e;try{return t()}finally{this.lineStart-=e}}};var ta=e.TextMarker=function(e,t){this.lines=[];this.type=t;this.doc=e};mo(ta);ta.prototype.clear=function(){if(!this.explicitlyCleared){var e=this.doc.cm,t=e&&!e.curOp;t&&ni(e);if(Eo(this,"clear")){var i=this.find();i&&po(this,"clear",i.from,i.to)}for(var r=null,n=null,o=0;o<this.lines.length;++o){var s=this.lines[o],a=Vr(s.markedSpans,this);if(e&&!this.collapsed)Ni(e,Hn(s),"text");else if(e){null!=a.to&&(n=Hn(s));null!=a.from&&(r=Hn(s))}s.markedSpans=Fr(s.markedSpans,a);null==a.from&&this.collapsed&&!un(this.doc,s)&&e&&Fn(s,ii(e.display))}if(e&&this.collapsed&&!e.options.lineWrapping)for(var o=0;o<this.lines.length;++o){var l=on(this.lines[o]),u=c(l);if(u>e.display.maxLineLength){e.display.maxLine=l;e.display.maxLineLength=u;e.display.maxLineChanged=!0}}null!=r&&e&&this.collapsed&&xi(e,r,n+1);this.lines.length=0;this.explicitlyCleared=!0;if(this.atomic&&this.doc.cantEdit){this.doc.cantEdit=!1;e&&Et(e.doc)}e&&po(e,"markerCleared",e,this);t&&si(e);this.parent&&this.parent.clear()}};ta.prototype.find=function(e,t){null==e&&"bookmark"==this.type&&(e=1);for(var i,r,n=0;n<this.lines.length;++n){var o=this.lines[n],s=Vr(o.markedSpans,this);if(null!=s.from){i=Is(t?o:Hn(o),s.from);if(-1==e)return i}if(null!=s.to){r=Is(t?o:Hn(o),s.to);if(1==e)return r}}return i&&{from:i,to:r}};ta.prototype.changed=function(){var e=this.find(-1,!0),t=this,i=this.doc.cm;e&&i&&fi(i,function(){var r=e.line,n=Hn(e.line),o=Bt(i,n);if(o){jt(o);i.curOp.selectionChanged=i.curOp.forceUpdate=!0}i.curOp.updateMaxLine=!0;if(!un(t.doc,r)&&null!=t.height){var s=t.height;t.height=null;var a=dn(t)-s;a&&Fn(r,r.height+a)}})};ta.prototype.attachLine=function(e){if(!this.lines.length&&this.doc.cm){var t=this.doc.cm.curOp;t.maybeHiddenMarkers&&-1!=Lo(t.maybeHiddenMarkers,this)||(t.maybeUnhiddenMarkers||(t.maybeUnhiddenMarkers=[])).push(this)}this.lines.push(e)};ta.prototype.detachLine=function(e){this.lines.splice(Lo(this.lines,e),1);if(!this.lines.length&&this.doc.cm){var t=this.doc.cm.curOp;(t.maybeHiddenMarkers||(t.maybeHiddenMarkers=[])).push(this)}};var ia=0,ra=e.SharedTextMarker=function(e,t){this.markers=e;this.primary=t;for(var i=0;i<e.length;++i)e[i].parent=this};mo(ra);ra.prototype.clear=function(){if(!this.explicitlyCleared){this.explicitlyCleared=!0;for(var e=0;e<this.markers.length;++e)this.markers[e].clear();po(this,"clear")}};ra.prototype.find=function(e,t){return this.primary.find(e,t)};var na=e.LineWidget=function(e,t,i){if(i)for(var r in i)i.hasOwnProperty(r)&&(this[r]=i[r]);this.cm=e;this.node=t};mo(na);na.prototype.clear=function(){var e=this.cm,t=this.line.widgets,i=this.line,r=Hn(i);if(null!=r&&t){for(var n=0;n<t.length;++n)t[n]==this&&t.splice(n--,1);t.length||(i.widgets=null);var o=dn(this);fi(e,function(){cn(e,i,-o);Ni(e,r,"widget");Fn(i,Math.max(0,i.height-o))})}};na.prototype.changed=function(){var e=this.height,t=this.cm,i=this.line;this.height=null;var r=dn(this)-e;r&&fi(t,function(){t.curOp.forceUpdate=!0;cn(t,i,r);Fn(i,i.height+r)})};var oa=e.Line=function(e,t,i){this.text=e;$r(this,t);this.height=i?i(this):1};mo(oa);oa.prototype.lineNo=function(){return Hn(this)};var sa={},aa={};_n.prototype={chunkSize:function(){return this.lines.length},removeInner:function(e,t){for(var i=e,r=e+t;r>i;++i){var n=this.lines[i];this.height-=n.height;En(n);po(n,"delete")}this.lines.splice(e,t)},collapse:function(e){e.push.apply(e,this.lines)},insertInner:function(e,t,i){this.height+=i;this.lines=this.lines.slice(0,e).concat(t).concat(this.lines.slice(e));for(var r=0;r<t.length;++r)t[r].parent=this},iterN:function(e,t,i){for(var r=e+t;r>e;++e)if(i(this.lines[e]))return!0}};Mn.prototype={chunkSize:function(){return this.size},removeInner:function(e,t){this.size-=t;for(var i=0;i<this.children.length;++i){var r=this.children[i],n=r.chunkSize();if(n>e){var o=Math.min(t,n-e),s=r.height;r.removeInner(e,o);this.height-=s-r.height;if(n==o){this.children.splice(i--,1);r.parent=null}if(0==(t-=o))break;e=0}else e-=n}if(this.size-t<25&&(this.children.length>1||!(this.children[0]instanceof _n))){var a=[];this.collapse(a);this.children=[new _n(a)];this.children[0].parent=this}},collapse:function(e){for(var t=0;t<this.children.length;++t)this.children[t].collapse(e)},insertInner:function(e,t,i){this.size+=t.length;this.height+=i;for(var r=0;r<this.children.length;++r){var n=this.children[r],o=n.chunkSize();if(o>=e){n.insertInner(e,t,i);if(n.lines&&n.lines.length>50){for(;n.lines.length>50;){var s=n.lines.splice(n.lines.length-25,25),a=new _n(s);n.height-=a.height;this.children.splice(r+1,0,a);a.parent=this}this.maybeSpill()}break}e-=o}},maybeSpill:function(){if(!(this.children.length<=10)){var e=this;do{var t=e.children.splice(e.children.length-5,5),i=new Mn(t);if(e.parent){e.size-=i.size;e.height-=i.height;var r=Lo(e.parent.children,e);e.parent.children.splice(r+1,0,i)}else{var n=new Mn(e.children);n.parent=e;e.children=[n,i];e=n}i.parent=e.parent}while(e.children.length>10);e.parent.maybeSpill()}},iterN:function(e,t,i){for(var r=0;r<this.children.length;++r){var n=this.children[r],o=n.chunkSize();if(o>e){var s=Math.min(t,o-e);if(n.iterN(e,s,i))return!0;if(0==(t-=s))break;e=0}else e-=o}}};var la=0,ua=e.Doc=function(e,t,i){if(!(this instanceof ua))return new ua(e,t,i);null==i&&(i=0);Mn.call(this,[new _n([new oa("",null)])]);this.first=i;this.scrollTop=this.scrollLeft=0;this.cantEdit=!1;this.cleanGeneration=1;this.frontier=i;var r=Is(i,0);this.sel=J(r);this.history=new zn(null);this.id=++la;this.modeOption=t;"string"==typeof e&&(e=Ga(e));wn(this,{from:r,to:r,text:e});dt(this,J(r),La)};ua.prototype=Io(Mn.prototype,{constructor:ua,iter:function(e,t,i){i?this.iterN(e-this.first,t-e,i):this.iterN(this.first,this.first+this.size,e)},insert:function(e,t){for(var i=0,r=0;r<t.length;++r)i+=t[r].height;this.insertInner(e-this.first,t,i)},remove:function(e,t){this.removeInner(e-this.first,t)},getValue:function(e){var t=Vn(this,this.first,this.first+this.size);return e===!1?t:t.join(e||"\n")},setValue:mi(function(e){var t=Is(this.first,0),i=this.first+this.size-1;dr(this,{from:t,to:Is(i,Bn(this,i).text.length),text:Ga(e),origin:"setValue",full:!0},!0);dt(this,J(t))}),replaceRange:function(e,t,i,r){t=tt(this,t);i=i?tt(this,i):t;vr(this,e,t,i,r)},getRange:function(e,t,i){var r=Un(this,tt(this,e),tt(this,t));return i===!1?r:r.join(i||"\n")},getLine:function(e){var t=this.getLineHandle(e);return t&&t.text},getLineHandle:function(e){return rt(this,e)?Bn(this,e):void 0},getLineNumber:function(e){return Hn(e)},getLineHandleVisualStart:function(e){"number"==typeof e&&(e=Bn(this,e));return on(e)},lineCount:function(){return this.size},firstLine:function(){return this.first},lastLine:function(){return this.first+this.size-1},clipPos:function(e){return tt(this,e)},getCursor:function(e){var t,i=this.sel.primary();t=null==e||"head"==e?i.head:"anchor"==e?i.anchor:"end"==e||"to"==e||e===!1?i.to():i.from();return t},listSelections:function(){return this.sel.ranges},somethingSelected:function(){return this.sel.somethingSelected()},setCursor:mi(function(e,t,i){ut(this,tt(this,"number"==typeof e?Is(e,t||0):e),null,i)}),setSelection:mi(function(e,t,i){ut(this,tt(this,e),tt(this,t||e),i)}),extendSelection:mi(function(e,t,i){st(this,tt(this,e),t&&tt(this,t),i)}),extendSelections:mi(function(e,t){at(this,nt(this,e,t))}),extendSelectionsBy:mi(function(e,t){at(this,To(this.sel.ranges,e),t)}),setSelections:mi(function(e,t,i){if(e.length){for(var r=0,n=[];r<e.length;r++)n[r]=new Q(tt(this,e[r].anchor),tt(this,e[r].head));null==t&&(t=Math.min(e.length-1,this.sel.primIndex));dt(this,Z(n,t),i)}}),addSelection:mi(function(e,t,i){var r=this.sel.ranges.slice(0);r.push(new Q(tt(this,e),tt(this,t||e)));dt(this,Z(r,r.length-1),i)}),getSelection:function(e){for(var t,i=this.sel.ranges,r=0;r<i.length;r++){var n=Un(this,i[r].from(),i[r].to());t=t?t.concat(n):n}return e===!1?t:t.join(e||"\n")},getSelections:function(e){for(var t=[],i=this.sel.ranges,r=0;r<i.length;r++){var n=Un(this,i[r].from(),i[r].to());e!==!1&&(n=n.join(e||"\n"));t[r]=n}return t},replaceSelection:function(e,t,i){for(var r=[],n=0;n<this.sel.ranges.length;n++)r[n]=e;this.replaceSelections(r,t,i||"+input")},replaceSelections:mi(function(e,t,i){for(var r=[],n=this.sel,o=0;o<n.ranges.length;o++){var s=n.ranges[o];r[o]={from:s.from(),to:s.to(),text:Ga(e[o]),origin:i}}for(var a=t&&"end"!=t&&pr(this,r,t),o=r.length-1;o>=0;o--)dr(this,r[o]);a?ct(this,a):this.cm&&yr(this.cm)}),undo:mi(function(){hr(this,"undo")}),redo:mi(function(){hr(this,"redo")}),undoSelection:mi(function(){hr(this,"undo",!0)}),redoSelection:mi(function(){hr(this,"redo",!0)}),setExtending:function(e){this.extend=e},getExtending:function(){return this.extend},historySize:function(){for(var e=this.history,t=0,i=0,r=0;r<e.done.length;r++)e.done[r].ranges||++t;for(var r=0;r<e.undone.length;r++)e.undone[r].ranges||++i;return{undo:t,redo:i}},clearHistory:function(){this.history=new zn(this.history.maxGeneration)},markClean:function(){this.cleanGeneration=this.changeGeneration(!0)},changeGeneration:function(e){e&&(this.history.lastOp=this.history.lastSelOp=this.history.lastOrigin=null);return this.history.generation},isClean:function(e){return this.history.generation==(e||this.cleanGeneration)
},getHistory:function(){return{done:ro(this.history.done),undone:ro(this.history.undone)}},setHistory:function(e){var t=this.history=new zn(this.history.maxGeneration);t.done=ro(e.done.slice(0),null,!0);t.undone=ro(e.undone.slice(0),null,!0)},addLineClass:mi(function(e,t,i){return Cr(this,e,"gutter"==t?"gutter":"class",function(e){var r="text"==t?"textClass":"background"==t?"bgClass":"gutter"==t?"gutterClass":"wrapClass";if(e[r]){if(_o(i).test(e[r]))return!1;e[r]+=" "+i}else e[r]=i;return!0})}),removeLineClass:mi(function(e,t,i){return Cr(this,e,"gutter"==t?"gutter":"class",function(e){var r="text"==t?"textClass":"background"==t?"bgClass":"gutter"==t?"gutterClass":"wrapClass",n=e[r];if(!n)return!1;if(null==i)e[r]=null;else{var o=n.match(_o(i));if(!o)return!1;var s=o.index+o[0].length;e[r]=n.slice(0,o.index)+(o.index&&s!=n.length?" ":"")+n.slice(s)||null}return!0})}),markText:function(e,t,i){return _r(this,tt(this,e),tt(this,t),i,"range")},setBookmark:function(e,t){var i={replacedWith:t&&(null==t.nodeType?t.widget:t),insertLeft:t&&t.insertLeft,clearWhenEmpty:!1,shared:t&&t.shared};e=tt(this,e);return _r(this,e,e,i,"bookmark")},findMarksAt:function(e){e=tt(this,e);var t=[],i=Bn(this,e.line).markedSpans;if(i)for(var r=0;r<i.length;++r){var n=i[r];(null==n.from||n.from<=e.ch)&&(null==n.to||n.to>=e.ch)&&t.push(n.marker.parent||n.marker)}return t},findMarks:function(e,t,i){e=tt(this,e);t=tt(this,t);var r=[],n=e.line;this.iter(e.line,t.line+1,function(o){var s=o.markedSpans;if(s)for(var a=0;a<s.length;a++){var l=s[a];n==e.line&&e.ch>l.to||null==l.from&&n!=e.line||n==t.line&&l.from>t.ch||i&&!i(l.marker)||r.push(l.marker.parent||l.marker)}++n});return r},getAllMarks:function(){var e=[];this.iter(function(t){var i=t.markedSpans;if(i)for(var r=0;r<i.length;++r)null!=i[r].from&&e.push(i[r].marker)});return e},posFromIndex:function(e){var t,i=this.first;this.iter(function(r){var n=r.text.length+1;if(n>e){t=e;return!0}e-=n;++i});return tt(this,Is(i,t))},indexFromPos:function(e){e=tt(this,e);var t=e.ch;if(e.line<this.first||e.ch<0)return 0;this.iter(this.first,e.line,function(e){t+=e.text.length+1});return t},copy:function(e){var t=new ua(Vn(this,this.first,this.first+this.size),this.modeOption,this.first);t.scrollTop=this.scrollTop;t.scrollLeft=this.scrollLeft;t.sel=this.sel;t.extend=!1;if(e){t.history.undoDepth=this.history.undoDepth;t.setHistory(this.getHistory())}return t},linkedDoc:function(e){e||(e={});var t=this.first,i=this.first+this.size;null!=e.from&&e.from>t&&(t=e.from);null!=e.to&&e.to<i&&(i=e.to);var r=new ua(Vn(this,t,i),e.mode||this.modeOption,t);e.sharedHist&&(r.history=this.history);(this.linked||(this.linked=[])).push({doc:r,sharedHist:e.sharedHist});r.linked=[{doc:this,isParent:!0,sharedHist:e.sharedHist}];Gr(r,kr(this));return r},unlinkDoc:function(t){t instanceof e&&(t=t.doc);if(this.linked)for(var i=0;i<this.linked.length;++i){var r=this.linked[i];if(r.doc==t){this.linked.splice(i,1);t.unlinkDoc(this);Br(kr(this));break}}if(t.history==this.history){var n=[t.id];kn(t,function(e){n.push(e.id)},!0);t.history=new zn(null);t.history.done=ro(this.history.done,n);t.history.undone=ro(this.history.undone,n)}},iterLinkedDocs:function(e){kn(this,e)},getMode:function(){return this.mode},getEditor:function(){return this.cm}});ua.prototype.eachLine=ua.prototype.iter;var pa="iter insert remove copy getEditor".split(" ");for(var ca in ua.prototype)ua.prototype.hasOwnProperty(ca)&&Lo(pa,ca)<0&&(e.prototype[ca]=function(e){return function(){return e.apply(this.doc,arguments)}}(ua.prototype[ca]));mo(ua);var da=e.e_preventDefault=function(e){e.preventDefault?e.preventDefault():e.returnValue=!1},fa=e.e_stopPropagation=function(e){e.stopPropagation?e.stopPropagation():e.cancelBubble=!0},ha=e.e_stop=function(e){da(e);fa(e)},Ea=e.on=function(e,t,i){if(e.addEventListener)e.addEventListener(t,i,!1);else if(e.attachEvent)e.attachEvent("on"+t,i);else{var r=e._handlers||(e._handlers={}),n=r[t]||(r[t]=[]);n.push(i)}},ma=e.off=function(e,t,i){if(e.removeEventListener)e.removeEventListener(t,i,!1);else if(e.detachEvent)e.detachEvent("on"+t,i);else{var r=e._handlers&&e._handlers[t];if(!r)return;for(var n=0;n<r.length;++n)if(r[n]==i){r.splice(n,1);break}}},ga=e.signal=function(e,t){var i=e._handlers&&e._handlers[t];if(i)for(var r=Array.prototype.slice.call(arguments,2),n=0;n<i.length;++n)i[n].apply(null,r)},va=null,xa=30,Na=e.Pass={toString:function(){return"CodeMirror.Pass"}},La={scroll:!1},Ta={origin:"*mouse"},Ia={origin:"+move"};go.prototype.set=function(e,t){clearTimeout(this.id);this.id=setTimeout(t,e)};var ya=e.countColumn=function(e,t,i,r,n){if(null==t){t=e.search(/[^\s\u00a0]/);-1==t&&(t=e.length)}for(var o=r||0,s=n||0;;){var a=e.indexOf(" ",o);if(0>a||a>=t)return s+(t-o);s+=a-o;s+=i-s%i;o=a+1}},Aa=[""],Sa=function(e){e.select()};hs?Sa=function(e){e.selectionStart=0;e.selectionEnd=e.value.length}:ns&&(Sa=function(e){try{e.select()}catch(t){}});var Ca,Ra=/[\u00df\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/,ba=e.isWordChar=function(e){return/\w/.test(e)||e>""&&(e.toUpperCase()!=e.toLowerCase()||Ra.test(e))},Oa=/[\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]/;Ca=document.createRange?function(e,t,i){var r=document.createRange();r.setEnd(e,i);r.setStart(e,t);return r}:function(e,t,i){var r=document.body.createTextRange();try{r.moveToElementText(e.parentNode)}catch(n){return r}r.collapse(!0);r.moveEnd("character",i);r.moveStart("character",t);return r};ns&&11>os&&(wo=function(){try{return document.activeElement}catch(e){return document.body}});var Pa,Da,wa=e.rmClass=function(e,t){var i=e.className,r=_o(t).exec(i);if(r){var n=i.slice(r.index+r[0].length);e.className=i.slice(0,r.index)+(n?r[1]+n:"")}},_a=e.addClass=function(e,t){var i=e.className;_o(t).test(i)||(e.className+=(i?" ":"")+t)},Ma=!1,ka=function(){if(ns&&9>os)return!1;var e=bo("div");return"draggable"in e||"dragDrop"in e}(),Ga=e.splitLines=3!="\n\nb".split(/\n/).length?function(e){for(var t=0,i=[],r=e.length;r>=t;){var n=e.indexOf("\n",t);-1==n&&(n=e.length);var o=e.slice(t,"\r"==e.charAt(n-1)?n-1:n),s=o.indexOf("\r");if(-1!=s){i.push(o.slice(0,s));t+=s+1}else{i.push(o);t=n+1}}return i}:function(e){return e.split(/\r\n?|\n/)},Ba=window.getSelection?function(e){try{return e.selectionStart!=e.selectionEnd}catch(t){return!1}}:function(e){try{var t=e.ownerDocument.selection.createRange()}catch(i){}return t&&t.parentElement()==e?0!=t.compareEndPoints("StartToEnd",t):!1},Ua=function(){var e=bo("div");if("oncopy"in e)return!0;e.setAttribute("oncopy","return;");return"function"==typeof e.oncopy}(),Va=null,Fa={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",107:"=",109:"-",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"};e.keyNames=Fa;(function(){for(var e=0;10>e;e++)Fa[e+48]=Fa[e+96]=String(e);for(var e=65;90>=e;e++)Fa[e]=String.fromCharCode(e);for(var e=1;12>=e;e++)Fa[e+111]=Fa[e+63235]="F"+e})();var Ha,ja=function(){function e(e){return 247>=e?i.charAt(e):e>=1424&&1524>=e?"R":e>=1536&&1773>=e?r.charAt(e-1536):e>=1774&&2220>=e?"r":e>=8192&&8203>=e?"w":8204==e?"b":"L"}function t(e,t,i){this.level=e;this.from=t;this.to=i}var i="bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN",r="rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm",n=/[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/,o=/[stwN]/,s=/[LRr]/,a=/[Lb1n]/,l=/[1n]/,u="L";return function(i){if(!n.test(i))return!1;for(var r,p=i.length,c=[],d=0;p>d;++d)c.push(r=e(i.charCodeAt(d)));for(var d=0,f=u;p>d;++d){var r=c[d];"m"==r?c[d]=f:f=r}for(var d=0,h=u;p>d;++d){var r=c[d];if("1"==r&&"r"==h)c[d]="n";else if(s.test(r)){h=r;"r"==r&&(c[d]="R")}}for(var d=1,f=c[0];p-1>d;++d){var r=c[d];"+"==r&&"1"==f&&"1"==c[d+1]?c[d]="1":","!=r||f!=c[d+1]||"1"!=f&&"n"!=f||(c[d]=f);f=r}for(var d=0;p>d;++d){var r=c[d];if(","==r)c[d]="N";else if("%"==r){for(var E=d+1;p>E&&"%"==c[E];++E);for(var m=d&&"!"==c[d-1]||p>E&&"1"==c[E]?"1":"N",g=d;E>g;++g)c[g]=m;d=E-1}}for(var d=0,h=u;p>d;++d){var r=c[d];"L"==h&&"1"==r?c[d]="L":s.test(r)&&(h=r)}for(var d=0;p>d;++d)if(o.test(c[d])){for(var E=d+1;p>E&&o.test(c[E]);++E);for(var v="L"==(d?c[d-1]:u),x="L"==(p>E?c[E]:u),m=v||x?"L":"R",g=d;E>g;++g)c[g]=m;d=E-1}for(var N,L=[],d=0;p>d;)if(a.test(c[d])){var T=d;for(++d;p>d&&a.test(c[d]);++d);L.push(new t(0,T,d))}else{var I=d,y=L.length;for(++d;p>d&&"L"!=c[d];++d);for(var g=I;d>g;)if(l.test(c[g])){g>I&&L.splice(y,0,new t(1,I,g));var A=g;for(++g;d>g&&l.test(c[g]);++g);L.splice(y,0,new t(2,A,g));I=g}else++g;d>I&&L.splice(y,0,new t(1,I,d))}if(1==L[0].level&&(N=i.match(/^\s+/))){L[0].from=N[0].length;L.unshift(new t(0,0,N[0].length))}if(1==No(L).level&&(N=i.match(/\s+$/))){No(L).to-=N[0].length;L.push(new t(0,p-N[0].length,p))}L[0].level!=No(L).level&&L.push(new t(L[0].level,p,p));return L}}();e.version="4.12.0";return e})},{}],16:[function(t,i){(function(e,t){"object"==typeof i&&"object"==typeof i.exports?i.exports=e.document?t(e,!0):function(e){if(!e.document)throw new Error("jQuery requires a window with a document");return t(e)}:t(e)})("undefined"!=typeof window?window:this,function(t,i){function r(e){var t=e.length,i=ot.type(e);return"function"===i||ot.isWindow(e)?!1:1===e.nodeType&&t?!0:"array"===i||0===t||"number"==typeof t&&t>0&&t-1 in e}function n(e,t,i){if(ot.isFunction(t))return ot.grep(e,function(e,r){return!!t.call(e,r,e)!==i});if(t.nodeType)return ot.grep(e,function(e){return e===t!==i});if("string"==typeof t){if(ft.test(t))return ot.filter(t,e,i);t=ot.filter(t,e)}return ot.grep(e,function(e){return ot.inArray(e,t)>=0!==i})}function o(e,t){do e=e[t];while(e&&1!==e.nodeType);return e}function s(e){var t=Lt[e]={};ot.each(e.match(Nt)||[],function(e,i){t[i]=!0});return t}function a(){if(Et.addEventListener){Et.removeEventListener("DOMContentLoaded",l,!1);t.removeEventListener("load",l,!1)}else{Et.detachEvent("onreadystatechange",l);t.detachEvent("onload",l)}}function l(){if(Et.addEventListener||"load"===event.type||"complete"===Et.readyState){a();ot.ready()}}function u(e,t,i){if(void 0===i&&1===e.nodeType){var r="data-"+t.replace(St,"-$1").toLowerCase();i=e.getAttribute(r);if("string"==typeof i){try{i="true"===i?!0:"false"===i?!1:"null"===i?null:+i+""===i?+i:At.test(i)?ot.parseJSON(i):i}catch(n){}ot.data(e,t,i)}else i=void 0}return i}function p(e){var t;for(t in e)if(("data"!==t||!ot.isEmptyObject(e[t]))&&"toJSON"!==t)return!1;return!0}function c(e,t,i,r){if(ot.acceptData(e)){var n,o,s=ot.expando,a=e.nodeType,l=a?ot.cache:e,u=a?e[s]:e[s]&&s;if(u&&l[u]&&(r||l[u].data)||void 0!==i||"string"!=typeof t){u||(u=a?e[s]=K.pop()||ot.guid++:s);l[u]||(l[u]=a?{}:{toJSON:ot.noop});("object"==typeof t||"function"==typeof t)&&(r?l[u]=ot.extend(l[u],t):l[u].data=ot.extend(l[u].data,t));o=l[u];if(!r){o.data||(o.data={});o=o.data}void 0!==i&&(o[ot.camelCase(t)]=i);if("string"==typeof t){n=o[t];null==n&&(n=o[ot.camelCase(t)])}else n=o;return n}}}function d(e,t,i){if(ot.acceptData(e)){var r,n,o=e.nodeType,s=o?ot.cache:e,a=o?e[ot.expando]:ot.expando;if(s[a]){if(t){r=i?s[a]:s[a].data;if(r){if(ot.isArray(t))t=t.concat(ot.map(t,ot.camelCase));else if(t in r)t=[t];else{t=ot.camelCase(t);t=t in r?[t]:t.split(" ")}n=t.length;for(;n--;)delete r[t[n]];if(i?!p(r):!ot.isEmptyObject(r))return}}if(!i){delete s[a].data;if(!p(s[a]))return}o?ot.cleanData([e],!0):rt.deleteExpando||s!=s.window?delete s[a]:s[a]=null}}}function f(){return!0}function h(){return!1}function E(){try{return Et.activeElement}catch(e){}}function m(e){var t=Gt.split("|"),i=e.createDocumentFragment();if(i.createElement)for(;t.length;)i.createElement(t.pop());return i}function g(e,t){var i,r,n=0,o=typeof e.getElementsByTagName!==yt?e.getElementsByTagName(t||"*"):typeof e.querySelectorAll!==yt?e.querySelectorAll(t||"*"):void 0;if(!o)for(o=[],i=e.childNodes||e;null!=(r=i[n]);n++)!t||ot.nodeName(r,t)?o.push(r):ot.merge(o,g(r,t));return void 0===t||t&&ot.nodeName(e,t)?ot.merge([e],o):o}function v(e){Pt.test(e.type)&&(e.defaultChecked=e.checked)}function x(e,t){return ot.nodeName(e,"table")&&ot.nodeName(11!==t.nodeType?t:t.firstChild,"tr")?e.getElementsByTagName("tbody")[0]||e.appendChild(e.ownerDocument.createElement("tbody")):e}function N(e){e.type=(null!==ot.find.attr(e,"type"))+"/"+e.type;return e}function L(e){var t=Yt.exec(e.type);t?e.type=t[1]:e.removeAttribute("type");return e}function T(e,t){for(var i,r=0;null!=(i=e[r]);r++)ot._data(i,"globalEval",!t||ot._data(t[r],"globalEval"))}function I(e,t){if(1===t.nodeType&&ot.hasData(e)){var i,r,n,o=ot._data(e),s=ot._data(t,o),a=o.events;if(a){delete s.handle;s.events={};for(i in a)for(r=0,n=a[i].length;n>r;r++)ot.event.add(t,i,a[i][r])}s.data&&(s.data=ot.extend({},s.data))}}function y(e,t){var i,r,n;if(1===t.nodeType){i=t.nodeName.toLowerCase();if(!rt.noCloneEvent&&t[ot.expando]){n=ot._data(t);for(r in n.events)ot.removeEvent(t,r,n.handle);t.removeAttribute(ot.expando)}if("script"===i&&t.text!==e.text){N(t).text=e.text;L(t)}else if("object"===i){t.parentNode&&(t.outerHTML=e.outerHTML);rt.html5Clone&&e.innerHTML&&!ot.trim(t.innerHTML)&&(t.innerHTML=e.innerHTML)}else if("input"===i&&Pt.test(e.type)){t.defaultChecked=t.checked=e.checked;t.value!==e.value&&(t.value=e.value)}else"option"===i?t.defaultSelected=t.selected=e.defaultSelected:("input"===i||"textarea"===i)&&(t.defaultValue=e.defaultValue)}}function A(e,i){var r,n=ot(i.createElement(e)).appendTo(i.body),o=t.getDefaultComputedStyle&&(r=t.getDefaultComputedStyle(n[0]))?r.display:ot.css(n[0],"display");n.detach();return o}function S(e){var t=Et,i=ei[e];if(!i){i=A(e,t);if("none"===i||!i){Jt=(Jt||ot("<iframe frameborder='0' width='0' height='0'/>")).appendTo(t.documentElement);t=(Jt[0].contentWindow||Jt[0].contentDocument).document;t.write();t.close();i=A(e,t);Jt.detach()}ei[e]=i}return i}function C(e,t){return{get:function(){var i=e();if(null!=i){if(!i)return(this.get=t).apply(this,arguments);delete this.get}}}}function R(e,t){if(t in e)return t;for(var i=t.charAt(0).toUpperCase()+t.slice(1),r=t,n=fi.length;n--;){t=fi[n]+i;if(t in e)return t}return r}function b(e,t){for(var i,r,n,o=[],s=0,a=e.length;a>s;s++){r=e[s];if(r.style){o[s]=ot._data(r,"olddisplay");i=r.style.display;if(t){o[s]||"none"!==i||(r.style.display="");""===r.style.display&&bt(r)&&(o[s]=ot._data(r,"olddisplay",S(r.nodeName)))}else{n=bt(r);(i&&"none"!==i||!n)&&ot._data(r,"olddisplay",n?i:ot.css(r,"display"))}}}for(s=0;a>s;s++){r=e[s];r.style&&(t&&"none"!==r.style.display&&""!==r.style.display||(r.style.display=t?o[s]||"":"none"))}return e}function O(e,t,i){var r=ui.exec(t);return r?Math.max(0,r[1]-(i||0))+(r[2]||"px"):t}function P(e,t,i,r,n){for(var o=i===(r?"border":"content")?4:"width"===t?1:0,s=0;4>o;o+=2){"margin"===i&&(s+=ot.css(e,i+Rt[o],!0,n));if(r){"content"===i&&(s-=ot.css(e,"padding"+Rt[o],!0,n));"margin"!==i&&(s-=ot.css(e,"border"+Rt[o]+"Width",!0,n))}else{s+=ot.css(e,"padding"+Rt[o],!0,n);"padding"!==i&&(s+=ot.css(e,"border"+Rt[o]+"Width",!0,n))}}return s}function D(e,t,i){var r=!0,n="width"===t?e.offsetWidth:e.offsetHeight,o=ti(e),s=rt.boxSizing&&"border-box"===ot.css(e,"boxSizing",!1,o);if(0>=n||null==n){n=ii(e,t,o);(0>n||null==n)&&(n=e.style[t]);if(ni.test(n))return n;r=s&&(rt.boxSizingReliable()||n===e.style[t]);n=parseFloat(n)||0}return n+P(e,t,i||(s?"border":"content"),r,o)+"px"}function w(e,t,i,r,n){return new w.prototype.init(e,t,i,r,n)}function _(){setTimeout(function(){hi=void 0});return hi=ot.now()}function M(e,t){var i,r={height:e},n=0;t=t?1:0;for(;4>n;n+=2-t){i=Rt[n];r["margin"+i]=r["padding"+i]=e}t&&(r.opacity=r.width=e);return r}function k(e,t,i){for(var r,n=(Ni[t]||[]).concat(Ni["*"]),o=0,s=n.length;s>o;o++)if(r=n[o].call(i,t,e))return r}function G(e,t,i){var r,n,o,s,a,l,u,p,c=this,d={},f=e.style,h=e.nodeType&&bt(e),E=ot._data(e,"fxshow");if(!i.queue){a=ot._queueHooks(e,"fx");if(null==a.unqueued){a.unqueued=0;l=a.empty.fire;a.empty.fire=function(){a.unqueued||l()}}a.unqueued++;c.always(function(){c.always(function(){a.unqueued--;ot.queue(e,"fx").length||a.empty.fire()})})}if(1===e.nodeType&&("height"in t||"width"in t)){i.overflow=[f.overflow,f.overflowX,f.overflowY];u=ot.css(e,"display");p="none"===u?ot._data(e,"olddisplay")||S(e.nodeName):u;"inline"===p&&"none"===ot.css(e,"float")&&(rt.inlineBlockNeedsLayout&&"inline"!==S(e.nodeName)?f.zoom=1:f.display="inline-block")}if(i.overflow){f.overflow="hidden";rt.shrinkWrapBlocks()||c.always(function(){f.overflow=i.overflow[0];f.overflowX=i.overflow[1];f.overflowY=i.overflow[2]})}for(r in t){n=t[r];if(mi.exec(n)){delete t[r];o=o||"toggle"===n;if(n===(h?"hide":"show")){if("show"!==n||!E||void 0===E[r])continue;h=!0}d[r]=E&&E[r]||ot.style(e,r)}else u=void 0}if(ot.isEmptyObject(d))"inline"===("none"===u?S(e.nodeName):u)&&(f.display=u);else{E?"hidden"in E&&(h=E.hidden):E=ot._data(e,"fxshow",{});o&&(E.hidden=!h);h?ot(e).show():c.done(function(){ot(e).hide()});c.done(function(){var t;ot._removeData(e,"fxshow");for(t in d)ot.style(e,t,d[t])});for(r in d){s=k(h?E[r]:0,r,c);if(!(r in E)){E[r]=s.start;if(h){s.end=s.start;s.start="width"===r||"height"===r?1:0}}}}}function B(e,t){var i,r,n,o,s;for(i in e){r=ot.camelCase(i);n=t[r];o=e[i];if(ot.isArray(o)){n=o[1];o=e[i]=o[0]}if(i!==r){e[r]=o;delete e[i]}s=ot.cssHooks[r];if(s&&"expand"in s){o=s.expand(o);delete e[r];for(i in o)if(!(i in e)){e[i]=o[i];t[i]=n}}else t[r]=n}}function U(e,t,i){var r,n,o=0,s=xi.length,a=ot.Deferred().always(function(){delete l.elem}),l=function(){if(n)return!1;for(var t=hi||_(),i=Math.max(0,u.startTime+u.duration-t),r=i/u.duration||0,o=1-r,s=0,l=u.tweens.length;l>s;s++)u.tweens[s].run(o);a.notifyWith(e,[u,o,i]);if(1>o&&l)return i;a.resolveWith(e,[u]);return!1},u=a.promise({elem:e,props:ot.extend({},t),opts:ot.extend(!0,{specialEasing:{}},i),originalProperties:t,originalOptions:i,startTime:hi||_(),duration:i.duration,tweens:[],createTween:function(t,i){var r=ot.Tween(e,u.opts,t,i,u.opts.specialEasing[t]||u.opts.easing);u.tweens.push(r);return r},stop:function(t){var i=0,r=t?u.tweens.length:0;if(n)return this;n=!0;for(;r>i;i++)u.tweens[i].run(1);t?a.resolveWith(e,[u,t]):a.rejectWith(e,[u,t]);return this}}),p=u.props;B(p,u.opts.specialEasing);for(;s>o;o++){r=xi[o].call(u,e,p,u.opts);if(r)return r}ot.map(p,k,u);ot.isFunction(u.opts.start)&&u.opts.start.call(e,u);ot.fx.timer(ot.extend(l,{elem:e,anim:u,queue:u.opts.queue}));return u.progress(u.opts.progress).done(u.opts.done,u.opts.complete).fail(u.opts.fail).always(u.opts.always)}function V(e){return function(t,i){if("string"!=typeof t){i=t;t="*"}var r,n=0,o=t.toLowerCase().match(Nt)||[];if(ot.isFunction(i))for(;r=o[n++];)if("+"===r.charAt(0)){r=r.slice(1)||"*";(e[r]=e[r]||[]).unshift(i)}else(e[r]=e[r]||[]).push(i)}}function F(e,t,i,r){function n(a){var l;o[a]=!0;ot.each(e[a]||[],function(e,a){var u=a(t,i,r);if("string"==typeof u&&!s&&!o[u]){t.dataTypes.unshift(u);n(u);return!1}return s?!(l=u):void 0});return l}var o={},s=e===Wi;return n(t.dataTypes[0])||!o["*"]&&n("*")}function H(e,t){var i,r,n=ot.ajaxSettings.flatOptions||{};for(r in t)void 0!==t[r]&&((n[r]?e:i||(i={}))[r]=t[r]);i&&ot.extend(!0,e,i);return e}function j(e,t,i){for(var r,n,o,s,a=e.contents,l=e.dataTypes;"*"===l[0];){l.shift();void 0===n&&(n=e.mimeType||t.getResponseHeader("Content-Type"))}if(n)for(s in a)if(a[s]&&a[s].test(n)){l.unshift(s);break}if(l[0]in i)o=l[0];else{for(s in i){if(!l[0]||e.converters[s+" "+l[0]]){o=s;break}r||(r=s)}o=o||r}if(o){o!==l[0]&&l.unshift(o);return i[o]}}function W(e,t,i,r){var n,o,s,a,l,u={},p=e.dataTypes.slice();if(p[1])for(s in e.converters)u[s.toLowerCase()]=e.converters[s];o=p.shift();for(;o;){e.responseFields[o]&&(i[e.responseFields[o]]=t);!l&&r&&e.dataFilter&&(t=e.dataFilter(t,e.dataType));l=o;o=p.shift();if(o)if("*"===o)o=l;else if("*"!==l&&l!==o){s=u[l+" "+o]||u["* "+o];if(!s)for(n in u){a=n.split(" ");if(a[1]===o){s=u[l+" "+a[0]]||u["* "+a[0]];if(s){if(s===!0)s=u[n];else if(u[n]!==!0){o=a[0];p.unshift(a[1])}break}}}if(s!==!0)if(s&&e["throws"])t=s(t);else try{t=s(t)}catch(c){return{state:"parsererror",error:s?c:"No conversion from "+l+" to "+o}}}}return{state:"success",data:t}}function q(e,t,i,r){var n;if(ot.isArray(t))ot.each(t,function(t,n){i||Yi.test(e)?r(e,n):q(e+"["+("object"==typeof n?t:"")+"]",n,i,r)});else if(i||"object"!==ot.type(t))r(e,t);else for(n in t)q(e+"["+n+"]",t[n],i,r)}function z(){try{return new t.XMLHttpRequest}catch(e){}}function X(){try{return new t.ActiveXObject("Microsoft.XMLHTTP")}catch(e){}}function Y(e){return ot.isWindow(e)?e:9===e.nodeType?e.defaultView||e.parentWindow:!1}var K=[],$=K.slice,Q=K.concat,Z=K.push,J=K.indexOf,et={},tt=et.toString,it=et.hasOwnProperty,rt={},nt="1.11.2",ot=function(e,t){return new ot.fn.init(e,t)},st=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,at=/^-ms-/,lt=/-([\da-z])/gi,ut=function(e,t){return t.toUpperCase()};ot.fn=ot.prototype={jquery:nt,constructor:ot,selector:"",length:0,toArray:function(){return $.call(this)},get:function(e){return null!=e?0>e?this[e+this.length]:this[e]:$.call(this)},pushStack:function(e){var t=ot.merge(this.constructor(),e);t.prevObject=this;t.context=this.context;return t},each:function(e,t){return ot.each(this,e,t)},map:function(e){return this.pushStack(ot.map(this,function(t,i){return e.call(t,i,t)}))},slice:function(){return this.pushStack($.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(e){var t=this.length,i=+e+(0>e?t:0);return this.pushStack(i>=0&&t>i?[this[i]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:Z,sort:K.sort,splice:K.splice};ot.extend=ot.fn.extend=function(){var e,t,i,r,n,o,s=arguments[0]||{},a=1,l=arguments.length,u=!1;if("boolean"==typeof s){u=s;s=arguments[a]||{};a++}"object"==typeof s||ot.isFunction(s)||(s={});if(a===l){s=this;a--}for(;l>a;a++)if(null!=(n=arguments[a]))for(r in n){e=s[r];i=n[r];if(s!==i)if(u&&i&&(ot.isPlainObject(i)||(t=ot.isArray(i)))){if(t){t=!1;o=e&&ot.isArray(e)?e:[]}else o=e&&ot.isPlainObject(e)?e:{};s[r]=ot.extend(u,o,i)}else void 0!==i&&(s[r]=i)}return s};ot.extend({expando:"jQuery"+(nt+Math.random()).replace(/\D/g,""),isReady:!0,error:function(e){throw new Error(e)},noop:function(){},isFunction:function(e){return"function"===ot.type(e)},isArray:Array.isArray||function(e){return"array"===ot.type(e)},isWindow:function(e){return null!=e&&e==e.window},isNumeric:function(e){return!ot.isArray(e)&&e-parseFloat(e)+1>=0},isEmptyObject:function(e){var t;for(t in e)return!1;return!0},isPlainObject:function(e){var t;if(!e||"object"!==ot.type(e)||e.nodeType||ot.isWindow(e))return!1;try{if(e.constructor&&!it.call(e,"constructor")&&!it.call(e.constructor.prototype,"isPrototypeOf"))return!1}catch(i){return!1}if(rt.ownLast)for(t in e)return it.call(e,t);for(t in e);return void 0===t||it.call(e,t)},type:function(e){return null==e?e+"":"object"==typeof e||"function"==typeof e?et[tt.call(e)]||"object":typeof e},globalEval:function(e){e&&ot.trim(e)&&(t.execScript||function(e){t.eval.call(t,e)})(e)},camelCase:function(e){return e.replace(at,"ms-").replace(lt,ut)},nodeName:function(e,t){return e.nodeName&&e.nodeName.toLowerCase()===t.toLowerCase()},each:function(e,t,i){var n,o=0,s=e.length,a=r(e);if(i)if(a)for(;s>o;o++){n=t.apply(e[o],i);if(n===!1)break}else for(o in e){n=t.apply(e[o],i);if(n===!1)break}else if(a)for(;s>o;o++){n=t.call(e[o],o,e[o]);if(n===!1)break}else for(o in e){n=t.call(e[o],o,e[o]);if(n===!1)break}return e},trim:function(e){return null==e?"":(e+"").replace(st,"")},makeArray:function(e,t){var i=t||[];null!=e&&(r(Object(e))?ot.merge(i,"string"==typeof e?[e]:e):Z.call(i,e));return i},inArray:function(e,t,i){var r;if(t){if(J)return J.call(t,e,i);r=t.length;i=i?0>i?Math.max(0,r+i):i:0;for(;r>i;i++)if(i in t&&t[i]===e)return i}return-1},merge:function(e,t){for(var i=+t.length,r=0,n=e.length;i>r;)e[n++]=t[r++];if(i!==i)for(;void 0!==t[r];)e[n++]=t[r++];e.length=n;return e},grep:function(e,t,i){for(var r,n=[],o=0,s=e.length,a=!i;s>o;o++){r=!t(e[o],o);r!==a&&n.push(e[o])}return n},map:function(e,t,i){var n,o=0,s=e.length,a=r(e),l=[];if(a)for(;s>o;o++){n=t(e[o],o,i);null!=n&&l.push(n)}else for(o in e){n=t(e[o],o,i);null!=n&&l.push(n)}return Q.apply([],l)},guid:1,proxy:function(e,t){var i,r,n;if("string"==typeof t){n=e[t];t=e;e=n}if(!ot.isFunction(e))return void 0;i=$.call(arguments,2);r=function(){return e.apply(t||this,i.concat($.call(arguments)))};r.guid=e.guid=e.guid||ot.guid++;return r},now:function(){return+new Date},support:rt});ot.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(e,t){et["[object "+t+"]"]=t.toLowerCase()});var pt=function(e){function t(e,t,i,r){var n,o,s,a,l,u,c,f,h,E;(t?t.ownerDocument||t:V)!==D&&P(t);t=t||D;i=i||[];a=t.nodeType;if("string"!=typeof e||!e||1!==a&&9!==a&&11!==a)return i;if(!r&&_){if(11!==a&&(n=vt.exec(e)))if(s=n[1]){if(9===a){o=t.getElementById(s);if(!o||!o.parentNode)return i;if(o.id===s){i.push(o);return i}}else if(t.ownerDocument&&(o=t.ownerDocument.getElementById(s))&&B(t,o)&&o.id===s){i.push(o);return i}}else{if(n[2]){Z.apply(i,t.getElementsByTagName(e));return i}if((s=n[3])&&L.getElementsByClassName){Z.apply(i,t.getElementsByClassName(s));return i}}if(L.qsa&&(!M||!M.test(e))){f=c=U;h=t;E=1!==a&&e;if(1===a&&"object"!==t.nodeName.toLowerCase()){u=A(e);(c=t.getAttribute("id"))?f=c.replace(Nt,"\\$&"):t.setAttribute("id",f);f="[id='"+f+"'] ";l=u.length;for(;l--;)u[l]=f+d(u[l]);h=xt.test(e)&&p(t.parentNode)||t;E=u.join(",")}if(E)try{Z.apply(i,h.querySelectorAll(E));return i}catch(m){}finally{c||t.removeAttribute("id")}}}return C(e.replace(lt,"$1"),t,i,r)}function i(){function e(i,r){t.push(i+" ")>T.cacheLength&&delete e[t.shift()];return e[i+" "]=r}var t=[];return e}function r(e){e[U]=!0;return e}function n(e){var t=D.createElement("div");try{return!!e(t)}catch(i){return!1}finally{t.parentNode&&t.parentNode.removeChild(t);t=null}}function o(e,t){for(var i=e.split("|"),r=e.length;r--;)T.attrHandle[i[r]]=t}function s(e,t){var i=t&&e,r=i&&1===e.nodeType&&1===t.nodeType&&(~t.sourceIndex||X)-(~e.sourceIndex||X);if(r)return r;if(i)for(;i=i.nextSibling;)if(i===t)return-1;return e?1:-1}function a(e){return function(t){var i=t.nodeName.toLowerCase();return"input"===i&&t.type===e}}function l(e){return function(t){var i=t.nodeName.toLowerCase();return("input"===i||"button"===i)&&t.type===e}}function u(e){return r(function(t){t=+t;return r(function(i,r){for(var n,o=e([],i.length,t),s=o.length;s--;)i[n=o[s]]&&(i[n]=!(r[n]=i[n]))})})}function p(e){return e&&"undefined"!=typeof e.getElementsByTagName&&e}function c(){}function d(e){for(var t=0,i=e.length,r="";i>t;t++)r+=e[t].value;return r}function f(e,t,i){var r=t.dir,n=i&&"parentNode"===r,o=H++;return t.first?function(t,i,o){for(;t=t[r];)if(1===t.nodeType||n)return e(t,i,o)}:function(t,i,s){var a,l,u=[F,o];if(s){for(;t=t[r];)if((1===t.nodeType||n)&&e(t,i,s))return!0}else for(;t=t[r];)if(1===t.nodeType||n){l=t[U]||(t[U]={});if((a=l[r])&&a[0]===F&&a[1]===o)return u[2]=a[2];l[r]=u;if(u[2]=e(t,i,s))return!0}}}function h(e){return e.length>1?function(t,i,r){for(var n=e.length;n--;)if(!e[n](t,i,r))return!1;return!0}:e[0]}function E(e,i,r){for(var n=0,o=i.length;o>n;n++)t(e,i[n],r);return r}function m(e,t,i,r,n){for(var o,s=[],a=0,l=e.length,u=null!=t;l>a;a++)if((o=e[a])&&(!i||i(o,r,n))){s.push(o);u&&t.push(a)}return s}function g(e,t,i,n,o,s){n&&!n[U]&&(n=g(n));o&&!o[U]&&(o=g(o,s));return r(function(r,s,a,l){var u,p,c,d=[],f=[],h=s.length,g=r||E(t||"*",a.nodeType?[a]:a,[]),v=!e||!r&&t?g:m(g,d,e,a,l),x=i?o||(r?e:h||n)?[]:s:v;i&&i(v,x,a,l);if(n){u=m(x,f);n(u,[],a,l);p=u.length;for(;p--;)(c=u[p])&&(x[f[p]]=!(v[f[p]]=c))}if(r){if(o||e){if(o){u=[];p=x.length;for(;p--;)(c=x[p])&&u.push(v[p]=c);o(null,x=[],u,l)}p=x.length;for(;p--;)(c=x[p])&&(u=o?et(r,c):d[p])>-1&&(r[u]=!(s[u]=c))}}else{x=m(x===s?x.splice(h,x.length):x);o?o(null,s,x,l):Z.apply(s,x)}})}function v(e){for(var t,i,r,n=e.length,o=T.relative[e[0].type],s=o||T.relative[" "],a=o?1:0,l=f(function(e){return e===t},s,!0),u=f(function(e){return et(t,e)>-1},s,!0),p=[function(e,i,r){var n=!o&&(r||i!==R)||((t=i).nodeType?l(e,i,r):u(e,i,r));t=null;return n}];n>a;a++)if(i=T.relative[e[a].type])p=[f(h(p),i)];else{i=T.filter[e[a].type].apply(null,e[a].matches);if(i[U]){r=++a;for(;n>r&&!T.relative[e[r].type];r++);return g(a>1&&h(p),a>1&&d(e.slice(0,a-1).concat({value:" "===e[a-2].type?"*":""})).replace(lt,"$1"),i,r>a&&v(e.slice(a,r)),n>r&&v(e=e.slice(r)),n>r&&d(e))}p.push(i)}return h(p)}function x(e,i){var n=i.length>0,o=e.length>0,s=function(r,s,a,l,u){var p,c,d,f=0,h="0",E=r&&[],g=[],v=R,x=r||o&&T.find.TAG("*",u),N=F+=null==v?1:Math.random()||.1,L=x.length;u&&(R=s!==D&&s);for(;h!==L&&null!=(p=x[h]);h++){if(o&&p){c=0;for(;d=e[c++];)if(d(p,s,a)){l.push(p);break}u&&(F=N)}if(n){(p=!d&&p)&&f--;r&&E.push(p)}}f+=h;if(n&&h!==f){c=0;for(;d=i[c++];)d(E,g,s,a);if(r){if(f>0)for(;h--;)E[h]||g[h]||(g[h]=$.call(l));g=m(g)}Z.apply(l,g);u&&!r&&g.length>0&&f+i.length>1&&t.uniqueSort(l)}if(u){F=N;R=v}return E};return n?r(s):s}var N,L,T,I,y,A,S,C,R,b,O,P,D,w,_,M,k,G,B,U="sizzle"+1*new Date,V=e.document,F=0,H=0,j=i(),W=i(),q=i(),z=function(e,t){e===t&&(O=!0);return 0},X=1<<31,Y={}.hasOwnProperty,K=[],$=K.pop,Q=K.push,Z=K.push,J=K.slice,et=function(e,t){for(var i=0,r=e.length;r>i;i++)if(e[i]===t)return i;return-1},tt="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",it="[\\x20\\t\\r\\n\\f]",rt="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",nt=rt.replace("w","w#"),ot="\\["+it+"*("+rt+")(?:"+it+"*([*^$|!~]?=)"+it+"*(?:'((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\"|("+nt+"))|)"+it+"*\\]",st=":("+rt+")(?:\\((('((?:\\\\.|[^\\\\'])*)'|\"((?:\\\\.|[^\\\\\"])*)\")|((?:\\\\.|[^\\\\()[\\]]|"+ot+")*)|.*)\\)|)",at=new RegExp(it+"+","g"),lt=new RegExp("^"+it+"+|((?:^|[^\\\\])(?:\\\\.)*)"+it+"+$","g"),ut=new RegExp("^"+it+"*,"+it+"*"),pt=new RegExp("^"+it+"*([>+~]|"+it+")"+it+"*"),ct=new RegExp("="+it+"*([^\\]'\"]*?)"+it+"*\\]","g"),dt=new RegExp(st),ft=new RegExp("^"+nt+"$"),ht={ID:new RegExp("^#("+rt+")"),CLASS:new RegExp("^\\.("+rt+")"),TAG:new RegExp("^("+rt.replace("w","w*")+")"),ATTR:new RegExp("^"+ot),PSEUDO:new RegExp("^"+st),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+it+"*(even|odd|(([+-]|)(\\d*)n|)"+it+"*(?:([+-]|)"+it+"*(\\d+)|))"+it+"*\\)|)","i"),bool:new RegExp("^(?:"+tt+")$","i"),needsContext:new RegExp("^"+it+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+it+"*((?:-\\d)?\\d*)"+it+"*\\)|)(?=[^-]|$)","i")},Et=/^(?:input|select|textarea|button)$/i,mt=/^h\d$/i,gt=/^[^{]+\{\s*\[native \w/,vt=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,xt=/[+~]/,Nt=/'|\\/g,Lt=new RegExp("\\\\([\\da-f]{1,6}"+it+"?|("+it+")|.)","ig"),Tt=function(e,t,i){var r="0x"+t-65536;
return r!==r||i?t:0>r?String.fromCharCode(r+65536):String.fromCharCode(r>>10|55296,1023&r|56320)},It=function(){P()};try{Z.apply(K=J.call(V.childNodes),V.childNodes);K[V.childNodes.length].nodeType}catch(yt){Z={apply:K.length?function(e,t){Q.apply(e,J.call(t))}:function(e,t){for(var i=e.length,r=0;e[i++]=t[r++];);e.length=i-1}}}L=t.support={};y=t.isXML=function(e){var t=e&&(e.ownerDocument||e).documentElement;return t?"HTML"!==t.nodeName:!1};P=t.setDocument=function(e){var t,i,r=e?e.ownerDocument||e:V;if(r===D||9!==r.nodeType||!r.documentElement)return D;D=r;w=r.documentElement;i=r.defaultView;i&&i!==i.top&&(i.addEventListener?i.addEventListener("unload",It,!1):i.attachEvent&&i.attachEvent("onunload",It));_=!y(r);L.attributes=n(function(e){e.className="i";return!e.getAttribute("className")});L.getElementsByTagName=n(function(e){e.appendChild(r.createComment(""));return!e.getElementsByTagName("*").length});L.getElementsByClassName=gt.test(r.getElementsByClassName);L.getById=n(function(e){w.appendChild(e).id=U;return!r.getElementsByName||!r.getElementsByName(U).length});if(L.getById){T.find.ID=function(e,t){if("undefined"!=typeof t.getElementById&&_){var i=t.getElementById(e);return i&&i.parentNode?[i]:[]}};T.filter.ID=function(e){var t=e.replace(Lt,Tt);return function(e){return e.getAttribute("id")===t}}}else{delete T.find.ID;T.filter.ID=function(e){var t=e.replace(Lt,Tt);return function(e){var i="undefined"!=typeof e.getAttributeNode&&e.getAttributeNode("id");return i&&i.value===t}}}T.find.TAG=L.getElementsByTagName?function(e,t){return"undefined"!=typeof t.getElementsByTagName?t.getElementsByTagName(e):L.qsa?t.querySelectorAll(e):void 0}:function(e,t){var i,r=[],n=0,o=t.getElementsByTagName(e);if("*"===e){for(;i=o[n++];)1===i.nodeType&&r.push(i);return r}return o};T.find.CLASS=L.getElementsByClassName&&function(e,t){return _?t.getElementsByClassName(e):void 0};k=[];M=[];if(L.qsa=gt.test(r.querySelectorAll)){n(function(e){w.appendChild(e).innerHTML="<a id='"+U+"'></a><select id='"+U+"-\f]' msallowcapture=''><option selected=''></option></select>";e.querySelectorAll("[msallowcapture^='']").length&&M.push("[*^$]="+it+"*(?:''|\"\")");e.querySelectorAll("[selected]").length||M.push("\\["+it+"*(?:value|"+tt+")");e.querySelectorAll("[id~="+U+"-]").length||M.push("~=");e.querySelectorAll(":checked").length||M.push(":checked");e.querySelectorAll("a#"+U+"+*").length||M.push(".#.+[+~]")});n(function(e){var t=r.createElement("input");t.setAttribute("type","hidden");e.appendChild(t).setAttribute("name","D");e.querySelectorAll("[name=d]").length&&M.push("name"+it+"*[*^$|!~]?=");e.querySelectorAll(":enabled").length||M.push(":enabled",":disabled");e.querySelectorAll("*,:x");M.push(",.*:")})}(L.matchesSelector=gt.test(G=w.matches||w.webkitMatchesSelector||w.mozMatchesSelector||w.oMatchesSelector||w.msMatchesSelector))&&n(function(e){L.disconnectedMatch=G.call(e,"div");G.call(e,"[s!='']:x");k.push("!=",st)});M=M.length&&new RegExp(M.join("|"));k=k.length&&new RegExp(k.join("|"));t=gt.test(w.compareDocumentPosition);B=t||gt.test(w.contains)?function(e,t){var i=9===e.nodeType?e.documentElement:e,r=t&&t.parentNode;return e===r||!(!r||1!==r.nodeType||!(i.contains?i.contains(r):e.compareDocumentPosition&&16&e.compareDocumentPosition(r)))}:function(e,t){if(t)for(;t=t.parentNode;)if(t===e)return!0;return!1};z=t?function(e,t){if(e===t){O=!0;return 0}var i=!e.compareDocumentPosition-!t.compareDocumentPosition;if(i)return i;i=(e.ownerDocument||e)===(t.ownerDocument||t)?e.compareDocumentPosition(t):1;return 1&i||!L.sortDetached&&t.compareDocumentPosition(e)===i?e===r||e.ownerDocument===V&&B(V,e)?-1:t===r||t.ownerDocument===V&&B(V,t)?1:b?et(b,e)-et(b,t):0:4&i?-1:1}:function(e,t){if(e===t){O=!0;return 0}var i,n=0,o=e.parentNode,a=t.parentNode,l=[e],u=[t];if(!o||!a)return e===r?-1:t===r?1:o?-1:a?1:b?et(b,e)-et(b,t):0;if(o===a)return s(e,t);i=e;for(;i=i.parentNode;)l.unshift(i);i=t;for(;i=i.parentNode;)u.unshift(i);for(;l[n]===u[n];)n++;return n?s(l[n],u[n]):l[n]===V?-1:u[n]===V?1:0};return r};t.matches=function(e,i){return t(e,null,null,i)};t.matchesSelector=function(e,i){(e.ownerDocument||e)!==D&&P(e);i=i.replace(ct,"='$1']");if(!(!L.matchesSelector||!_||k&&k.test(i)||M&&M.test(i)))try{var r=G.call(e,i);if(r||L.disconnectedMatch||e.document&&11!==e.document.nodeType)return r}catch(n){}return t(i,D,null,[e]).length>0};t.contains=function(e,t){(e.ownerDocument||e)!==D&&P(e);return B(e,t)};t.attr=function(e,t){(e.ownerDocument||e)!==D&&P(e);var i=T.attrHandle[t.toLowerCase()],r=i&&Y.call(T.attrHandle,t.toLowerCase())?i(e,t,!_):void 0;return void 0!==r?r:L.attributes||!_?e.getAttribute(t):(r=e.getAttributeNode(t))&&r.specified?r.value:null};t.error=function(e){throw new Error("Syntax error, unrecognized expression: "+e)};t.uniqueSort=function(e){var t,i=[],r=0,n=0;O=!L.detectDuplicates;b=!L.sortStable&&e.slice(0);e.sort(z);if(O){for(;t=e[n++];)t===e[n]&&(r=i.push(n));for(;r--;)e.splice(i[r],1)}b=null;return e};I=t.getText=function(e){var t,i="",r=0,n=e.nodeType;if(n){if(1===n||9===n||11===n){if("string"==typeof e.textContent)return e.textContent;for(e=e.firstChild;e;e=e.nextSibling)i+=I(e)}else if(3===n||4===n)return e.nodeValue}else for(;t=e[r++];)i+=I(t);return i};T=t.selectors={cacheLength:50,createPseudo:r,match:ht,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(e){e[1]=e[1].replace(Lt,Tt);e[3]=(e[3]||e[4]||e[5]||"").replace(Lt,Tt);"~="===e[2]&&(e[3]=" "+e[3]+" ");return e.slice(0,4)},CHILD:function(e){e[1]=e[1].toLowerCase();if("nth"===e[1].slice(0,3)){e[3]||t.error(e[0]);e[4]=+(e[4]?e[5]+(e[6]||1):2*("even"===e[3]||"odd"===e[3]));e[5]=+(e[7]+e[8]||"odd"===e[3])}else e[3]&&t.error(e[0]);return e},PSEUDO:function(e){var t,i=!e[6]&&e[2];if(ht.CHILD.test(e[0]))return null;if(e[3])e[2]=e[4]||e[5]||"";else if(i&&dt.test(i)&&(t=A(i,!0))&&(t=i.indexOf(")",i.length-t)-i.length)){e[0]=e[0].slice(0,t);e[2]=i.slice(0,t)}return e.slice(0,3)}},filter:{TAG:function(e){var t=e.replace(Lt,Tt).toLowerCase();return"*"===e?function(){return!0}:function(e){return e.nodeName&&e.nodeName.toLowerCase()===t}},CLASS:function(e){var t=j[e+" "];return t||(t=new RegExp("(^|"+it+")"+e+"("+it+"|$)"))&&j(e,function(e){return t.test("string"==typeof e.className&&e.className||"undefined"!=typeof e.getAttribute&&e.getAttribute("class")||"")})},ATTR:function(e,i,r){return function(n){var o=t.attr(n,e);if(null==o)return"!="===i;if(!i)return!0;o+="";return"="===i?o===r:"!="===i?o!==r:"^="===i?r&&0===o.indexOf(r):"*="===i?r&&o.indexOf(r)>-1:"$="===i?r&&o.slice(-r.length)===r:"~="===i?(" "+o.replace(at," ")+" ").indexOf(r)>-1:"|="===i?o===r||o.slice(0,r.length+1)===r+"-":!1}},CHILD:function(e,t,i,r,n){var o="nth"!==e.slice(0,3),s="last"!==e.slice(-4),a="of-type"===t;return 1===r&&0===n?function(e){return!!e.parentNode}:function(t,i,l){var u,p,c,d,f,h,E=o!==s?"nextSibling":"previousSibling",m=t.parentNode,g=a&&t.nodeName.toLowerCase(),v=!l&&!a;if(m){if(o){for(;E;){c=t;for(;c=c[E];)if(a?c.nodeName.toLowerCase()===g:1===c.nodeType)return!1;h=E="only"===e&&!h&&"nextSibling"}return!0}h=[s?m.firstChild:m.lastChild];if(s&&v){p=m[U]||(m[U]={});u=p[e]||[];f=u[0]===F&&u[1];d=u[0]===F&&u[2];c=f&&m.childNodes[f];for(;c=++f&&c&&c[E]||(d=f=0)||h.pop();)if(1===c.nodeType&&++d&&c===t){p[e]=[F,f,d];break}}else if(v&&(u=(t[U]||(t[U]={}))[e])&&u[0]===F)d=u[1];else for(;c=++f&&c&&c[E]||(d=f=0)||h.pop();)if((a?c.nodeName.toLowerCase()===g:1===c.nodeType)&&++d){v&&((c[U]||(c[U]={}))[e]=[F,d]);if(c===t)break}d-=n;return d===r||d%r===0&&d/r>=0}}},PSEUDO:function(e,i){var n,o=T.pseudos[e]||T.setFilters[e.toLowerCase()]||t.error("unsupported pseudo: "+e);if(o[U])return o(i);if(o.length>1){n=[e,e,"",i];return T.setFilters.hasOwnProperty(e.toLowerCase())?r(function(e,t){for(var r,n=o(e,i),s=n.length;s--;){r=et(e,n[s]);e[r]=!(t[r]=n[s])}}):function(e){return o(e,0,n)}}return o}},pseudos:{not:r(function(e){var t=[],i=[],n=S(e.replace(lt,"$1"));return n[U]?r(function(e,t,i,r){for(var o,s=n(e,null,r,[]),a=e.length;a--;)(o=s[a])&&(e[a]=!(t[a]=o))}):function(e,r,o){t[0]=e;n(t,null,o,i);t[0]=null;return!i.pop()}}),has:r(function(e){return function(i){return t(e,i).length>0}}),contains:r(function(e){e=e.replace(Lt,Tt);return function(t){return(t.textContent||t.innerText||I(t)).indexOf(e)>-1}}),lang:r(function(e){ft.test(e||"")||t.error("unsupported lang: "+e);e=e.replace(Lt,Tt).toLowerCase();return function(t){var i;do if(i=_?t.lang:t.getAttribute("xml:lang")||t.getAttribute("lang")){i=i.toLowerCase();return i===e||0===i.indexOf(e+"-")}while((t=t.parentNode)&&1===t.nodeType);return!1}}),target:function(t){var i=e.location&&e.location.hash;return i&&i.slice(1)===t.id},root:function(e){return e===w},focus:function(e){return e===D.activeElement&&(!D.hasFocus||D.hasFocus())&&!!(e.type||e.href||~e.tabIndex)},enabled:function(e){return e.disabled===!1},disabled:function(e){return e.disabled===!0},checked:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&!!e.checked||"option"===t&&!!e.selected},selected:function(e){e.parentNode&&e.parentNode.selectedIndex;return e.selected===!0},empty:function(e){for(e=e.firstChild;e;e=e.nextSibling)if(e.nodeType<6)return!1;return!0},parent:function(e){return!T.pseudos.empty(e)},header:function(e){return mt.test(e.nodeName)},input:function(e){return Et.test(e.nodeName)},button:function(e){var t=e.nodeName.toLowerCase();return"input"===t&&"button"===e.type||"button"===t},text:function(e){var t;return"input"===e.nodeName.toLowerCase()&&"text"===e.type&&(null==(t=e.getAttribute("type"))||"text"===t.toLowerCase())},first:u(function(){return[0]}),last:u(function(e,t){return[t-1]}),eq:u(function(e,t,i){return[0>i?i+t:i]}),even:u(function(e,t){for(var i=0;t>i;i+=2)e.push(i);return e}),odd:u(function(e,t){for(var i=1;t>i;i+=2)e.push(i);return e}),lt:u(function(e,t,i){for(var r=0>i?i+t:i;--r>=0;)e.push(r);return e}),gt:u(function(e,t,i){for(var r=0>i?i+t:i;++r<t;)e.push(r);return e})}};T.pseudos.nth=T.pseudos.eq;for(N in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})T.pseudos[N]=a(N);for(N in{submit:!0,reset:!0})T.pseudos[N]=l(N);c.prototype=T.filters=T.pseudos;T.setFilters=new c;A=t.tokenize=function(e,i){var r,n,o,s,a,l,u,p=W[e+" "];if(p)return i?0:p.slice(0);a=e;l=[];u=T.preFilter;for(;a;){if(!r||(n=ut.exec(a))){n&&(a=a.slice(n[0].length)||a);l.push(o=[])}r=!1;if(n=pt.exec(a)){r=n.shift();o.push({value:r,type:n[0].replace(lt," ")});a=a.slice(r.length)}for(s in T.filter)if((n=ht[s].exec(a))&&(!u[s]||(n=u[s](n)))){r=n.shift();o.push({value:r,type:s,matches:n});a=a.slice(r.length)}if(!r)break}return i?a.length:a?t.error(e):W(e,l).slice(0)};S=t.compile=function(e,t){var i,r=[],n=[],o=q[e+" "];if(!o){t||(t=A(e));i=t.length;for(;i--;){o=v(t[i]);o[U]?r.push(o):n.push(o)}o=q(e,x(n,r));o.selector=e}return o};C=t.select=function(e,t,i,r){var n,o,s,a,l,u="function"==typeof e&&e,c=!r&&A(e=u.selector||e);i=i||[];if(1===c.length){o=c[0]=c[0].slice(0);if(o.length>2&&"ID"===(s=o[0]).type&&L.getById&&9===t.nodeType&&_&&T.relative[o[1].type]){t=(T.find.ID(s.matches[0].replace(Lt,Tt),t)||[])[0];if(!t)return i;u&&(t=t.parentNode);e=e.slice(o.shift().value.length)}n=ht.needsContext.test(e)?0:o.length;for(;n--;){s=o[n];if(T.relative[a=s.type])break;if((l=T.find[a])&&(r=l(s.matches[0].replace(Lt,Tt),xt.test(o[0].type)&&p(t.parentNode)||t))){o.splice(n,1);e=r.length&&d(o);if(!e){Z.apply(i,r);return i}break}}}(u||S(e,c))(r,t,!_,i,xt.test(e)&&p(t.parentNode)||t);return i};L.sortStable=U.split("").sort(z).join("")===U;L.detectDuplicates=!!O;P();L.sortDetached=n(function(e){return 1&e.compareDocumentPosition(D.createElement("div"))});n(function(e){e.innerHTML="<a href='#'></a>";return"#"===e.firstChild.getAttribute("href")})||o("type|href|height|width",function(e,t,i){return i?void 0:e.getAttribute(t,"type"===t.toLowerCase()?1:2)});L.attributes&&n(function(e){e.innerHTML="<input/>";e.firstChild.setAttribute("value","");return""===e.firstChild.getAttribute("value")})||o("value",function(e,t,i){return i||"input"!==e.nodeName.toLowerCase()?void 0:e.defaultValue});n(function(e){return null==e.getAttribute("disabled")})||o(tt,function(e,t,i){var r;return i?void 0:e[t]===!0?t.toLowerCase():(r=e.getAttributeNode(t))&&r.specified?r.value:null});return t}(t);ot.find=pt;ot.expr=pt.selectors;ot.expr[":"]=ot.expr.pseudos;ot.unique=pt.uniqueSort;ot.text=pt.getText;ot.isXMLDoc=pt.isXML;ot.contains=pt.contains;var ct=ot.expr.match.needsContext,dt=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,ft=/^.[^:#\[\.,]*$/;ot.filter=function(e,t,i){var r=t[0];i&&(e=":not("+e+")");return 1===t.length&&1===r.nodeType?ot.find.matchesSelector(r,e)?[r]:[]:ot.find.matches(e,ot.grep(t,function(e){return 1===e.nodeType}))};ot.fn.extend({find:function(e){var t,i=[],r=this,n=r.length;if("string"!=typeof e)return this.pushStack(ot(e).filter(function(){for(t=0;n>t;t++)if(ot.contains(r[t],this))return!0}));for(t=0;n>t;t++)ot.find(e,r[t],i);i=this.pushStack(n>1?ot.unique(i):i);i.selector=this.selector?this.selector+" "+e:e;return i},filter:function(e){return this.pushStack(n(this,e||[],!1))},not:function(e){return this.pushStack(n(this,e||[],!0))},is:function(e){return!!n(this,"string"==typeof e&&ct.test(e)?ot(e):e||[],!1).length}});var ht,Et=t.document,mt=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,gt=ot.fn.init=function(e,t){var i,r;if(!e)return this;if("string"==typeof e){i="<"===e.charAt(0)&&">"===e.charAt(e.length-1)&&e.length>=3?[null,e,null]:mt.exec(e);if(!i||!i[1]&&t)return!t||t.jquery?(t||ht).find(e):this.constructor(t).find(e);if(i[1]){t=t instanceof ot?t[0]:t;ot.merge(this,ot.parseHTML(i[1],t&&t.nodeType?t.ownerDocument||t:Et,!0));if(dt.test(i[1])&&ot.isPlainObject(t))for(i in t)ot.isFunction(this[i])?this[i](t[i]):this.attr(i,t[i]);return this}r=Et.getElementById(i[2]);if(r&&r.parentNode){if(r.id!==i[2])return ht.find(e);this.length=1;this[0]=r}this.context=Et;this.selector=e;return this}if(e.nodeType){this.context=this[0]=e;this.length=1;return this}if(ot.isFunction(e))return"undefined"!=typeof ht.ready?ht.ready(e):e(ot);if(void 0!==e.selector){this.selector=e.selector;this.context=e.context}return ot.makeArray(e,this)};gt.prototype=ot.fn;ht=ot(Et);var vt=/^(?:parents|prev(?:Until|All))/,xt={children:!0,contents:!0,next:!0,prev:!0};ot.extend({dir:function(e,t,i){for(var r=[],n=e[t];n&&9!==n.nodeType&&(void 0===i||1!==n.nodeType||!ot(n).is(i));){1===n.nodeType&&r.push(n);n=n[t]}return r},sibling:function(e,t){for(var i=[];e;e=e.nextSibling)1===e.nodeType&&e!==t&&i.push(e);return i}});ot.fn.extend({has:function(e){var t,i=ot(e,this),r=i.length;return this.filter(function(){for(t=0;r>t;t++)if(ot.contains(this,i[t]))return!0})},closest:function(e,t){for(var i,r=0,n=this.length,o=[],s=ct.test(e)||"string"!=typeof e?ot(e,t||this.context):0;n>r;r++)for(i=this[r];i&&i!==t;i=i.parentNode)if(i.nodeType<11&&(s?s.index(i)>-1:1===i.nodeType&&ot.find.matchesSelector(i,e))){o.push(i);break}return this.pushStack(o.length>1?ot.unique(o):o)},index:function(e){return e?"string"==typeof e?ot.inArray(this[0],ot(e)):ot.inArray(e.jquery?e[0]:e,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(e,t){return this.pushStack(ot.unique(ot.merge(this.get(),ot(e,t))))},addBack:function(e){return this.add(null==e?this.prevObject:this.prevObject.filter(e))}});ot.each({parent:function(e){var t=e.parentNode;return t&&11!==t.nodeType?t:null},parents:function(e){return ot.dir(e,"parentNode")},parentsUntil:function(e,t,i){return ot.dir(e,"parentNode",i)},next:function(e){return o(e,"nextSibling")},prev:function(e){return o(e,"previousSibling")},nextAll:function(e){return ot.dir(e,"nextSibling")},prevAll:function(e){return ot.dir(e,"previousSibling")},nextUntil:function(e,t,i){return ot.dir(e,"nextSibling",i)},prevUntil:function(e,t,i){return ot.dir(e,"previousSibling",i)},siblings:function(e){return ot.sibling((e.parentNode||{}).firstChild,e)},children:function(e){return ot.sibling(e.firstChild)},contents:function(e){return ot.nodeName(e,"iframe")?e.contentDocument||e.contentWindow.document:ot.merge([],e.childNodes)}},function(e,t){ot.fn[e]=function(i,r){var n=ot.map(this,t,i);"Until"!==e.slice(-5)&&(r=i);r&&"string"==typeof r&&(n=ot.filter(r,n));if(this.length>1){xt[e]||(n=ot.unique(n));vt.test(e)&&(n=n.reverse())}return this.pushStack(n)}});var Nt=/\S+/g,Lt={};ot.Callbacks=function(e){e="string"==typeof e?Lt[e]||s(e):ot.extend({},e);var t,i,r,n,o,a,l=[],u=!e.once&&[],p=function(s){i=e.memory&&s;r=!0;o=a||0;a=0;n=l.length;t=!0;for(;l&&n>o;o++)if(l[o].apply(s[0],s[1])===!1&&e.stopOnFalse){i=!1;break}t=!1;l&&(u?u.length&&p(u.shift()):i?l=[]:c.disable())},c={add:function(){if(l){var r=l.length;(function o(t){ot.each(t,function(t,i){var r=ot.type(i);"function"===r?e.unique&&c.has(i)||l.push(i):i&&i.length&&"string"!==r&&o(i)})})(arguments);if(t)n=l.length;else if(i){a=r;p(i)}}return this},remove:function(){l&&ot.each(arguments,function(e,i){for(var r;(r=ot.inArray(i,l,r))>-1;){l.splice(r,1);if(t){n>=r&&n--;o>=r&&o--}}});return this},has:function(e){return e?ot.inArray(e,l)>-1:!(!l||!l.length)},empty:function(){l=[];n=0;return this},disable:function(){l=u=i=void 0;return this},disabled:function(){return!l},lock:function(){u=void 0;i||c.disable();return this},locked:function(){return!u},fireWith:function(e,i){if(l&&(!r||u)){i=i||[];i=[e,i.slice?i.slice():i];t?u.push(i):p(i)}return this},fire:function(){c.fireWith(this,arguments);return this},fired:function(){return!!r}};return c};ot.extend({Deferred:function(e){var t=[["resolve","done",ot.Callbacks("once memory"),"resolved"],["reject","fail",ot.Callbacks("once memory"),"rejected"],["notify","progress",ot.Callbacks("memory")]],i="pending",r={state:function(){return i},always:function(){n.done(arguments).fail(arguments);return this},then:function(){var e=arguments;return ot.Deferred(function(i){ot.each(t,function(t,o){var s=ot.isFunction(e[t])&&e[t];n[o[1]](function(){var e=s&&s.apply(this,arguments);e&&ot.isFunction(e.promise)?e.promise().done(i.resolve).fail(i.reject).progress(i.notify):i[o[0]+"With"](this===r?i.promise():this,s?[e]:arguments)})});e=null}).promise()},promise:function(e){return null!=e?ot.extend(e,r):r}},n={};r.pipe=r.then;ot.each(t,function(e,o){var s=o[2],a=o[3];r[o[1]]=s.add;a&&s.add(function(){i=a},t[1^e][2].disable,t[2][2].lock);n[o[0]]=function(){n[o[0]+"With"](this===n?r:this,arguments);return this};n[o[0]+"With"]=s.fireWith});r.promise(n);e&&e.call(n,n);return n},when:function(e){var t,i,r,n=0,o=$.call(arguments),s=o.length,a=1!==s||e&&ot.isFunction(e.promise)?s:0,l=1===a?e:ot.Deferred(),u=function(e,i,r){return function(n){i[e]=this;r[e]=arguments.length>1?$.call(arguments):n;r===t?l.notifyWith(i,r):--a||l.resolveWith(i,r)}};if(s>1){t=new Array(s);i=new Array(s);r=new Array(s);for(;s>n;n++)o[n]&&ot.isFunction(o[n].promise)?o[n].promise().done(u(n,r,o)).fail(l.reject).progress(u(n,i,t)):--a}a||l.resolveWith(r,o);return l.promise()}});var Tt;ot.fn.ready=function(e){ot.ready.promise().done(e);return this};ot.extend({isReady:!1,readyWait:1,holdReady:function(e){e?ot.readyWait++:ot.ready(!0)},ready:function(e){if(e===!0?!--ot.readyWait:!ot.isReady){if(!Et.body)return setTimeout(ot.ready);ot.isReady=!0;if(!(e!==!0&&--ot.readyWait>0)){Tt.resolveWith(Et,[ot]);if(ot.fn.triggerHandler){ot(Et).triggerHandler("ready");ot(Et).off("ready")}}}}});ot.ready.promise=function(e){if(!Tt){Tt=ot.Deferred();if("complete"===Et.readyState)setTimeout(ot.ready);else if(Et.addEventListener){Et.addEventListener("DOMContentLoaded",l,!1);t.addEventListener("load",l,!1)}else{Et.attachEvent("onreadystatechange",l);t.attachEvent("onload",l);var i=!1;try{i=null==t.frameElement&&Et.documentElement}catch(r){}i&&i.doScroll&&function n(){if(!ot.isReady){try{i.doScroll("left")}catch(e){return setTimeout(n,50)}a();ot.ready()}}()}}return Tt.promise(e)};var It,yt="undefined";for(It in ot(rt))break;rt.ownLast="0"!==It;rt.inlineBlockNeedsLayout=!1;ot(function(){var e,t,i,r;i=Et.getElementsByTagName("body")[0];if(i&&i.style){t=Et.createElement("div");r=Et.createElement("div");r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px";i.appendChild(r).appendChild(t);if(typeof t.style.zoom!==yt){t.style.cssText="display:inline;margin:0;border:0;padding:1px;width:1px;zoom:1";rt.inlineBlockNeedsLayout=e=3===t.offsetWidth;e&&(i.style.zoom=1)}i.removeChild(r)}});(function(){var e=Et.createElement("div");if(null==rt.deleteExpando){rt.deleteExpando=!0;try{delete e.test}catch(t){rt.deleteExpando=!1}}e=null})();ot.acceptData=function(e){var t=ot.noData[(e.nodeName+" ").toLowerCase()],i=+e.nodeType||1;return 1!==i&&9!==i?!1:!t||t!==!0&&e.getAttribute("classid")===t};var At=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,St=/([A-Z])/g;ot.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(e){e=e.nodeType?ot.cache[e[ot.expando]]:e[ot.expando];return!!e&&!p(e)},data:function(e,t,i){return c(e,t,i)},removeData:function(e,t){return d(e,t)},_data:function(e,t,i){return c(e,t,i,!0)},_removeData:function(e,t){return d(e,t,!0)}});ot.fn.extend({data:function(e,t){var i,r,n,o=this[0],s=o&&o.attributes;if(void 0===e){if(this.length){n=ot.data(o);if(1===o.nodeType&&!ot._data(o,"parsedAttrs")){i=s.length;for(;i--;)if(s[i]){r=s[i].name;if(0===r.indexOf("data-")){r=ot.camelCase(r.slice(5));u(o,r,n[r])}}ot._data(o,"parsedAttrs",!0)}}return n}return"object"==typeof e?this.each(function(){ot.data(this,e)}):arguments.length>1?this.each(function(){ot.data(this,e,t)}):o?u(o,e,ot.data(o,e)):void 0},removeData:function(e){return this.each(function(){ot.removeData(this,e)})}});ot.extend({queue:function(e,t,i){var r;if(e){t=(t||"fx")+"queue";r=ot._data(e,t);i&&(!r||ot.isArray(i)?r=ot._data(e,t,ot.makeArray(i)):r.push(i));return r||[]}},dequeue:function(e,t){t=t||"fx";var i=ot.queue(e,t),r=i.length,n=i.shift(),o=ot._queueHooks(e,t),s=function(){ot.dequeue(e,t)};if("inprogress"===n){n=i.shift();r--}if(n){"fx"===t&&i.unshift("inprogress");delete o.stop;n.call(e,s,o)}!r&&o&&o.empty.fire()},_queueHooks:function(e,t){var i=t+"queueHooks";return ot._data(e,i)||ot._data(e,i,{empty:ot.Callbacks("once memory").add(function(){ot._removeData(e,t+"queue");ot._removeData(e,i)})})}});ot.fn.extend({queue:function(e,t){var i=2;if("string"!=typeof e){t=e;e="fx";i--}return arguments.length<i?ot.queue(this[0],e):void 0===t?this:this.each(function(){var i=ot.queue(this,e,t);ot._queueHooks(this,e);"fx"===e&&"inprogress"!==i[0]&&ot.dequeue(this,e)})},dequeue:function(e){return this.each(function(){ot.dequeue(this,e)})},clearQueue:function(e){return this.queue(e||"fx",[])},promise:function(e,t){var i,r=1,n=ot.Deferred(),o=this,s=this.length,a=function(){--r||n.resolveWith(o,[o])};if("string"!=typeof e){t=e;e=void 0}e=e||"fx";for(;s--;){i=ot._data(o[s],e+"queueHooks");if(i&&i.empty){r++;i.empty.add(a)}}a();return n.promise(t)}});var Ct=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,Rt=["Top","Right","Bottom","Left"],bt=function(e,t){e=t||e;return"none"===ot.css(e,"display")||!ot.contains(e.ownerDocument,e)},Ot=ot.access=function(e,t,i,r,n,o,s){var a=0,l=e.length,u=null==i;if("object"===ot.type(i)){n=!0;for(a in i)ot.access(e,t,a,i[a],!0,o,s)}else if(void 0!==r){n=!0;ot.isFunction(r)||(s=!0);if(u)if(s){t.call(e,r);t=null}else{u=t;t=function(e,t,i){return u.call(ot(e),i)}}if(t)for(;l>a;a++)t(e[a],i,s?r:r.call(e[a],a,t(e[a],i)))}return n?e:u?t.call(e):l?t(e[0],i):o},Pt=/^(?:checkbox|radio)$/i;(function(){var e=Et.createElement("input"),t=Et.createElement("div"),i=Et.createDocumentFragment();t.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";rt.leadingWhitespace=3===t.firstChild.nodeType;rt.tbody=!t.getElementsByTagName("tbody").length;rt.htmlSerialize=!!t.getElementsByTagName("link").length;rt.html5Clone="<:nav></:nav>"!==Et.createElement("nav").cloneNode(!0).outerHTML;e.type="checkbox";e.checked=!0;i.appendChild(e);rt.appendChecked=e.checked;t.innerHTML="<textarea>x</textarea>";rt.noCloneChecked=!!t.cloneNode(!0).lastChild.defaultValue;i.appendChild(t);t.innerHTML="<input type='radio' checked='checked' name='t'/>";rt.checkClone=t.cloneNode(!0).cloneNode(!0).lastChild.checked;rt.noCloneEvent=!0;if(t.attachEvent){t.attachEvent("onclick",function(){rt.noCloneEvent=!1});t.cloneNode(!0).click()}if(null==rt.deleteExpando){rt.deleteExpando=!0;try{delete t.test}catch(r){rt.deleteExpando=!1}}})();(function(){var e,i,r=Et.createElement("div");for(e in{submit:!0,change:!0,focusin:!0}){i="on"+e;if(!(rt[e+"Bubbles"]=i in t)){r.setAttribute(i,"t");rt[e+"Bubbles"]=r.attributes[i].expando===!1}}r=null})();var Dt=/^(?:input|select|textarea)$/i,wt=/^key/,_t=/^(?:mouse|pointer|contextmenu)|click/,Mt=/^(?:focusinfocus|focusoutblur)$/,kt=/^([^.]*)(?:\.(.+)|)$/;ot.event={global:{},add:function(e,t,i,r,n){var o,s,a,l,u,p,c,d,f,h,E,m=ot._data(e);if(m){if(i.handler){l=i;i=l.handler;n=l.selector}i.guid||(i.guid=ot.guid++);(s=m.events)||(s=m.events={});if(!(p=m.handle)){p=m.handle=function(e){return typeof ot===yt||e&&ot.event.triggered===e.type?void 0:ot.event.dispatch.apply(p.elem,arguments)};p.elem=e}t=(t||"").match(Nt)||[""];a=t.length;for(;a--;){o=kt.exec(t[a])||[];f=E=o[1];h=(o[2]||"").split(".").sort();if(f){u=ot.event.special[f]||{};f=(n?u.delegateType:u.bindType)||f;u=ot.event.special[f]||{};c=ot.extend({type:f,origType:E,data:r,handler:i,guid:i.guid,selector:n,needsContext:n&&ot.expr.match.needsContext.test(n),namespace:h.join(".")},l);if(!(d=s[f])){d=s[f]=[];d.delegateCount=0;u.setup&&u.setup.call(e,r,h,p)!==!1||(e.addEventListener?e.addEventListener(f,p,!1):e.attachEvent&&e.attachEvent("on"+f,p))}if(u.add){u.add.call(e,c);c.handler.guid||(c.handler.guid=i.guid)}n?d.splice(d.delegateCount++,0,c):d.push(c);ot.event.global[f]=!0}}e=null}},remove:function(e,t,i,r,n){var o,s,a,l,u,p,c,d,f,h,E,m=ot.hasData(e)&&ot._data(e);if(m&&(p=m.events)){t=(t||"").match(Nt)||[""];u=t.length;for(;u--;){a=kt.exec(t[u])||[];f=E=a[1];h=(a[2]||"").split(".").sort();if(f){c=ot.event.special[f]||{};f=(r?c.delegateType:c.bindType)||f;d=p[f]||[];a=a[2]&&new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)");l=o=d.length;for(;o--;){s=d[o];if(!(!n&&E!==s.origType||i&&i.guid!==s.guid||a&&!a.test(s.namespace)||r&&r!==s.selector&&("**"!==r||!s.selector))){d.splice(o,1);s.selector&&d.delegateCount--;c.remove&&c.remove.call(e,s)}}if(l&&!d.length){c.teardown&&c.teardown.call(e,h,m.handle)!==!1||ot.removeEvent(e,f,m.handle);delete p[f]}}else for(f in p)ot.event.remove(e,f+t[u],i,r,!0)}if(ot.isEmptyObject(p)){delete m.handle;ot._removeData(e,"events")}}},trigger:function(e,i,r,n){var o,s,a,l,u,p,c,d=[r||Et],f=it.call(e,"type")?e.type:e,h=it.call(e,"namespace")?e.namespace.split("."):[];a=p=r=r||Et;if(3!==r.nodeType&&8!==r.nodeType&&!Mt.test(f+ot.event.triggered)){if(f.indexOf(".")>=0){h=f.split(".");f=h.shift();h.sort()}s=f.indexOf(":")<0&&"on"+f;e=e[ot.expando]?e:new ot.Event(f,"object"==typeof e&&e);e.isTrigger=n?2:3;e.namespace=h.join(".");e.namespace_re=e.namespace?new RegExp("(^|\\.)"+h.join("\\.(?:.*\\.|)")+"(\\.|$)"):null;e.result=void 0;e.target||(e.target=r);i=null==i?[e]:ot.makeArray(i,[e]);u=ot.event.special[f]||{};if(n||!u.trigger||u.trigger.apply(r,i)!==!1){if(!n&&!u.noBubble&&!ot.isWindow(r)){l=u.delegateType||f;Mt.test(l+f)||(a=a.parentNode);for(;a;a=a.parentNode){d.push(a);p=a}p===(r.ownerDocument||Et)&&d.push(p.defaultView||p.parentWindow||t)}c=0;for(;(a=d[c++])&&!e.isPropagationStopped();){e.type=c>1?l:u.bindType||f;o=(ot._data(a,"events")||{})[e.type]&&ot._data(a,"handle");o&&o.apply(a,i);o=s&&a[s];if(o&&o.apply&&ot.acceptData(a)){e.result=o.apply(a,i);e.result===!1&&e.preventDefault()}}e.type=f;if(!n&&!e.isDefaultPrevented()&&(!u._default||u._default.apply(d.pop(),i)===!1)&&ot.acceptData(r)&&s&&r[f]&&!ot.isWindow(r)){p=r[s];p&&(r[s]=null);ot.event.triggered=f;try{r[f]()}catch(E){}ot.event.triggered=void 0;p&&(r[s]=p)}return e.result}}},dispatch:function(e){e=ot.event.fix(e);var t,i,r,n,o,s=[],a=$.call(arguments),l=(ot._data(this,"events")||{})[e.type]||[],u=ot.event.special[e.type]||{};a[0]=e;e.delegateTarget=this;if(!u.preDispatch||u.preDispatch.call(this,e)!==!1){s=ot.event.handlers.call(this,e,l);t=0;for(;(n=s[t++])&&!e.isPropagationStopped();){e.currentTarget=n.elem;o=0;for(;(r=n.handlers[o++])&&!e.isImmediatePropagationStopped();)if(!e.namespace_re||e.namespace_re.test(r.namespace)){e.handleObj=r;e.data=r.data;i=((ot.event.special[r.origType]||{}).handle||r.handler).apply(n.elem,a);if(void 0!==i&&(e.result=i)===!1){e.preventDefault();e.stopPropagation()}}}u.postDispatch&&u.postDispatch.call(this,e);return e.result}},handlers:function(e,t){var i,r,n,o,s=[],a=t.delegateCount,l=e.target;if(a&&l.nodeType&&(!e.button||"click"!==e.type))for(;l!=this;l=l.parentNode||this)if(1===l.nodeType&&(l.disabled!==!0||"click"!==e.type)){n=[];for(o=0;a>o;o++){r=t[o];i=r.selector+" ";void 0===n[i]&&(n[i]=r.needsContext?ot(i,this).index(l)>=0:ot.find(i,this,null,[l]).length);n[i]&&n.push(r)}n.length&&s.push({elem:l,handlers:n})}a<t.length&&s.push({elem:this,handlers:t.slice(a)});return s},fix:function(e){if(e[ot.expando])return e;var t,i,r,n=e.type,o=e,s=this.fixHooks[n];s||(this.fixHooks[n]=s=_t.test(n)?this.mouseHooks:wt.test(n)?this.keyHooks:{});r=s.props?this.props.concat(s.props):this.props;e=new ot.Event(o);t=r.length;for(;t--;){i=r[t];e[i]=o[i]}e.target||(e.target=o.srcElement||Et);3===e.target.nodeType&&(e.target=e.target.parentNode);e.metaKey=!!e.metaKey;return s.filter?s.filter(e,o):e},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(e,t){null==e.which&&(e.which=null!=t.charCode?t.charCode:t.keyCode);return e}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(e,t){var i,r,n,o=t.button,s=t.fromElement;if(null==e.pageX&&null!=t.clientX){r=e.target.ownerDocument||Et;n=r.documentElement;i=r.body;e.pageX=t.clientX+(n&&n.scrollLeft||i&&i.scrollLeft||0)-(n&&n.clientLeft||i&&i.clientLeft||0);e.pageY=t.clientY+(n&&n.scrollTop||i&&i.scrollTop||0)-(n&&n.clientTop||i&&i.clientTop||0)}!e.relatedTarget&&s&&(e.relatedTarget=s===e.target?t.toElement:s);e.which||void 0===o||(e.which=1&o?1:2&o?3:4&o?2:0);return e}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==E()&&this.focus)try{this.focus();return!1}catch(e){}},delegateType:"focusin"},blur:{trigger:function(){if(this===E()&&this.blur){this.blur();return!1}},delegateType:"focusout"},click:{trigger:function(){if(ot.nodeName(this,"input")&&"checkbox"===this.type&&this.click){this.click();return!1}},_default:function(e){return ot.nodeName(e.target,"a")}},beforeunload:{postDispatch:function(e){void 0!==e.result&&e.originalEvent&&(e.originalEvent.returnValue=e.result)}}},simulate:function(e,t,i,r){var n=ot.extend(new ot.Event,i,{type:e,isSimulated:!0,originalEvent:{}});r?ot.event.trigger(n,null,t):ot.event.dispatch.call(t,n);n.isDefaultPrevented()&&i.preventDefault()}};ot.removeEvent=Et.removeEventListener?function(e,t,i){e.removeEventListener&&e.removeEventListener(t,i,!1)}:function(e,t,i){var r="on"+t;if(e.detachEvent){typeof e[r]===yt&&(e[r]=null);e.detachEvent(r,i)}};ot.Event=function(e,t){if(!(this instanceof ot.Event))return new ot.Event(e,t);if(e&&e.type){this.originalEvent=e;this.type=e.type;this.isDefaultPrevented=e.defaultPrevented||void 0===e.defaultPrevented&&e.returnValue===!1?f:h}else this.type=e;t&&ot.extend(this,t);this.timeStamp=e&&e.timeStamp||ot.now();this[ot.expando]=!0};ot.Event.prototype={isDefaultPrevented:h,isPropagationStopped:h,isImmediatePropagationStopped:h,preventDefault:function(){var e=this.originalEvent;this.isDefaultPrevented=f;e&&(e.preventDefault?e.preventDefault():e.returnValue=!1)},stopPropagation:function(){var e=this.originalEvent;this.isPropagationStopped=f;if(e){e.stopPropagation&&e.stopPropagation();e.cancelBubble=!0}},stopImmediatePropagation:function(){var e=this.originalEvent;
this.isImmediatePropagationStopped=f;e&&e.stopImmediatePropagation&&e.stopImmediatePropagation();this.stopPropagation()}};ot.each({mouseenter:"mouseover",mouseleave:"mouseout",pointerenter:"pointerover",pointerleave:"pointerout"},function(e,t){ot.event.special[e]={delegateType:t,bindType:t,handle:function(e){var i,r=this,n=e.relatedTarget,o=e.handleObj;if(!n||n!==r&&!ot.contains(r,n)){e.type=o.origType;i=o.handler.apply(this,arguments);e.type=t}return i}}});rt.submitBubbles||(ot.event.special.submit={setup:function(){if(ot.nodeName(this,"form"))return!1;ot.event.add(this,"click._submit keypress._submit",function(e){var t=e.target,i=ot.nodeName(t,"input")||ot.nodeName(t,"button")?t.form:void 0;if(i&&!ot._data(i,"submitBubbles")){ot.event.add(i,"submit._submit",function(e){e._submit_bubble=!0});ot._data(i,"submitBubbles",!0)}});return void 0},postDispatch:function(e){if(e._submit_bubble){delete e._submit_bubble;this.parentNode&&!e.isTrigger&&ot.event.simulate("submit",this.parentNode,e,!0)}},teardown:function(){if(ot.nodeName(this,"form"))return!1;ot.event.remove(this,"._submit");return void 0}});rt.changeBubbles||(ot.event.special.change={setup:function(){if(Dt.test(this.nodeName)){if("checkbox"===this.type||"radio"===this.type){ot.event.add(this,"propertychange._change",function(e){"checked"===e.originalEvent.propertyName&&(this._just_changed=!0)});ot.event.add(this,"click._change",function(e){this._just_changed&&!e.isTrigger&&(this._just_changed=!1);ot.event.simulate("change",this,e,!0)})}return!1}ot.event.add(this,"beforeactivate._change",function(e){var t=e.target;if(Dt.test(t.nodeName)&&!ot._data(t,"changeBubbles")){ot.event.add(t,"change._change",function(e){!this.parentNode||e.isSimulated||e.isTrigger||ot.event.simulate("change",this.parentNode,e,!0)});ot._data(t,"changeBubbles",!0)}})},handle:function(e){var t=e.target;return this!==t||e.isSimulated||e.isTrigger||"radio"!==t.type&&"checkbox"!==t.type?e.handleObj.handler.apply(this,arguments):void 0},teardown:function(){ot.event.remove(this,"._change");return!Dt.test(this.nodeName)}});rt.focusinBubbles||ot.each({focus:"focusin",blur:"focusout"},function(e,t){var i=function(e){ot.event.simulate(t,e.target,ot.event.fix(e),!0)};ot.event.special[t]={setup:function(){var r=this.ownerDocument||this,n=ot._data(r,t);n||r.addEventListener(e,i,!0);ot._data(r,t,(n||0)+1)},teardown:function(){var r=this.ownerDocument||this,n=ot._data(r,t)-1;if(n)ot._data(r,t,n);else{r.removeEventListener(e,i,!0);ot._removeData(r,t)}}}});ot.fn.extend({on:function(e,t,i,r,n){var o,s;if("object"==typeof e){if("string"!=typeof t){i=i||t;t=void 0}for(o in e)this.on(o,t,i,e[o],n);return this}if(null==i&&null==r){r=t;i=t=void 0}else if(null==r)if("string"==typeof t){r=i;i=void 0}else{r=i;i=t;t=void 0}if(r===!1)r=h;else if(!r)return this;if(1===n){s=r;r=function(e){ot().off(e);return s.apply(this,arguments)};r.guid=s.guid||(s.guid=ot.guid++)}return this.each(function(){ot.event.add(this,e,r,i,t)})},one:function(e,t,i,r){return this.on(e,t,i,r,1)},off:function(e,t,i){var r,n;if(e&&e.preventDefault&&e.handleObj){r=e.handleObj;ot(e.delegateTarget).off(r.namespace?r.origType+"."+r.namespace:r.origType,r.selector,r.handler);return this}if("object"==typeof e){for(n in e)this.off(n,t,e[n]);return this}if(t===!1||"function"==typeof t){i=t;t=void 0}i===!1&&(i=h);return this.each(function(){ot.event.remove(this,e,i,t)})},trigger:function(e,t){return this.each(function(){ot.event.trigger(e,t,this)})},triggerHandler:function(e,t){var i=this[0];return i?ot.event.trigger(e,t,i,!0):void 0}});var Gt="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",Bt=/ jQuery\d+="(?:null|\d+)"/g,Ut=new RegExp("<(?:"+Gt+")[\\s/>]","i"),Vt=/^\s+/,Ft=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,Ht=/<([\w:]+)/,jt=/<tbody/i,Wt=/<|&#?\w+;/,qt=/<(?:script|style|link)/i,zt=/checked\s*(?:[^=]|=\s*.checked.)/i,Xt=/^$|\/(?:java|ecma)script/i,Yt=/^true\/(.*)/,Kt=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,$t={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:rt.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},Qt=m(Et),Zt=Qt.appendChild(Et.createElement("div"));$t.optgroup=$t.option;$t.tbody=$t.tfoot=$t.colgroup=$t.caption=$t.thead;$t.th=$t.td;ot.extend({clone:function(e,t,i){var r,n,o,s,a,l=ot.contains(e.ownerDocument,e);if(rt.html5Clone||ot.isXMLDoc(e)||!Ut.test("<"+e.nodeName+">"))o=e.cloneNode(!0);else{Zt.innerHTML=e.outerHTML;Zt.removeChild(o=Zt.firstChild)}if(!(rt.noCloneEvent&&rt.noCloneChecked||1!==e.nodeType&&11!==e.nodeType||ot.isXMLDoc(e))){r=g(o);a=g(e);for(s=0;null!=(n=a[s]);++s)r[s]&&y(n,r[s])}if(t)if(i){a=a||g(e);r=r||g(o);for(s=0;null!=(n=a[s]);s++)I(n,r[s])}else I(e,o);r=g(o,"script");r.length>0&&T(r,!l&&g(e,"script"));r=a=n=null;return o},buildFragment:function(e,t,i,r){for(var n,o,s,a,l,u,p,c=e.length,d=m(t),f=[],h=0;c>h;h++){o=e[h];if(o||0===o)if("object"===ot.type(o))ot.merge(f,o.nodeType?[o]:o);else if(Wt.test(o)){a=a||d.appendChild(t.createElement("div"));l=(Ht.exec(o)||["",""])[1].toLowerCase();p=$t[l]||$t._default;a.innerHTML=p[1]+o.replace(Ft,"<$1></$2>")+p[2];n=p[0];for(;n--;)a=a.lastChild;!rt.leadingWhitespace&&Vt.test(o)&&f.push(t.createTextNode(Vt.exec(o)[0]));if(!rt.tbody){o="table"!==l||jt.test(o)?"<table>"!==p[1]||jt.test(o)?0:a:a.firstChild;n=o&&o.childNodes.length;for(;n--;)ot.nodeName(u=o.childNodes[n],"tbody")&&!u.childNodes.length&&o.removeChild(u)}ot.merge(f,a.childNodes);a.textContent="";for(;a.firstChild;)a.removeChild(a.firstChild);a=d.lastChild}else f.push(t.createTextNode(o))}a&&d.removeChild(a);rt.appendChecked||ot.grep(g(f,"input"),v);h=0;for(;o=f[h++];)if(!r||-1===ot.inArray(o,r)){s=ot.contains(o.ownerDocument,o);a=g(d.appendChild(o),"script");s&&T(a);if(i){n=0;for(;o=a[n++];)Xt.test(o.type||"")&&i.push(o)}}a=null;return d},cleanData:function(e,t){for(var i,r,n,o,s=0,a=ot.expando,l=ot.cache,u=rt.deleteExpando,p=ot.event.special;null!=(i=e[s]);s++)if(t||ot.acceptData(i)){n=i[a];o=n&&l[n];if(o){if(o.events)for(r in o.events)p[r]?ot.event.remove(i,r):ot.removeEvent(i,r,o.handle);if(l[n]){delete l[n];u?delete i[a]:typeof i.removeAttribute!==yt?i.removeAttribute(a):i[a]=null;K.push(n)}}}}});ot.fn.extend({text:function(e){return Ot(this,function(e){return void 0===e?ot.text(this):this.empty().append((this[0]&&this[0].ownerDocument||Et).createTextNode(e))},null,e,arguments.length)},append:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=x(this,e);t.appendChild(e)}})},prepend:function(){return this.domManip(arguments,function(e){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var t=x(this,e);t.insertBefore(e,t.firstChild)}})},before:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this)})},after:function(){return this.domManip(arguments,function(e){this.parentNode&&this.parentNode.insertBefore(e,this.nextSibling)})},remove:function(e,t){for(var i,r=e?ot.filter(e,this):this,n=0;null!=(i=r[n]);n++){t||1!==i.nodeType||ot.cleanData(g(i));if(i.parentNode){t&&ot.contains(i.ownerDocument,i)&&T(g(i,"script"));i.parentNode.removeChild(i)}}return this},empty:function(){for(var e,t=0;null!=(e=this[t]);t++){1===e.nodeType&&ot.cleanData(g(e,!1));for(;e.firstChild;)e.removeChild(e.firstChild);e.options&&ot.nodeName(e,"select")&&(e.options.length=0)}return this},clone:function(e,t){e=null==e?!1:e;t=null==t?e:t;return this.map(function(){return ot.clone(this,e,t)})},html:function(e){return Ot(this,function(e){var t=this[0]||{},i=0,r=this.length;if(void 0===e)return 1===t.nodeType?t.innerHTML.replace(Bt,""):void 0;if(!("string"!=typeof e||qt.test(e)||!rt.htmlSerialize&&Ut.test(e)||!rt.leadingWhitespace&&Vt.test(e)||$t[(Ht.exec(e)||["",""])[1].toLowerCase()])){e=e.replace(Ft,"<$1></$2>");try{for(;r>i;i++){t=this[i]||{};if(1===t.nodeType){ot.cleanData(g(t,!1));t.innerHTML=e}}t=0}catch(n){}}t&&this.empty().append(e)},null,e,arguments.length)},replaceWith:function(){var e=arguments[0];this.domManip(arguments,function(t){e=this.parentNode;ot.cleanData(g(this));e&&e.replaceChild(t,this)});return e&&(e.length||e.nodeType)?this:this.remove()},detach:function(e){return this.remove(e,!0)},domManip:function(e,t){e=Q.apply([],e);var i,r,n,o,s,a,l=0,u=this.length,p=this,c=u-1,d=e[0],f=ot.isFunction(d);if(f||u>1&&"string"==typeof d&&!rt.checkClone&&zt.test(d))return this.each(function(i){var r=p.eq(i);f&&(e[0]=d.call(this,i,r.html()));r.domManip(e,t)});if(u){a=ot.buildFragment(e,this[0].ownerDocument,!1,this);i=a.firstChild;1===a.childNodes.length&&(a=i);if(i){o=ot.map(g(a,"script"),N);n=o.length;for(;u>l;l++){r=a;if(l!==c){r=ot.clone(r,!0,!0);n&&ot.merge(o,g(r,"script"))}t.call(this[l],r,l)}if(n){s=o[o.length-1].ownerDocument;ot.map(o,L);for(l=0;n>l;l++){r=o[l];Xt.test(r.type||"")&&!ot._data(r,"globalEval")&&ot.contains(s,r)&&(r.src?ot._evalUrl&&ot._evalUrl(r.src):ot.globalEval((r.text||r.textContent||r.innerHTML||"").replace(Kt,"")))}}a=i=null}}return this}});ot.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(e,t){ot.fn[e]=function(e){for(var i,r=0,n=[],o=ot(e),s=o.length-1;s>=r;r++){i=r===s?this:this.clone(!0);ot(o[r])[t](i);Z.apply(n,i.get())}return this.pushStack(n)}});var Jt,ei={};(function(){var e;rt.shrinkWrapBlocks=function(){if(null!=e)return e;e=!1;var t,i,r;i=Et.getElementsByTagName("body")[0];if(i&&i.style){t=Et.createElement("div");r=Et.createElement("div");r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px";i.appendChild(r).appendChild(t);if(typeof t.style.zoom!==yt){t.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";t.appendChild(Et.createElement("div")).style.width="5px";e=3!==t.offsetWidth}i.removeChild(r);return e}}})();var ti,ii,ri=/^margin/,ni=new RegExp("^("+Ct+")(?!px)[a-z%]+$","i"),oi=/^(top|right|bottom|left)$/;if(t.getComputedStyle){ti=function(e){return e.ownerDocument.defaultView.opener?e.ownerDocument.defaultView.getComputedStyle(e,null):t.getComputedStyle(e,null)};ii=function(e,t,i){var r,n,o,s,a=e.style;i=i||ti(e);s=i?i.getPropertyValue(t)||i[t]:void 0;if(i){""!==s||ot.contains(e.ownerDocument,e)||(s=ot.style(e,t));if(ni.test(s)&&ri.test(t)){r=a.width;n=a.minWidth;o=a.maxWidth;a.minWidth=a.maxWidth=a.width=s;s=i.width;a.width=r;a.minWidth=n;a.maxWidth=o}}return void 0===s?s:s+""}}else if(Et.documentElement.currentStyle){ti=function(e){return e.currentStyle};ii=function(e,t,i){var r,n,o,s,a=e.style;i=i||ti(e);s=i?i[t]:void 0;null==s&&a&&a[t]&&(s=a[t]);if(ni.test(s)&&!oi.test(t)){r=a.left;n=e.runtimeStyle;o=n&&n.left;o&&(n.left=e.currentStyle.left);a.left="fontSize"===t?"1em":s;s=a.pixelLeft+"px";a.left=r;o&&(n.left=o)}return void 0===s?s:s+""||"auto"}}(function(){function e(){var e,i,r,n;i=Et.getElementsByTagName("body")[0];if(i&&i.style){e=Et.createElement("div");r=Et.createElement("div");r.style.cssText="position:absolute;border:0;width:0;height:0;top:0;left:-9999px";i.appendChild(r).appendChild(e);e.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";o=s=!1;l=!0;if(t.getComputedStyle){o="1%"!==(t.getComputedStyle(e,null)||{}).top;s="4px"===(t.getComputedStyle(e,null)||{width:"4px"}).width;n=e.appendChild(Et.createElement("div"));n.style.cssText=e.style.cssText="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;margin:0;border:0;padding:0";n.style.marginRight=n.style.width="0";e.style.width="1px";l=!parseFloat((t.getComputedStyle(n,null)||{}).marginRight);e.removeChild(n)}e.innerHTML="<table><tr><td></td><td>t</td></tr></table>";n=e.getElementsByTagName("td");n[0].style.cssText="margin:0;border:0;padding:0;display:none";a=0===n[0].offsetHeight;if(a){n[0].style.display="";n[1].style.display="none";a=0===n[0].offsetHeight}i.removeChild(r)}}var i,r,n,o,s,a,l;i=Et.createElement("div");i.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";n=i.getElementsByTagName("a")[0];r=n&&n.style;if(r){r.cssText="float:left;opacity:.5";rt.opacity="0.5"===r.opacity;rt.cssFloat=!!r.cssFloat;i.style.backgroundClip="content-box";i.cloneNode(!0).style.backgroundClip="";rt.clearCloneStyle="content-box"===i.style.backgroundClip;rt.boxSizing=""===r.boxSizing||""===r.MozBoxSizing||""===r.WebkitBoxSizing;ot.extend(rt,{reliableHiddenOffsets:function(){null==a&&e();return a},boxSizingReliable:function(){null==s&&e();return s},pixelPosition:function(){null==o&&e();return o},reliableMarginRight:function(){null==l&&e();return l}})}})();ot.swap=function(e,t,i,r){var n,o,s={};for(o in t){s[o]=e.style[o];e.style[o]=t[o]}n=i.apply(e,r||[]);for(o in t)e.style[o]=s[o];return n};var si=/alpha\([^)]*\)/i,ai=/opacity\s*=\s*([^)]*)/,li=/^(none|table(?!-c[ea]).+)/,ui=new RegExp("^("+Ct+")(.*)$","i"),pi=new RegExp("^([+-])=("+Ct+")","i"),ci={position:"absolute",visibility:"hidden",display:"block"},di={letterSpacing:"0",fontWeight:"400"},fi=["Webkit","O","Moz","ms"];ot.extend({cssHooks:{opacity:{get:function(e,t){if(t){var i=ii(e,"opacity");return""===i?"1":i}}}},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":rt.cssFloat?"cssFloat":"styleFloat"},style:function(e,t,i,r){if(e&&3!==e.nodeType&&8!==e.nodeType&&e.style){var n,o,s,a=ot.camelCase(t),l=e.style;t=ot.cssProps[a]||(ot.cssProps[a]=R(l,a));s=ot.cssHooks[t]||ot.cssHooks[a];if(void 0===i)return s&&"get"in s&&void 0!==(n=s.get(e,!1,r))?n:l[t];o=typeof i;if("string"===o&&(n=pi.exec(i))){i=(n[1]+1)*n[2]+parseFloat(ot.css(e,t));o="number"}if(null!=i&&i===i){"number"!==o||ot.cssNumber[a]||(i+="px");rt.clearCloneStyle||""!==i||0!==t.indexOf("background")||(l[t]="inherit");if(!(s&&"set"in s&&void 0===(i=s.set(e,i,r))))try{l[t]=i}catch(u){}}}},css:function(e,t,i,r){var n,o,s,a=ot.camelCase(t);t=ot.cssProps[a]||(ot.cssProps[a]=R(e.style,a));s=ot.cssHooks[t]||ot.cssHooks[a];s&&"get"in s&&(o=s.get(e,!0,i));void 0===o&&(o=ii(e,t,r));"normal"===o&&t in di&&(o=di[t]);if(""===i||i){n=parseFloat(o);return i===!0||ot.isNumeric(n)?n||0:o}return o}});ot.each(["height","width"],function(e,t){ot.cssHooks[t]={get:function(e,i,r){return i?li.test(ot.css(e,"display"))&&0===e.offsetWidth?ot.swap(e,ci,function(){return D(e,t,r)}):D(e,t,r):void 0},set:function(e,i,r){var n=r&&ti(e);return O(e,i,r?P(e,t,r,rt.boxSizing&&"border-box"===ot.css(e,"boxSizing",!1,n),n):0)}}});rt.opacity||(ot.cssHooks.opacity={get:function(e,t){return ai.test((t&&e.currentStyle?e.currentStyle.filter:e.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":t?"1":""},set:function(e,t){var i=e.style,r=e.currentStyle,n=ot.isNumeric(t)?"alpha(opacity="+100*t+")":"",o=r&&r.filter||i.filter||"";i.zoom=1;if((t>=1||""===t)&&""===ot.trim(o.replace(si,""))&&i.removeAttribute){i.removeAttribute("filter");if(""===t||r&&!r.filter)return}i.filter=si.test(o)?o.replace(si,n):o+" "+n}});ot.cssHooks.marginRight=C(rt.reliableMarginRight,function(e,t){return t?ot.swap(e,{display:"inline-block"},ii,[e,"marginRight"]):void 0});ot.each({margin:"",padding:"",border:"Width"},function(e,t){ot.cssHooks[e+t]={expand:function(i){for(var r=0,n={},o="string"==typeof i?i.split(" "):[i];4>r;r++)n[e+Rt[r]+t]=o[r]||o[r-2]||o[0];return n}};ri.test(e)||(ot.cssHooks[e+t].set=O)});ot.fn.extend({css:function(e,t){return Ot(this,function(e,t,i){var r,n,o={},s=0;if(ot.isArray(t)){r=ti(e);n=t.length;for(;n>s;s++)o[t[s]]=ot.css(e,t[s],!1,r);return o}return void 0!==i?ot.style(e,t,i):ot.css(e,t)},e,t,arguments.length>1)},show:function(){return b(this,!0)},hide:function(){return b(this)},toggle:function(e){return"boolean"==typeof e?e?this.show():this.hide():this.each(function(){bt(this)?ot(this).show():ot(this).hide()})}});ot.Tween=w;w.prototype={constructor:w,init:function(e,t,i,r,n,o){this.elem=e;this.prop=i;this.easing=n||"swing";this.options=t;this.start=this.now=this.cur();this.end=r;this.unit=o||(ot.cssNumber[i]?"":"px")},cur:function(){var e=w.propHooks[this.prop];return e&&e.get?e.get(this):w.propHooks._default.get(this)},run:function(e){var t,i=w.propHooks[this.prop];this.pos=t=this.options.duration?ot.easing[this.easing](e,this.options.duration*e,0,1,this.options.duration):e;this.now=(this.end-this.start)*t+this.start;this.options.step&&this.options.step.call(this.elem,this.now,this);i&&i.set?i.set(this):w.propHooks._default.set(this);return this}};w.prototype.init.prototype=w.prototype;w.propHooks={_default:{get:function(e){var t;if(null!=e.elem[e.prop]&&(!e.elem.style||null==e.elem.style[e.prop]))return e.elem[e.prop];t=ot.css(e.elem,e.prop,"");return t&&"auto"!==t?t:0},set:function(e){ot.fx.step[e.prop]?ot.fx.step[e.prop](e):e.elem.style&&(null!=e.elem.style[ot.cssProps[e.prop]]||ot.cssHooks[e.prop])?ot.style(e.elem,e.prop,e.now+e.unit):e.elem[e.prop]=e.now}}};w.propHooks.scrollTop=w.propHooks.scrollLeft={set:function(e){e.elem.nodeType&&e.elem.parentNode&&(e.elem[e.prop]=e.now)}};ot.easing={linear:function(e){return e},swing:function(e){return.5-Math.cos(e*Math.PI)/2}};ot.fx=w.prototype.init;ot.fx.step={};var hi,Ei,mi=/^(?:toggle|show|hide)$/,gi=new RegExp("^(?:([+-])=|)("+Ct+")([a-z%]*)$","i"),vi=/queueHooks$/,xi=[G],Ni={"*":[function(e,t){var i=this.createTween(e,t),r=i.cur(),n=gi.exec(t),o=n&&n[3]||(ot.cssNumber[e]?"":"px"),s=(ot.cssNumber[e]||"px"!==o&&+r)&&gi.exec(ot.css(i.elem,e)),a=1,l=20;if(s&&s[3]!==o){o=o||s[3];n=n||[];s=+r||1;do{a=a||".5";s/=a;ot.style(i.elem,e,s+o)}while(a!==(a=i.cur()/r)&&1!==a&&--l)}if(n){s=i.start=+s||+r||0;i.unit=o;i.end=n[1]?s+(n[1]+1)*n[2]:+n[2]}return i}]};ot.Animation=ot.extend(U,{tweener:function(e,t){if(ot.isFunction(e)){t=e;e=["*"]}else e=e.split(" ");for(var i,r=0,n=e.length;n>r;r++){i=e[r];Ni[i]=Ni[i]||[];Ni[i].unshift(t)}},prefilter:function(e,t){t?xi.unshift(e):xi.push(e)}});ot.speed=function(e,t,i){var r=e&&"object"==typeof e?ot.extend({},e):{complete:i||!i&&t||ot.isFunction(e)&&e,duration:e,easing:i&&t||t&&!ot.isFunction(t)&&t};r.duration=ot.fx.off?0:"number"==typeof r.duration?r.duration:r.duration in ot.fx.speeds?ot.fx.speeds[r.duration]:ot.fx.speeds._default;(null==r.queue||r.queue===!0)&&(r.queue="fx");r.old=r.complete;r.complete=function(){ot.isFunction(r.old)&&r.old.call(this);r.queue&&ot.dequeue(this,r.queue)};return r};ot.fn.extend({fadeTo:function(e,t,i,r){return this.filter(bt).css("opacity",0).show().end().animate({opacity:t},e,i,r)},animate:function(e,t,i,r){var n=ot.isEmptyObject(e),o=ot.speed(t,i,r),s=function(){var t=U(this,ot.extend({},e),o);(n||ot._data(this,"finish"))&&t.stop(!0)};s.finish=s;return n||o.queue===!1?this.each(s):this.queue(o.queue,s)},stop:function(e,t,i){var r=function(e){var t=e.stop;delete e.stop;t(i)};if("string"!=typeof e){i=t;t=e;e=void 0}t&&e!==!1&&this.queue(e||"fx",[]);return this.each(function(){var t=!0,n=null!=e&&e+"queueHooks",o=ot.timers,s=ot._data(this);if(n)s[n]&&s[n].stop&&r(s[n]);else for(n in s)s[n]&&s[n].stop&&vi.test(n)&&r(s[n]);for(n=o.length;n--;)if(o[n].elem===this&&(null==e||o[n].queue===e)){o[n].anim.stop(i);t=!1;o.splice(n,1)}(t||!i)&&ot.dequeue(this,e)})},finish:function(e){e!==!1&&(e=e||"fx");return this.each(function(){var t,i=ot._data(this),r=i[e+"queue"],n=i[e+"queueHooks"],o=ot.timers,s=r?r.length:0;i.finish=!0;ot.queue(this,e,[]);n&&n.stop&&n.stop.call(this,!0);for(t=o.length;t--;)if(o[t].elem===this&&o[t].queue===e){o[t].anim.stop(!0);o.splice(t,1)}for(t=0;s>t;t++)r[t]&&r[t].finish&&r[t].finish.call(this);delete i.finish})}});ot.each(["toggle","show","hide"],function(e,t){var i=ot.fn[t];ot.fn[t]=function(e,r,n){return null==e||"boolean"==typeof e?i.apply(this,arguments):this.animate(M(t,!0),e,r,n)}});ot.each({slideDown:M("show"),slideUp:M("hide"),slideToggle:M("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(e,t){ot.fn[e]=function(e,i,r){return this.animate(t,e,i,r)}});ot.timers=[];ot.fx.tick=function(){var e,t=ot.timers,i=0;hi=ot.now();for(;i<t.length;i++){e=t[i];e()||t[i]!==e||t.splice(i--,1)}t.length||ot.fx.stop();hi=void 0};ot.fx.timer=function(e){ot.timers.push(e);e()?ot.fx.start():ot.timers.pop()};ot.fx.interval=13;ot.fx.start=function(){Ei||(Ei=setInterval(ot.fx.tick,ot.fx.interval))};ot.fx.stop=function(){clearInterval(Ei);Ei=null};ot.fx.speeds={slow:600,fast:200,_default:400};ot.fn.delay=function(e,t){e=ot.fx?ot.fx.speeds[e]||e:e;t=t||"fx";return this.queue(t,function(t,i){var r=setTimeout(t,e);i.stop=function(){clearTimeout(r)}})};(function(){var e,t,i,r,n;t=Et.createElement("div");t.setAttribute("className","t");t.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>";r=t.getElementsByTagName("a")[0];i=Et.createElement("select");n=i.appendChild(Et.createElement("option"));e=t.getElementsByTagName("input")[0];r.style.cssText="top:1px";rt.getSetAttribute="t"!==t.className;rt.style=/top/.test(r.getAttribute("style"));rt.hrefNormalized="/a"===r.getAttribute("href");rt.checkOn=!!e.value;rt.optSelected=n.selected;rt.enctype=!!Et.createElement("form").enctype;i.disabled=!0;rt.optDisabled=!n.disabled;e=Et.createElement("input");e.setAttribute("value","");rt.input=""===e.getAttribute("value");e.value="t";e.setAttribute("type","radio");rt.radioValue="t"===e.value})();var Li=/\r/g;ot.fn.extend({val:function(e){var t,i,r,n=this[0];if(arguments.length){r=ot.isFunction(e);return this.each(function(i){var n;if(1===this.nodeType){n=r?e.call(this,i,ot(this).val()):e;null==n?n="":"number"==typeof n?n+="":ot.isArray(n)&&(n=ot.map(n,function(e){return null==e?"":e+""}));t=ot.valHooks[this.type]||ot.valHooks[this.nodeName.toLowerCase()];t&&"set"in t&&void 0!==t.set(this,n,"value")||(this.value=n)}})}if(n){t=ot.valHooks[n.type]||ot.valHooks[n.nodeName.toLowerCase()];if(t&&"get"in t&&void 0!==(i=t.get(n,"value")))return i;i=n.value;return"string"==typeof i?i.replace(Li,""):null==i?"":i}}});ot.extend({valHooks:{option:{get:function(e){var t=ot.find.attr(e,"value");return null!=t?t:ot.trim(ot.text(e))}},select:{get:function(e){for(var t,i,r=e.options,n=e.selectedIndex,o="select-one"===e.type||0>n,s=o?null:[],a=o?n+1:r.length,l=0>n?a:o?n:0;a>l;l++){i=r[l];if(!(!i.selected&&l!==n||(rt.optDisabled?i.disabled:null!==i.getAttribute("disabled"))||i.parentNode.disabled&&ot.nodeName(i.parentNode,"optgroup"))){t=ot(i).val();if(o)return t;s.push(t)}}return s},set:function(e,t){for(var i,r,n=e.options,o=ot.makeArray(t),s=n.length;s--;){r=n[s];if(ot.inArray(ot.valHooks.option.get(r),o)>=0)try{r.selected=i=!0}catch(a){r.scrollHeight}else r.selected=!1}i||(e.selectedIndex=-1);return n}}}});ot.each(["radio","checkbox"],function(){ot.valHooks[this]={set:function(e,t){return ot.isArray(t)?e.checked=ot.inArray(ot(e).val(),t)>=0:void 0}};rt.checkOn||(ot.valHooks[this].get=function(e){return null===e.getAttribute("value")?"on":e.value})});var Ti,Ii,yi=ot.expr.attrHandle,Ai=/^(?:checked|selected)$/i,Si=rt.getSetAttribute,Ci=rt.input;ot.fn.extend({attr:function(e,t){return Ot(this,ot.attr,e,t,arguments.length>1)},removeAttr:function(e){return this.each(function(){ot.removeAttr(this,e)})}});ot.extend({attr:function(e,t,i){var r,n,o=e.nodeType;if(e&&3!==o&&8!==o&&2!==o){if(typeof e.getAttribute===yt)return ot.prop(e,t,i);if(1!==o||!ot.isXMLDoc(e)){t=t.toLowerCase();r=ot.attrHooks[t]||(ot.expr.match.bool.test(t)?Ii:Ti)}if(void 0===i){if(r&&"get"in r&&null!==(n=r.get(e,t)))return n;n=ot.find.attr(e,t);return null==n?void 0:n}if(null!==i){if(r&&"set"in r&&void 0!==(n=r.set(e,i,t)))return n;e.setAttribute(t,i+"");return i}ot.removeAttr(e,t)}},removeAttr:function(e,t){var i,r,n=0,o=t&&t.match(Nt);if(o&&1===e.nodeType)for(;i=o[n++];){r=ot.propFix[i]||i;ot.expr.match.bool.test(i)?Ci&&Si||!Ai.test(i)?e[r]=!1:e[ot.camelCase("default-"+i)]=e[r]=!1:ot.attr(e,i,"");e.removeAttribute(Si?i:r)}},attrHooks:{type:{set:function(e,t){if(!rt.radioValue&&"radio"===t&&ot.nodeName(e,"input")){var i=e.value;e.setAttribute("type",t);i&&(e.value=i);return t}}}}});Ii={set:function(e,t,i){t===!1?ot.removeAttr(e,i):Ci&&Si||!Ai.test(i)?e.setAttribute(!Si&&ot.propFix[i]||i,i):e[ot.camelCase("default-"+i)]=e[i]=!0;return i}};ot.each(ot.expr.match.bool.source.match(/\w+/g),function(e,t){var i=yi[t]||ot.find.attr;yi[t]=Ci&&Si||!Ai.test(t)?function(e,t,r){var n,o;if(!r){o=yi[t];yi[t]=n;n=null!=i(e,t,r)?t.toLowerCase():null;yi[t]=o}return n}:function(e,t,i){return i?void 0:e[ot.camelCase("default-"+t)]?t.toLowerCase():null}});Ci&&Si||(ot.attrHooks.value={set:function(e,t,i){if(!ot.nodeName(e,"input"))return Ti&&Ti.set(e,t,i);e.defaultValue=t;return void 0}});if(!Si){Ti={set:function(e,t,i){var r=e.getAttributeNode(i);r||e.setAttributeNode(r=e.ownerDocument.createAttribute(i));r.value=t+="";return"value"===i||t===e.getAttribute(i)?t:void 0}};yi.id=yi.name=yi.coords=function(e,t,i){var r;return i?void 0:(r=e.getAttributeNode(t))&&""!==r.value?r.value:null};ot.valHooks.button={get:function(e,t){var i=e.getAttributeNode(t);return i&&i.specified?i.value:void 0},set:Ti.set};ot.attrHooks.contenteditable={set:function(e,t,i){Ti.set(e,""===t?!1:t,i)}};ot.each(["width","height"],function(e,t){ot.attrHooks[t]={set:function(e,i){if(""===i){e.setAttribute(t,"auto");return i}}}})}rt.style||(ot.attrHooks.style={get:function(e){return e.style.cssText||void 0},set:function(e,t){return e.style.cssText=t+""}});var Ri=/^(?:input|select|textarea|button|object)$/i,bi=/^(?:a|area)$/i;ot.fn.extend({prop:function(e,t){return Ot(this,ot.prop,e,t,arguments.length>1)},removeProp:function(e){e=ot.propFix[e]||e;return this.each(function(){try{this[e]=void 0;delete this[e]}catch(t){}})}});ot.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(e,t,i){var r,n,o,s=e.nodeType;if(e&&3!==s&&8!==s&&2!==s){o=1!==s||!ot.isXMLDoc(e);if(o){t=ot.propFix[t]||t;n=ot.propHooks[t]}return void 0!==i?n&&"set"in n&&void 0!==(r=n.set(e,i,t))?r:e[t]=i:n&&"get"in n&&null!==(r=n.get(e,t))?r:e[t]}},propHooks:{tabIndex:{get:function(e){var t=ot.find.attr(e,"tabindex");return t?parseInt(t,10):Ri.test(e.nodeName)||bi.test(e.nodeName)&&e.href?0:-1}}}});rt.hrefNormalized||ot.each(["href","src"],function(e,t){ot.propHooks[t]={get:function(e){return e.getAttribute(t,4)}}});rt.optSelected||(ot.propHooks.selected={get:function(e){var t=e.parentNode;if(t){t.selectedIndex;t.parentNode&&t.parentNode.selectedIndex}return null}});ot.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){ot.propFix[this.toLowerCase()]=this});rt.enctype||(ot.propFix.enctype="encoding");var Oi=/[\t\r\n\f]/g;ot.fn.extend({addClass:function(e){var t,i,r,n,o,s,a=0,l=this.length,u="string"==typeof e&&e;if(ot.isFunction(e))return this.each(function(t){ot(this).addClass(e.call(this,t,this.className))});if(u){t=(e||"").match(Nt)||[];for(;l>a;a++){i=this[a];r=1===i.nodeType&&(i.className?(" "+i.className+" ").replace(Oi," "):" ");if(r){o=0;for(;n=t[o++];)r.indexOf(" "+n+" ")<0&&(r+=n+" ");s=ot.trim(r);i.className!==s&&(i.className=s)}}}return this},removeClass:function(e){var t,i,r,n,o,s,a=0,l=this.length,u=0===arguments.length||"string"==typeof e&&e;if(ot.isFunction(e))return this.each(function(t){ot(this).removeClass(e.call(this,t,this.className))});if(u){t=(e||"").match(Nt)||[];for(;l>a;a++){i=this[a];r=1===i.nodeType&&(i.className?(" "+i.className+" ").replace(Oi," "):"");if(r){o=0;for(;n=t[o++];)for(;r.indexOf(" "+n+" ")>=0;)r=r.replace(" "+n+" "," ");s=e?ot.trim(r):"";i.className!==s&&(i.className=s)}}}return this},toggleClass:function(e,t){var i=typeof e;return"boolean"==typeof t&&"string"===i?t?this.addClass(e):this.removeClass(e):this.each(ot.isFunction(e)?function(i){ot(this).toggleClass(e.call(this,i,this.className,t),t)}:function(){if("string"===i)for(var t,r=0,n=ot(this),o=e.match(Nt)||[];t=o[r++];)n.hasClass(t)?n.removeClass(t):n.addClass(t);else if(i===yt||"boolean"===i){this.className&&ot._data(this,"__className__",this.className);this.className=this.className||e===!1?"":ot._data(this,"__className__")||""}})},hasClass:function(e){for(var t=" "+e+" ",i=0,r=this.length;r>i;i++)if(1===this[i].nodeType&&(" "+this[i].className+" ").replace(Oi," ").indexOf(t)>=0)return!0;return!1}});ot.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(e,t){ot.fn[t]=function(e,i){return arguments.length>0?this.on(t,null,e,i):this.trigger(t)}});ot.fn.extend({hover:function(e,t){return this.mouseenter(e).mouseleave(t||e)},bind:function(e,t,i){return this.on(e,null,t,i)},unbind:function(e,t){return this.off(e,null,t)},delegate:function(e,t,i,r){return this.on(t,e,i,r)},undelegate:function(e,t,i){return 1===arguments.length?this.off(e,"**"):this.off(t,e||"**",i)}});var Pi=ot.now(),Di=/\?/,wi=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;ot.parseJSON=function(e){if(t.JSON&&t.JSON.parse)return t.JSON.parse(e+"");var i,r=null,n=ot.trim(e+"");return n&&!ot.trim(n.replace(wi,function(e,t,n,o){i&&t&&(r=0);if(0===r)return e;i=n||t;r+=!o-!n;return""}))?Function("return "+n)():ot.error("Invalid JSON: "+e)};ot.parseXML=function(e){var i,r;if(!e||"string"!=typeof e)return null;try{if(t.DOMParser){r=new DOMParser;i=r.parseFromString(e,"text/xml")}else{i=new ActiveXObject("Microsoft.XMLDOM");i.async="false";i.loadXML(e)}}catch(n){i=void 0}i&&i.documentElement&&!i.getElementsByTagName("parsererror").length||ot.error("Invalid XML: "+e);return i};var _i,Mi,ki=/#.*$/,Gi=/([?&])_=[^&]*/,Bi=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Ui=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Vi=/^(?:GET|HEAD)$/,Fi=/^\/\//,Hi=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,ji={},Wi={},qi="*/".concat("*");try{Mi=location.href}catch(zi){Mi=Et.createElement("a");Mi.href="";Mi=Mi.href}_i=Hi.exec(Mi.toLowerCase())||[];ot.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Mi,type:"GET",isLocal:Ui.test(_i[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":qi,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":ot.parseJSON,"text xml":ot.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(e,t){return t?H(H(e,ot.ajaxSettings),t):H(ot.ajaxSettings,e)},ajaxPrefilter:V(ji),ajaxTransport:V(Wi),ajax:function(e,t){function i(e,t,i,r){var n,p,g,v,N,T=t;if(2!==x){x=2;a&&clearTimeout(a);u=void 0;s=r||"";L.readyState=e>0?4:0;n=e>=200&&300>e||304===e;i&&(v=j(c,L,i));v=W(c,v,L,n);if(n){if(c.ifModified){N=L.getResponseHeader("Last-Modified");N&&(ot.lastModified[o]=N);N=L.getResponseHeader("etag");N&&(ot.etag[o]=N)}if(204===e||"HEAD"===c.type)T="nocontent";else if(304===e)T="notmodified";else{T=v.state;p=v.data;g=v.error;n=!g}}else{g=T;if(e||!T){T="error";0>e&&(e=0)}}L.status=e;L.statusText=(t||T)+"";n?h.resolveWith(d,[p,T,L]):h.rejectWith(d,[L,T,g]);L.statusCode(m);m=void 0;l&&f.trigger(n?"ajaxSuccess":"ajaxError",[L,c,n?p:g]);E.fireWith(d,[L,T]);if(l){f.trigger("ajaxComplete",[L,c]);--ot.active||ot.event.trigger("ajaxStop")}}}if("object"==typeof e){t=e;e=void 0}t=t||{};var r,n,o,s,a,l,u,p,c=ot.ajaxSetup({},t),d=c.context||c,f=c.context&&(d.nodeType||d.jquery)?ot(d):ot.event,h=ot.Deferred(),E=ot.Callbacks("once memory"),m=c.statusCode||{},g={},v={},x=0,N="canceled",L={readyState:0,getResponseHeader:function(e){var t;
if(2===x){if(!p){p={};for(;t=Bi.exec(s);)p[t[1].toLowerCase()]=t[2]}t=p[e.toLowerCase()]}return null==t?null:t},getAllResponseHeaders:function(){return 2===x?s:null},setRequestHeader:function(e,t){var i=e.toLowerCase();if(!x){e=v[i]=v[i]||e;g[e]=t}return this},overrideMimeType:function(e){x||(c.mimeType=e);return this},statusCode:function(e){var t;if(e)if(2>x)for(t in e)m[t]=[m[t],e[t]];else L.always(e[L.status]);return this},abort:function(e){var t=e||N;u&&u.abort(t);i(0,t);return this}};h.promise(L).complete=E.add;L.success=L.done;L.error=L.fail;c.url=((e||c.url||Mi)+"").replace(ki,"").replace(Fi,_i[1]+"//");c.type=t.method||t.type||c.method||c.type;c.dataTypes=ot.trim(c.dataType||"*").toLowerCase().match(Nt)||[""];if(null==c.crossDomain){r=Hi.exec(c.url.toLowerCase());c.crossDomain=!(!r||r[1]===_i[1]&&r[2]===_i[2]&&(r[3]||("http:"===r[1]?"80":"443"))===(_i[3]||("http:"===_i[1]?"80":"443")))}c.data&&c.processData&&"string"!=typeof c.data&&(c.data=ot.param(c.data,c.traditional));F(ji,c,t,L);if(2===x)return L;l=ot.event&&c.global;l&&0===ot.active++&&ot.event.trigger("ajaxStart");c.type=c.type.toUpperCase();c.hasContent=!Vi.test(c.type);o=c.url;if(!c.hasContent){if(c.data){o=c.url+=(Di.test(o)?"&":"?")+c.data;delete c.data}c.cache===!1&&(c.url=Gi.test(o)?o.replace(Gi,"$1_="+Pi++):o+(Di.test(o)?"&":"?")+"_="+Pi++)}if(c.ifModified){ot.lastModified[o]&&L.setRequestHeader("If-Modified-Since",ot.lastModified[o]);ot.etag[o]&&L.setRequestHeader("If-None-Match",ot.etag[o])}(c.data&&c.hasContent&&c.contentType!==!1||t.contentType)&&L.setRequestHeader("Content-Type",c.contentType);L.setRequestHeader("Accept",c.dataTypes[0]&&c.accepts[c.dataTypes[0]]?c.accepts[c.dataTypes[0]]+("*"!==c.dataTypes[0]?", "+qi+"; q=0.01":""):c.accepts["*"]);for(n in c.headers)L.setRequestHeader(n,c.headers[n]);if(c.beforeSend&&(c.beforeSend.call(d,L,c)===!1||2===x))return L.abort();N="abort";for(n in{success:1,error:1,complete:1})L[n](c[n]);u=F(Wi,c,t,L);if(u){L.readyState=1;l&&f.trigger("ajaxSend",[L,c]);c.async&&c.timeout>0&&(a=setTimeout(function(){L.abort("timeout")},c.timeout));try{x=1;u.send(g,i)}catch(T){if(!(2>x))throw T;i(-1,T)}}else i(-1,"No Transport");return L},getJSON:function(e,t,i){return ot.get(e,t,i,"json")},getScript:function(e,t){return ot.get(e,void 0,t,"script")}});ot.each(["get","post"],function(e,t){ot[t]=function(e,i,r,n){if(ot.isFunction(i)){n=n||r;r=i;i=void 0}return ot.ajax({url:e,type:t,dataType:n,data:i,success:r})}});ot._evalUrl=function(e){return ot.ajax({url:e,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})};ot.fn.extend({wrapAll:function(e){if(ot.isFunction(e))return this.each(function(t){ot(this).wrapAll(e.call(this,t))});if(this[0]){var t=ot(e,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&t.insertBefore(this[0]);t.map(function(){for(var e=this;e.firstChild&&1===e.firstChild.nodeType;)e=e.firstChild;return e}).append(this)}return this},wrapInner:function(e){return this.each(ot.isFunction(e)?function(t){ot(this).wrapInner(e.call(this,t))}:function(){var t=ot(this),i=t.contents();i.length?i.wrapAll(e):t.append(e)})},wrap:function(e){var t=ot.isFunction(e);return this.each(function(i){ot(this).wrapAll(t?e.call(this,i):e)})},unwrap:function(){return this.parent().each(function(){ot.nodeName(this,"body")||ot(this).replaceWith(this.childNodes)}).end()}});ot.expr.filters.hidden=function(e){return e.offsetWidth<=0&&e.offsetHeight<=0||!rt.reliableHiddenOffsets()&&"none"===(e.style&&e.style.display||ot.css(e,"display"))};ot.expr.filters.visible=function(e){return!ot.expr.filters.hidden(e)};var Xi=/%20/g,Yi=/\[\]$/,Ki=/\r?\n/g,$i=/^(?:submit|button|image|reset|file)$/i,Qi=/^(?:input|select|textarea|keygen)/i;ot.param=function(e,t){var i,r=[],n=function(e,t){t=ot.isFunction(t)?t():null==t?"":t;r[r.length]=encodeURIComponent(e)+"="+encodeURIComponent(t)};void 0===t&&(t=ot.ajaxSettings&&ot.ajaxSettings.traditional);if(ot.isArray(e)||e.jquery&&!ot.isPlainObject(e))ot.each(e,function(){n(this.name,this.value)});else for(i in e)q(i,e[i],t,n);return r.join("&").replace(Xi,"+")};ot.fn.extend({serialize:function(){return ot.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var e=ot.prop(this,"elements");return e?ot.makeArray(e):this}).filter(function(){var e=this.type;return this.name&&!ot(this).is(":disabled")&&Qi.test(this.nodeName)&&!$i.test(e)&&(this.checked||!Pt.test(e))}).map(function(e,t){var i=ot(this).val();return null==i?null:ot.isArray(i)?ot.map(i,function(e){return{name:t.name,value:e.replace(Ki,"\r\n")}}):{name:t.name,value:i.replace(Ki,"\r\n")}}).get()}});ot.ajaxSettings.xhr=void 0!==t.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&z()||X()}:z;var Zi=0,Ji={},er=ot.ajaxSettings.xhr();t.attachEvent&&t.attachEvent("onunload",function(){for(var e in Ji)Ji[e](void 0,!0)});rt.cors=!!er&&"withCredentials"in er;er=rt.ajax=!!er;er&&ot.ajaxTransport(function(e){if(!e.crossDomain||rt.cors){var t;return{send:function(i,r){var n,o=e.xhr(),s=++Zi;o.open(e.type,e.url,e.async,e.username,e.password);if(e.xhrFields)for(n in e.xhrFields)o[n]=e.xhrFields[n];e.mimeType&&o.overrideMimeType&&o.overrideMimeType(e.mimeType);e.crossDomain||i["X-Requested-With"]||(i["X-Requested-With"]="XMLHttpRequest");for(n in i)void 0!==i[n]&&o.setRequestHeader(n,i[n]+"");o.send(e.hasContent&&e.data||null);t=function(i,n){var a,l,u;if(t&&(n||4===o.readyState)){delete Ji[s];t=void 0;o.onreadystatechange=ot.noop;if(n)4!==o.readyState&&o.abort();else{u={};a=o.status;"string"==typeof o.responseText&&(u.text=o.responseText);try{l=o.statusText}catch(p){l=""}a||!e.isLocal||e.crossDomain?1223===a&&(a=204):a=u.text?200:404}}u&&r(a,l,u,o.getAllResponseHeaders())};e.async?4===o.readyState?setTimeout(t):o.onreadystatechange=Ji[s]=t:t()},abort:function(){t&&t(void 0,!0)}}}});ot.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(e){ot.globalEval(e);return e}}});ot.ajaxPrefilter("script",function(e){void 0===e.cache&&(e.cache=!1);if(e.crossDomain){e.type="GET";e.global=!1}});ot.ajaxTransport("script",function(e){if(e.crossDomain){var t,i=Et.head||ot("head")[0]||Et.documentElement;return{send:function(r,n){t=Et.createElement("script");t.async=!0;e.scriptCharset&&(t.charset=e.scriptCharset);t.src=e.url;t.onload=t.onreadystatechange=function(e,i){if(i||!t.readyState||/loaded|complete/.test(t.readyState)){t.onload=t.onreadystatechange=null;t.parentNode&&t.parentNode.removeChild(t);t=null;i||n(200,"success")}};i.insertBefore(t,i.firstChild)},abort:function(){t&&t.onload(void 0,!0)}}}});var tr=[],ir=/(=)\?(?=&|$)|\?\?/;ot.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var e=tr.pop()||ot.expando+"_"+Pi++;this[e]=!0;return e}});ot.ajaxPrefilter("json jsonp",function(e,i,r){var n,o,s,a=e.jsonp!==!1&&(ir.test(e.url)?"url":"string"==typeof e.data&&!(e.contentType||"").indexOf("application/x-www-form-urlencoded")&&ir.test(e.data)&&"data");if(a||"jsonp"===e.dataTypes[0]){n=e.jsonpCallback=ot.isFunction(e.jsonpCallback)?e.jsonpCallback():e.jsonpCallback;a?e[a]=e[a].replace(ir,"$1"+n):e.jsonp!==!1&&(e.url+=(Di.test(e.url)?"&":"?")+e.jsonp+"="+n);e.converters["script json"]=function(){s||ot.error(n+" was not called");return s[0]};e.dataTypes[0]="json";o=t[n];t[n]=function(){s=arguments};r.always(function(){t[n]=o;if(e[n]){e.jsonpCallback=i.jsonpCallback;tr.push(n)}s&&ot.isFunction(o)&&o(s[0]);s=o=void 0});return"script"}});ot.parseHTML=function(e,t,i){if(!e||"string"!=typeof e)return null;if("boolean"==typeof t){i=t;t=!1}t=t||Et;var r=dt.exec(e),n=!i&&[];if(r)return[t.createElement(r[1])];r=ot.buildFragment([e],t,n);n&&n.length&&ot(n).remove();return ot.merge([],r.childNodes)};var rr=ot.fn.load;ot.fn.load=function(e,t,i){if("string"!=typeof e&&rr)return rr.apply(this,arguments);var r,n,o,s=this,a=e.indexOf(" ");if(a>=0){r=ot.trim(e.slice(a,e.length));e=e.slice(0,a)}if(ot.isFunction(t)){i=t;t=void 0}else t&&"object"==typeof t&&(o="POST");s.length>0&&ot.ajax({url:e,type:o,dataType:"html",data:t}).done(function(e){n=arguments;s.html(r?ot("<div>").append(ot.parseHTML(e)).find(r):e)}).complete(i&&function(e,t){s.each(i,n||[e.responseText,t,e])});return this};ot.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(e,t){ot.fn[t]=function(e){return this.on(t,e)}});ot.expr.filters.animated=function(e){return ot.grep(ot.timers,function(t){return e===t.elem}).length};var nr=t.document.documentElement;ot.offset={setOffset:function(e,t,i){var r,n,o,s,a,l,u,p=ot.css(e,"position"),c=ot(e),d={};"static"===p&&(e.style.position="relative");a=c.offset();o=ot.css(e,"top");l=ot.css(e,"left");u=("absolute"===p||"fixed"===p)&&ot.inArray("auto",[o,l])>-1;if(u){r=c.position();s=r.top;n=r.left}else{s=parseFloat(o)||0;n=parseFloat(l)||0}ot.isFunction(t)&&(t=t.call(e,i,a));null!=t.top&&(d.top=t.top-a.top+s);null!=t.left&&(d.left=t.left-a.left+n);"using"in t?t.using.call(e,d):c.css(d)}};ot.fn.extend({offset:function(e){if(arguments.length)return void 0===e?this:this.each(function(t){ot.offset.setOffset(this,e,t)});var t,i,r={top:0,left:0},n=this[0],o=n&&n.ownerDocument;if(o){t=o.documentElement;if(!ot.contains(t,n))return r;typeof n.getBoundingClientRect!==yt&&(r=n.getBoundingClientRect());i=Y(o);return{top:r.top+(i.pageYOffset||t.scrollTop)-(t.clientTop||0),left:r.left+(i.pageXOffset||t.scrollLeft)-(t.clientLeft||0)}}},position:function(){if(this[0]){var e,t,i={top:0,left:0},r=this[0];if("fixed"===ot.css(r,"position"))t=r.getBoundingClientRect();else{e=this.offsetParent();t=this.offset();ot.nodeName(e[0],"html")||(i=e.offset());i.top+=ot.css(e[0],"borderTopWidth",!0);i.left+=ot.css(e[0],"borderLeftWidth",!0)}return{top:t.top-i.top-ot.css(r,"marginTop",!0),left:t.left-i.left-ot.css(r,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){for(var e=this.offsetParent||nr;e&&!ot.nodeName(e,"html")&&"static"===ot.css(e,"position");)e=e.offsetParent;return e||nr})}});ot.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(e,t){var i=/Y/.test(t);ot.fn[e]=function(r){return Ot(this,function(e,r,n){var o=Y(e);if(void 0===n)return o?t in o?o[t]:o.document.documentElement[r]:e[r];o?o.scrollTo(i?ot(o).scrollLeft():n,i?n:ot(o).scrollTop()):e[r]=n;return void 0},e,r,arguments.length,null)}});ot.each(["top","left"],function(e,t){ot.cssHooks[t]=C(rt.pixelPosition,function(e,i){if(i){i=ii(e,t);return ni.test(i)?ot(e).position()[t]+"px":i}})});ot.each({Height:"height",Width:"width"},function(e,t){ot.each({padding:"inner"+e,content:t,"":"outer"+e},function(i,r){ot.fn[r]=function(r,n){var o=arguments.length&&(i||"boolean"!=typeof r),s=i||(r===!0||n===!0?"margin":"border");return Ot(this,function(t,i,r){var n;if(ot.isWindow(t))return t.document.documentElement["client"+e];if(9===t.nodeType){n=t.documentElement;return Math.max(t.body["scroll"+e],n["scroll"+e],t.body["offset"+e],n["offset"+e],n["client"+e])}return void 0===r?ot.css(t,i,s):ot.style(t,i,r,s)},t,o?r:void 0,o,null)}})});ot.fn.size=function(){return this.length};ot.fn.andSelf=ot.fn.addBack;"function"==typeof e&&e.amd&&e("jquery",[],function(){return ot});var or=t.jQuery,sr=t.$;ot.noConflict=function(e){t.$===ot&&(t.$=sr);e&&t.jQuery===ot&&(t.jQuery=or);return ot};typeof i===yt&&(t.jQuery=t.$=ot);return ot})},{}],17:[function(t,i){(function(t){function r(){try{return l in t&&t[l]}catch(e){return!1}}function n(e){return e.replace(/^d/,"___$&").replace(h,"___")}var o,s={},a=t.document,l="localStorage",u="script";s.disabled=!1;s.version="1.3.17";s.set=function(){};s.get=function(){};s.has=function(e){return void 0!==s.get(e)};s.remove=function(){};s.clear=function(){};s.transact=function(e,t,i){if(null==i){i=t;t=null}null==t&&(t={});var r=s.get(e,t);i(r);s.set(e,r)};s.getAll=function(){};s.forEach=function(){};s.serialize=function(e){return JSON.stringify(e)};s.deserialize=function(e){if("string"!=typeof e)return void 0;try{return JSON.parse(e)}catch(t){return e||void 0}};if(r()){o=t[l];s.set=function(e,t){if(void 0===t)return s.remove(e);o.setItem(e,s.serialize(t));return t};s.get=function(e,t){var i=s.deserialize(o.getItem(e));return void 0===i?t:i};s.remove=function(e){o.removeItem(e)};s.clear=function(){o.clear()};s.getAll=function(){var e={};s.forEach(function(t,i){e[t]=i});return e};s.forEach=function(e){for(var t=0;t<o.length;t++){var i=o.key(t);e(i,s.get(i))}}}else if(a.documentElement.addBehavior){var p,c;try{c=new ActiveXObject("htmlfile");c.open();c.write("<"+u+">document.w=window</"+u+'><iframe src="/favicon.ico"></iframe>');c.close();p=c.w.frames[0].document;o=p.createElement("div")}catch(d){o=a.createElement("div");p=a.body}var f=function(e){return function(){var t=Array.prototype.slice.call(arguments,0);t.unshift(o);p.appendChild(o);o.addBehavior("#default#userData");o.load(l);var i=e.apply(s,t);p.removeChild(o);return i}},h=new RegExp("[!\"#$%&'()*+,/\\\\:;<=>?@[\\]^`{|}~]","g");s.set=f(function(e,t,i){t=n(t);if(void 0===i)return s.remove(t);e.setAttribute(t,s.serialize(i));e.save(l);return i});s.get=f(function(e,t,i){t=n(t);var r=s.deserialize(e.getAttribute(t));return void 0===r?i:r});s.remove=f(function(e,t){t=n(t);e.removeAttribute(t);e.save(l)});s.clear=f(function(e){var t=e.XMLDocument.documentElement.attributes;e.load(l);for(var i,r=0;i=t[r];r++)e.removeAttribute(i.name);e.save(l)});s.getAll=function(){var e={};s.forEach(function(t,i){e[t]=i});return e};s.forEach=f(function(e,t){for(var i,r=e.XMLDocument.documentElement.attributes,n=0;i=r[n];++n)t(i.name,s.deserialize(e.getAttribute(i.name)))})}try{var E="__storejs__";s.set(E,E);s.get(E)!=E&&(s.disabled=!0);s.remove(E)}catch(d){s.disabled=!0}s.enabled=!s.disabled;"undefined"!=typeof i&&i.exports&&this.module!==i?i.exports=s:"function"==typeof e&&e.amd?e(s):t.store=s})(Function("return this")())},{}],18:[function(e,t){t.exports={name:"yasgui-utils",version:"1.5.2",description:"Utils for YASGUI libs",main:"src/main.js",repository:{type:"git",url:"git://github.com/YASGUI/Utils.git"},licenses:[{type:"MIT",url:"http://yasgui.github.io/license.txt"}],author:"Laurens Rietveld",maintainers:[{name:"Laurens Rietveld",email:"[email protected]",web:"http://laurensrietveld.nl"}],bugs:{url:"https://github.com/YASGUI/Utils/issues"},homepage:"https://github.com/YASGUI/Utils",dependencies:{store:"^1.3.14"}}},{}],19:[function(e,t){window.console=window.console||{log:function(){}};t.exports={storage:e("./storage.js"),svg:e("./svg.js"),version:{"yasgui-utils":e("../package.json").version},nestedExists:function(e){for(var t=Array.prototype.slice.call(arguments,1),i=0;i<t.length;i++){if(!e||!e.hasOwnProperty(t[i]))return!1;e=e[t[i]]}return!0}}},{"../package.json":18,"./storage.js":20,"./svg.js":21}],20:[function(e,t){{var i=e("store"),r={day:function(){return 864e5},month:function(){30*r.day()},year:function(){12*r.month()}};t.exports={set:function(e,t,n){if(i.enabled&&e&&void 0!==t){"string"==typeof n&&(n=r[n]());t.documentElement&&(t=(new XMLSerializer).serializeToString(t.documentElement));i.set(e,{val:t,exp:n,time:(new Date).getTime()})}},remove:function(e){i.enabled&&e&&i.remove(e)},get:function(e){if(!i.enabled)return null;if(e){var t=i.get(e);return t?t.exp&&(new Date).getTime()-t.time>t.exp?null:t.val:null}return null}}}},{store:17}],21:[function(e,t){t.exports={draw:function(e,i){if(e){var r=t.exports.getElement(i);r&&(e.append?e.append(r):e.appendChild(r))}},getElement:function(e){if(e&&0==e.indexOf("<svg")){var t=new DOMParser,i=t.parseFromString(e,"text/xml"),r=i.documentElement,n=document.createElement("div");n.className="svgImg";n.appendChild(r);return n}return!1}}},{}],22:[function(e,t){t.exports={name:"yasgui-yasqe",description:"Yet Another SPARQL Query Editor",version:"2.3.9",main:"src/main.js",licenses:[{type:"MIT",url:"http://yasqe.yasgui.org/license.txt"}],author:"Laurens Rietveld",homepage:"http://yasqe.yasgui.org",devDependencies:{browserify:"^6.1.0",gulp:"~3.6.0","gulp-bump":"^0.1.11","gulp-concat":"^2.4.1","gulp-connect":"^2.0.5","gulp-embedlr":"^0.5.2","gulp-filter":"^1.0.2","gulp-git":"^0.5.2","gulp-jsvalidate":"^0.2.0","gulp-livereload":"^1.3.1","gulp-minify-css":"0.3.11","gulp-notify":"^2.0.1","gulp-rename":"^1.2.0","gulp-streamify":"0.0.5","gulp-tag-version":"^1.1.0","gulp-uglify":"^1.0.1","require-dir":"^0.1.0","run-sequence":"^1.0.1","vinyl-buffer":"^1.0.0","vinyl-source-stream":"~0.1.1",watchify:"^0.6.4","gulp-sourcemaps":"^1.2.8",exorcist:"^0.1.6","vinyl-transform":"0.0.1","gulp-sass":"^1.2.2","bootstrap-sass":"^3.3.1","browserify-transform-tools":"^1.2.1","gulp-cssimport":"^1.3.1"},bugs:"https://github.com/YASGUI/YASQE/issues/",keywords:["JavaScript","SPARQL","Editor","Semantic Web","Linked Data"],maintainers:[{name:"Laurens Rietveld",email:"[email protected]",web:"http://laurensrietveld.nl"}],repository:{type:"git",url:"https://github.com/YASGUI/YASQE.git"},dependencies:{jquery:"~ 1.11.0",codemirror:"^4.7.0","yasgui-utils":"^1.4.1"},optionalShim:{codemirror:{require:"codemirror",global:"CodeMirror"},jquery:{require:"jquery",global:"jQuery"},"../../lib/codemirror":{require:"codemirror",global:"CodeMirror"}}}},{}],23:[function(e,t){"use strict";var i=e("jquery"),r=e("../utils.js"),n=e("yasgui-utils"),o=e("../../lib/trie.js");t.exports=function(e,t){var a={},l={},u={};t.on("cursorActivity",function(){d(!0)});t.on("change",function(){var e=[];for(var r in a)a[r].is(":visible")&&e.push(a[r]);if(e.length>0){var n=i(t.getWrapperElement()).find(".CodeMirror-vscrollbar"),o=0;n.is(":visible")&&(o=n.outerWidth());e.forEach(function(e){e.css("right",o)})}});var p=function(e,i){u[e.name]=new o;for(var s=0;s<i.length;s++)u[e.name].insert(i[s]);var a=r.getPersistencyId(t,e.persistent);a&&n.storage.set(a,i,"month")},c=function(e,i){var o=l[e]=new i(t,e);o.name=e;if(o.bulk){var s=function(e){e&&e instanceof Array&&e.length>0&&p(o,e)};if(o.get instanceof Array)s(o.get);else{var a=null,u=r.getPersistencyId(t,o.persistent);u&&(a=n.storage.get(u));a&&a.length>0?s(a):o.get instanceof Function&&(o.async?o.get(null,s):s(o.get()))}}},d=function(r){if(!t.somethingSelected()){var n=function(i){if(r&&(!i.autoShow||!i.bulk&&i.async))return!1;var n={closeCharacters:/(?=a)b/,completeSingle:!1};!i.bulk&&i.async&&(n.async=!0);{var o=function(e,t){return f(i,t)};e.showHint(t,o,n)}return!0};for(var o in l)if(-1!=i.inArray(o,t.options.autocompleters)){var s=l[o];if(s.isValidCompletionPosition)if(s.isValidCompletionPosition()){if(!s.callbacks||!s.callbacks.validPosition||s.callbacks.validPosition(t,s)!==!1){var a=n(s);if(a)break}}else s.callbacks&&s.callbacks.invalidPosition&&s.callbacks.invalidPosition(t,s)}}},f=function(e,i){var r=function(t){var i=t.autocompletionString||t.string,r=[];if(u[e.name])r=u[e.name].autoComplete(i);else if("function"==typeof e.get&&0==e.async)r=e.get(i);else if("object"==typeof e.get)for(var n=i.length,o=0;o<e.get.length;o++){var s=e.get[o];s.slice(0,n)==i&&r.push(s)}return h(r,e,t)},n=t.getCompleteToken();e.preProcessToken&&(n=e.preProcessToken(n));if(n){if(e.bulk||!e.async)return r(n);var o=function(t){i(h(t,e,n))};e.get(n,o)}},h=function(e,i,r){for(var n=[],o=0;o<e.length;o++){var a=e[o];i.postProcessToken&&(a=i.postProcessToken(r,a));n.push({text:a,displayText:a,hint:s})}var l=t.getCursor(),u={completionToken:r.string,list:n,from:{line:l.line,ch:r.start},to:{line:l.line,ch:r.end}};if(i.callbacks)for(var p in i.callbacks)i.callbacks[p]&&t.on(u,p,i.callbacks[p]);return u};return{init:c,completers:l,notifications:{getEl:function(e){return i(a[e.name])},show:function(e,t){if(!t.autoshow){a[t.name]||(a[t.name]=i("<div class='completionNotification'></div>"));a[t.name].show().text("Press "+(-1!=navigator.userAgent.indexOf("Mac OS X")?"CMD":"CTRL")+" - <spacebar> to autocomplete").appendTo(i(e.getWrapperElement()))}},hide:function(e,t){a[t.name]&&a[t.name].hide()}},autoComplete:d,getTrie:function(e){return"string"==typeof e?u[e]:u[e.name]}}};var s=function(e,t,i){i.text!=e.getTokenAt(e.getCursor()).string&&e.replaceRange(i.text,t.from,t.to)}},{"../../lib/trie.js":5,"../utils.js":36,jquery:16,"yasgui-utils":19}],24:[function(e,t){"use strict";e("jquery");t.exports=function(i,r){return{isValidCompletionPosition:function(){return t.exports.isValidCompletionPosition(i)},get:function(t,r){return e("./utils").fetchFromLov(i,this,t,r)},preProcessToken:function(e){return t.exports.preProcessToken(i,e)},postProcessToken:function(e,r){return t.exports.postProcessToken(i,e,r)},async:!0,bulk:!1,autoShow:!1,persistent:r,callbacks:{validPosition:i.autocompleters.notifications.show,invalidPosition:i.autocompleters.notifications.hide}}};t.exports.isValidCompletionPosition=function(e){var t=e.getCompleteToken();if(0==t.string.indexOf("?"))return!1;var i=e.getCursor(),r=e.getPreviousNonWsToken(i.line,t);return"a"==r.string?!0:"rdf:type"==r.string?!0:"rdfs:domain"==r.string?!0:"rdfs:range"==r.string?!0:!1};t.exports.preProcessToken=function(t,i){return e("./utils.js").preprocessResourceTokenForCompletion(t,i)};t.exports.postProcessToken=function(t,i,r){return e("./utils.js").postprocessResourceTokenForCompletion(t,i,r)}},{"./utils":27,"./utils.js":27,jquery:16}],25:[function(e,t){"use strict";var i=e("jquery"),r={"string-2":"prefixed",atom:"var"};t.exports=function(e,r){e.on("change",function(){t.exports.appendPrefixIfNeeded(e,r)});return{isValidCompletionPosition:function(){return t.exports.isValidCompletionPosition(e)},get:function(e,t){i.get("http://prefix.cc/popular/all.file.json",function(e){var i=[];for(var r in e)if("bif"!=r){var n=r+": <"+e[r]+">";i.push(n)}i.sort();t(i)})},preProcessToken:function(i){return t.exports.preprocessPrefixTokenForCompletion(e,i)},async:!0,bulk:!0,autoShow:!0,persistent:r}};t.exports.isValidCompletionPosition=function(e){var t=e.getCursor(),r=e.getTokenAt(t);if(e.getLine(t.line).length>t.ch)return!1;"ws"!=r.type&&(r=e.getCompleteToken());if(0==!r.string.indexOf("a")&&-1==i.inArray("PNAME_NS",r.state.possibleCurrent))return!1;var n=e.getPreviousNonWsToken(t.line,r);return n&&"PREFIX"==n.string.toUpperCase()?!0:!1};t.exports.preprocessPrefixTokenForCompletion=function(e,t){var i=e.getPreviousNonWsToken(e.getCursor().line,t);i&&i.string&&":"==i.string.slice(-1)&&(t={start:i.start,end:t.end,string:i.string+" "+t.string,state:t.state});return t};t.exports.appendPrefixIfNeeded=function(e,t){if(e.autocompleters.getTrie(t)&&e.options.autocompleters&&-1!=e.options.autocompleters.indexOf(t)){var i=e.getCursor(),n=e.getTokenAt(i);if("prefixed"==r[n.type]){var o=n.string.indexOf(":");if(-1!==o){var s=e.getPreviousNonWsToken(i.line,n).string.toUpperCase(),a=e.getTokenAt({line:i.line,ch:n.start});if("PREFIX"!=s&&("ws"==a.type||null==a.type)){var l=n.string.substring(0,o+1),u=e.getPrefixesFromQuery();if(null==u[l.slice(0,-1)]){var p=e.autocompleters.getTrie(t).autoComplete(l);p.length>0&&e.addPrefixes(p[0])}}}}}}},{jquery:16}],26:[function(e,t){"use strict";var i=e("jquery");t.exports=function(i,r){return{isValidCompletionPosition:function(){return t.exports.isValidCompletionPosition(i)},get:function(t,r){return e("./utils").fetchFromLov(i,this,t,r)},preProcessToken:function(e){return t.exports.preProcessToken(i,e)},postProcessToken:function(e,r){return t.exports.postProcessToken(i,e,r)},async:!0,bulk:!1,autoShow:!1,persistent:r,callbacks:{validPosition:i.autocompleters.notifications.show,invalidPosition:i.autocompleters.notifications.hide}}};t.exports.isValidCompletionPosition=function(e){var t=e.getCompleteToken();if(0==t.string.length)return!1;if(0==t.string.indexOf("?"))return!1;if(i.inArray("a",t.state.possibleCurrent)>=0)return!0;var r=e.getCursor(),n=e.getPreviousNonWsToken(r.line,t);return"rdfs:subPropertyOf"==n.string?!0:!1};t.exports.preProcessToken=function(t,i){return e("./utils.js").preprocessResourceTokenForCompletion(t,i)};t.exports.postProcessToken=function(t,i,r){return e("./utils.js").postprocessResourceTokenForCompletion(t,i,r)}},{"./utils":27,"./utils.js":27,jquery:16}],27:[function(e,t){"use strict";var i=e("jquery"),r=(e("./utils.js"),e("yasgui-utils")),n=function(e,t){var i=e.getPrefixesFromQuery();if(0==!t.string.indexOf("<")){t.tokenPrefix=t.string.substring(0,t.string.indexOf(":")+1);null!=i[t.tokenPrefix.slice(0,-1)]&&(t.tokenPrefixUri=i[t.tokenPrefix.slice(0,-1)])}t.autocompletionString=t.string.trim();if(0==!t.string.indexOf("<")&&t.string.indexOf(":")>-1)for(var r in i)if(0==t.string.indexOf(r)){t.autocompletionString=i[r];t.autocompletionString+=t.string.substring(r.length+1);break}0==t.autocompletionString.indexOf("<")&&(t.autocompletionString=t.autocompletionString.substring(1));-1!==t.autocompletionString.indexOf(">",t.length-1)&&(t.autocompletionString=t.autocompletionString.substring(0,t.autocompletionString.length-1));return t},o=function(e,t,i){i=t.tokenPrefix&&t.autocompletionString&&t.tokenPrefixUri?t.tokenPrefix+i.substring(t.tokenPrefixUri.length):"<"+i+">";return i},s=function(t,n,o,s){if(!o||!o.string||0==o.string.trim().length){t.autocompleters.notifications.getEl(n).empty().append("Nothing to autocomplete yet!");return!1}var a=50,l={q:o.autocompletionString,page:1};l.type="classes"==n.name?"class":"property";var u=[],p="",c=function(){p="http://lov.okfn.org/dataset/lov/api/v2/autocomplete/terms?"+i.param(l)};c();var d=function(){l.page++;c()},f=function(){i.get(p,function(e){for(var r=0;r<e.results.length;r++)u.push(i.isArray(e.results[r].uri)&&e.results[r].uri.length>0?e.results[r].uri[0]:e.results[r].uri);if(u.length<e.total_results&&u.length<a){d();f()}else{u.length>0?t.autocompleters.notifications.hide(t,n):t.autocompleters.notifications.getEl(n).text("0 matches found...");s(u)}}).fail(function(){t.autocompleters.notifications.getEl(n).empty().append("Failed fetching suggestions..")})};t.autocompleters.notifications.getEl(n).empty().append(i("<span>Fetchting autocompletions </span>")).append(i(r.svg.getElement(e("../imgs.js").loader)).addClass("notificationLoader"));f()};t.exports={fetchFromLov:s,preprocessResourceTokenForCompletion:n,postprocessResourceTokenForCompletion:o}},{"../imgs.js":30,"./utils.js":27,jquery:16,"yasgui-utils":19}],28:[function(e,t){"use strict";var i=e("jquery");t.exports=function(e){return{isValidCompletionPosition:function(){var t=e.getTokenAt(e.getCursor());if("ws"!=t.type){t=e.getCompleteToken(t);if(t&&0==t.string.indexOf("?"))return!0}return!1},get:function(t){if(0==t.trim().length)return[];var r={};i(e.getWrapperElement()).find(".cm-atom").each(function(){var e=this.innerHTML;if(0==e.indexOf("?")){var n=i(this).next(),o=n.attr("class");o&&n.attr("class").indexOf("cm-atom")>=0&&(e+=n.text());if(e.length<=1)return;if(0!==e.indexOf(t))return;if(e==t)return;r[e]=!0}});var n=[];for(var o in r)n.push(o);n.sort();return n},async:!1,bulk:!1,autoShow:!0}}},{jquery:16}],29:[function(e){var t=e("jquery"),i=e("./main.js");i.defaults=t.extend(!0,{},i.defaults,{mode:"sparql11",value:"PREFIX rdf: <http://www.w3.org/1999/02/22-rdf-syntax-ns#>\nPREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>\nSELECT * WHERE {\n ?sub ?pred ?obj .\n} \nLIMIT 10",highlightSelectionMatches:{showToken:/\w/},tabMode:"indent",lineNumbers:!0,lineWrapping:!0,backdrop:!1,foldGutter:{rangeFinder:i.fold.brace},gutters:["gutterErrorBar","CodeMirror-linenumbers","CodeMirror-foldgutter"],matchBrackets:!0,fixedGutter:!0,syntaxErrorCheck:!0,extraKeys:{"Ctrl-Space":i.autoComplete,"Cmd-Space":i.autoComplete,"Ctrl-D":i.deleteLine,"Ctrl-K":i.deleteLine,"Cmd-D":i.deleteLine,"Cmd-K":i.deleteLine,"Ctrl-/":i.commentLines,"Cmd-/":i.commentLines,"Ctrl-Alt-Down":i.copyLineDown,"Ctrl-Alt-Up":i.copyLineUp,"Cmd-Alt-Down":i.copyLineDown,"Cmd-Alt-Up":i.copyLineUp,"Shift-Ctrl-F":i.doAutoFormat,"Shift-Cmd-F":i.doAutoFormat,"Ctrl-]":i.indentMore,"Cmd-]":i.indentMore,"Ctrl-[":i.indentLess,"Cmd-[":i.indentLess,"Ctrl-S":i.storeQuery,"Cmd-S":i.storeQuery,"Ctrl-Enter":i.executeQuery,"Cmd-Enter":i.executeQuery,F11:function(e){e.setOption("fullScreen",!e.getOption("fullScreen"))},Esc:function(e){e.getOption("fullScreen")&&e.setOption("fullScreen",!1)}},cursorHeight:.9,createShareLink:i.createShareLink,consumeShareLink:i.consumeShareLink,persistent:function(e){return"yasqe_"+t(e.getWrapperElement()).closest("[id]").attr("id")+"_queryVal"},sparql:{showQueryButton:!1,endpoint:"http://dbpedia.org/sparql",requestMethod:"POST",acceptHeaderGraph:"text/turtle,*/*;q=0.9",acceptHeaderSelect:"application/sparql-results+json,*/*;q=0.9",acceptHeaderUpdate:"text/plain,*/*;q=0.9",namedGraphs:[],defaultGraphs:[],args:[],headers:{},callbacks:{beforeSend:null,complete:null,error:null,success:null},handlers:{}}})},{"./main.js":31,jquery:16}],30:[function(e,t){"use strict";t.exports={loader:'<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" width="100%" height="100%" fill="black"> <circle cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(45 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.125s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(90 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.25s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(135 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.375s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(180 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.5s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(225 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.625s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(270 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.75s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(315 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.875s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle> <circle transform="rotate(180 16 16)" cx="16" cy="3" r="0"> <animate attributeName="r" values="0;3;0;0" dur="1s" repeatCount="indefinite" begin="0.5s" keySplines="0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8;0.2 0.2 0.4 0.8" calcMode="spline" /> </circle></svg>',query:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 80 80" enable-background="new 0 0 80 80" xml:space="preserve"><g ></g><g > <path d="M64.622,2.411H14.995c-6.627,0-12,5.373-12,12v49.897c0,6.627,5.373,12,12,12h49.627c6.627,0,12-5.373,12-12V14.411 C76.622,7.783,71.249,2.411,64.622,2.411z M24.125,63.906V15.093L61,39.168L24.125,63.906z"/></g></svg>',queryInvalid:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 73.627 73.897" enable-background="new 0 0 80 80" xml:space="preserve" inkscape:version="0.48.4 r9939" sodipodi:docname="warning.svg"><metadata ><rdf:RDF><cc:Work rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /></cc:Work></rdf:RDF></metadata><defs /><sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="1855" inkscape:window-height="1056" showgrid="false" inkscape:zoom="3.1936344" inkscape:cx="36.8135" inkscape:cy="36.9485" inkscape:window-x="2625" inkscape:window-y="24" inkscape:window-maximized="1" inkscape:current-layer="svg2" /><g transform="translate(-2.995,-2.411)" /><g transform="translate(-2.995,-2.411)" ><path d="M 64.622,2.411 H 14.995 c -6.627,0 -12,5.373 -12,12 v 49.897 c 0,6.627 5.373,12 12,12 h 49.627 c 6.627,0 12,-5.373 12,-12 V 14.411 c 0,-6.628 -5.373,-12 -12,-12 z M 24.125,63.906 V 15.093 L 61,39.168 24.125,63.906 z" inkscape:connector-curvature="0" /></g><path d="M 66.129381,65.903784 H 49.769875 c -1.64721,0 -2.889385,-0.581146 -3.498678,-1.63595 -0.609293,-1.055608 -0.491079,-2.422161 0.332391,-3.848223 l 8.179753,-14.167069 c 0.822934,-1.42633 1.9477,-2.211737 3.166018,-2.211737 1.218319,0 2.343086,0.785407 3.166019,2.211737 l 8.179751,14.167069 c 0.823472,1.426062 0.941686,2.792615 0.33239,3.848223 -0.609023,1.054804 -1.851197,1.63595 -3.498138,1.63595 z M 59.618815,60.91766 c 0,-0.850276 -0.68944,-1.539719 -1.539717,-1.539719 -0.850276,0 -1.539718,0.689443 -1.539718,1.539719 0,0.850277 0.689442,1.539718 1.539718,1.539718 0.850277,0 1.539717,-0.689441 1.539717,-1.539718 z m 0.04155,-9.265919 c 0,-0.873061 -0.707939,-1.580998 -1.580999,-1.580998 -0.873061,0 -1.580999,0.707937 -1.580999,1.580998 l 0.373403,5.610965 h 0.0051 c 0.05415,0.619747 0.568548,1.10761 1.202504,1.10761 0.586239,0 1.075443,-0.415756 1.188563,-0.968489 0.0092,-0.04476 0.0099,-0.09248 0.01392,-0.138854 h 0.01072 l 0.367776,-5.611232 z" inkscape:connector-curvature="0" style="fill:#aa8800" /></svg>',download:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" baseProfile="tiny" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 100 100" xml:space="preserve"><g ></g><g > <path fill-rule="evenodd" fill="#000000" d="M88,84v-2c0-2.961-0.859-4-4-4H16c-2.961,0-4,0.98-4,4v2c0,3.102,1.039,4,4,4h68 C87.02,88,88,87.039,88,84z M58,12H42c-5,0-6,0.941-6,6v22H16l34,34l34-34H64V18C64,12.941,62.939,12,58,12z"/></g></svg>',share:'<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="0 0 100 100" style="enable-background:new 0 0 100 100;" xml:space="preserve"><path d="M36.764,50c0,0.308-0.07,0.598-0.088,0.905l32.247,16.119c2.76-2.338,6.293-3.797,10.195-3.797 C87.89,63.228,95,70.338,95,79.109C95,87.89,87.89,95,79.118,95c-8.78,0-15.882-7.11-15.882-15.891c0-0.316,0.07-0.598,0.088-0.905 L31.077,62.085c-2.769,2.329-6.293,3.788-10.195,3.788C12.11,65.873,5,58.771,5,50c0-8.78,7.11-15.891,15.882-15.891 c3.902,0,7.427,1.468,10.195,3.797l32.247-16.119c-0.018-0.308-0.088-0.598-0.088-0.914C63.236,12.11,70.338,5,79.118,5 C87.89,5,95,12.11,95,20.873c0,8.78-7.11,15.891-15.882,15.891c-3.911,0-7.436-1.468-10.195-3.806L36.676,49.086 C36.693,49.394,36.764,49.684,36.764,50z"/></svg>',warning:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" viewBox="0 0 66.399998 66.399998" enable-background="new 0 0 69.3 69.3" xml:space="preserve" height="100%" width="100%" inkscape:version="0.48.4 r9939" ><g transform="translate(-1.5,-1.5)" style="fill:#ff0000"><path d="M 34.7,1.5 C 16.4,1.5 1.5,16.4 1.5,34.7 1.5,53 16.4,67.9 34.7,67.9 53,67.9 67.9,53 67.9,34.7 67.9,16.4 53,1.5 34.7,1.5 z m 0,59.4 C 20.2,60.9 8.5,49.1 8.5,34.7 8.5,20.2 20.3,8.5 34.7,8.5 c 14.4,0 26.2,11.8 26.2,26.2 0,14.4 -11.8,26.2 -26.2,26.2 z" inkscape:connector-curvature="0" style="fill:#ff0000" /><path d="m 34.6,47.1 c -1.4,0 -2.5,0.5 -3.5,1.5 -0.9,1 -1.4,2.2 -1.4,3.6 0,1.6 0.5,2.8 1.5,3.8 1,0.9 2.1,1.3 3.4,1.3 1.3,0 2.4,-0.5 3.4,-1.4 1,-0.9 1.5,-2.2 1.5,-3.7 0,-1.4 -0.5,-2.6 -1.4,-3.6 -0.9,-1 -2.1,-1.5 -3.5,-1.5 z" inkscape:connector-curvature="0" style="fill:#ff0000" /><path d="m 34.8,13.9 c -1.5,0 -2.8,0.5 -3.7,1.6 -0.9,1 -1.4,2.4 -1.4,4.2 0,1.1 0.1,2.9 0.2,5.6 l 0.8,13.1 c 0.2,1.8 0.4,3.2 0.9,4.1 0.5,1.2 1.5,1.8 2.9,1.8 1.3,0 2.3,-0.7 2.9,-1.9 0.5,-1 0.7,-2.3 0.9,-4 L 39.4,25 c 0.1,-1.3 0.2,-2.5 0.2,-3.8 0,-2.2 -0.3,-3.9 -0.8,-5.1 -0.5,-1 -1.6,-2.2 -4,-2.2 z" inkscape:connector-curvature="0" style="fill:#ff0000" /></g></svg>',fullscreen:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="5 -10 74.074074 100" enable-background="new 0 0 100 100" xml:space="preserve" inkscape:version="0.48.4 r9939" sodipodi:docname="noun_2186_cc.svg"><metadata ><rdf:RDF><cc:Work rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /></cc:Work></rdf:RDF></metadata><defs /><sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="640" inkscape:window-height="480" showgrid="false" fit-margin-top="0" fit-margin-left="0" fit-margin-right="0" fit-margin-bottom="0" inkscape:zoom="2.36" inkscape:cx="44.101509" inkscape:cy="31.481481" inkscape:window-x="65" inkscape:window-y="24" inkscape:window-maximized="0" inkscape:current-layer="Layer_1" /><path d="m -7.962963,-10 v 38.889 l 16.667,-16.667 16.667,16.667 5.555,-5.555 -16.667,-16.667 16.667,-16.667 h -38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 92.037037,-10 v 38.889 l -16.667,-16.667 -16.666,16.667 -5.556,-5.555 16.666,-16.667 -16.666,-16.667 h 38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="M -7.962963,90 V 51.111 l 16.667,16.666 16.667,-16.666 5.555,5.556 -16.667,16.666 16.667,16.667 h -38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="M 92.037037,90 V 51.111 l -16.667,16.666 -16.666,-16.666 -5.556,5.556 16.666,16.666 -16.666,16.667 h 38.889 z" inkscape:connector-curvature="0" style="fill:#010101" /></svg>',smallscreen:'<svg xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:cc="http://creativecommons.org/ns#" xmlns:rdf="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:svg="http://www.w3.org/2000/svg" xmlns="http://www.w3.org/2000/svg" xmlns:sodipodi="http://sodipodi.sourceforge.net/DTD/sodipodi-0.dtd" xmlns:inkscape="http://www.inkscape.org/namespaces/inkscape" version="1.1" x="0px" y="0px" width="100%" height="100%" viewBox="5 -10 74.074074 100" enable-background="new 0 0 100 100" xml:space="preserve" inkscape:version="0.48.4 r9939" sodipodi:docname="noun_2186_cc.svg"><metadata ><rdf:RDF><cc:Work rdf:about=""><dc:format>image/svg+xml</dc:format><dc:type rdf:resource="http://purl.org/dc/dcmitype/StillImage" /></cc:Work></rdf:RDF></metadata><defs /><sodipodi:namedview pagecolor="#ffffff" bordercolor="#666666" borderopacity="1" objecttolerance="10" gridtolerance="10" guidetolerance="10" inkscape:pageopacity="0" inkscape:pageshadow="2" inkscape:window-width="1855" inkscape:window-height="1056" showgrid="false" fit-margin-top="0" fit-margin-left="0" fit-margin-right="0" fit-margin-bottom="0" inkscape:zoom="2.36" inkscape:cx="44.101509" inkscape:cy="31.481481" inkscape:window-x="65" inkscape:window-y="24" inkscape:window-maximized="1" inkscape:current-layer="Layer_1" /><path d="m 30.926037,28.889 0,-38.889 -16.667,16.667 -16.667,-16.667 -5.555,5.555 16.667,16.667 -16.667,16.667 38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 53.148037,28.889 0,-38.889 16.667,16.667 16.666,-16.667 5.556,5.555 -16.666,16.667 16.666,16.667 -38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 30.926037,51.111 0,38.889 -16.667,-16.666 -16.667,16.666 -5.555,-5.556 16.667,-16.666 -16.667,-16.667 38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /><path d="m 53.148037,51.111 0,38.889 16.667,-16.666 16.666,16.666 5.556,-5.556 -16.666,-16.666 16.666,-16.667 -38.889,0 z" inkscape:connector-curvature="0" style="fill:#010101" /></svg>'}
},{}],31:[function(e,t){"use strict";window.console=window.console||{log:function(){}};var i=e("jquery"),r=e("codemirror"),n=e("./utils.js"),o=e("yasgui-utils"),s=e("./imgs.js");e("../lib/deparam.js");e("codemirror/addon/fold/foldcode.js");e("codemirror/addon/fold/foldgutter.js");e("codemirror/addon/fold/xml-fold.js");e("codemirror/addon/fold/brace-fold.js");e("codemirror/addon/hint/show-hint.js");e("codemirror/addon/search/searchcursor.js");e("codemirror/addon/edit/matchbrackets.js");e("codemirror/addon/runmode/runmode.js");e("codemirror/addon/display/fullscreen.js");e("../lib/grammar/tokenizer.js");var a=t.exports=function(e,t){var n=i("<div>",{"class":"yasqe"}).appendTo(i(e));t=l(t);var o=u(r(n[0],t));d(o);return o},l=function(e){var t=i.extend(!0,{},a.defaults,e);return t},u=function(t){t.autocompleters=e("./autocompleters/autocompleterBase.js")(a,t);t.options.autocompleters&&t.options.autocompleters.forEach(function(e){a.Autocompleters[e]&&t.autocompleters.init(e,a.Autocompleters[e])});t.getCompleteToken=function(i,r){return e("./tokenUtils.js").getCompleteToken(t,i,r)};t.getPreviousNonWsToken=function(i,r){return e("./tokenUtils.js").getPreviousNonWsToken(t,i,r)};t.getNextNonWsToken=function(i,r){return e("./tokenUtils.js").getNextNonWsToken(t,i,r)};var r=null,n=null;t.setBackdrop=function(e){if(t.options.backdrop||0===t.options.backdrop||"0"===t.options.backdrop){if(null===n){n=+t.options.backdrop;1===n&&(n=400)}r||(r=i("<div>",{"class":"backdrop"}).click(function(){i(this).hide()}).insertAfter(i(t.getWrapperElement())));e?r.show(n):r.hide(n)}};t.query=function(e){a.executeQuery(t,e)};t.getUrlArguments=function(e){return a.getUrlArguments(t,e)};t.getPrefixesFromQuery=function(){return e("./prefixUtils.js").getPrefixesFromQuery(t)};t.addPrefixes=function(i){return e("./prefixUtils.js").addPrefixes(t,i)};t.removePrefixes=function(i){return e("./prefixUtils.js").removePrefixes(t,i)};t.getValueWithoutComments=function(){var e="";a.runMode(t.getValue(),"sparql11",function(t,i){"comment"!=i&&(e+=t)});return e};t.getQueryType=function(){return t.queryType};t.getQueryMode=function(){var e=t.getQueryType();return"INSERT"==e||"DELETE"==e||"LOAD"==e||"CLEAR"==e||"CREATE"==e||"DROP"==e||"COPY"==e||"MOVE"==e||"ADD"==e?"update":"query"};t.setCheckSyntaxErrors=function(e){t.options.syntaxErrorCheck=e;h(t)};t.enableCompleter=function(e){p(t.options,e);a.Autocompleters[e]&&t.autocompleters.init(e,a.Autocompleters[e])};t.disableCompleter=function(e){c(t.options,e)};return t},p=function(e,t){e.autocompleters||(e.autocompleters=[]);e.autocompleters.push(t)},c=function(e,t){if("object"==typeof e.autocompleters){var r=i.inArray(t,e.autocompleters);if(r>=0){e.autocompleters.splice(r,1);c(e,t)}}},d=function(e){var t=n.getPersistencyId(e,e.options.persistent);if(t){var r=o.storage.get(t);r&&e.setValue(r)}a.drawButtons(e);e.on("blur",function(e){a.storeQuery(e)});e.on("change",function(e){h(e);a.updateQueryButton(e);a.positionButtons(e)});e.on("changes",function(){h(e);a.updateQueryButton(e);a.positionButtons(e)});e.on("cursorActivity",function(e){f(e)});e.prevQueryValid=!1;h(e);a.positionButtons(e);if(e.options.consumeShareLink){var s=i.deparam(window.location.search.substring(1));e.options.consumeShareLink(e,s)}},f=function(e){e.cursor=i(".CodeMirror-cursor");e.buttons&&e.buttons.is(":visible")&&e.cursor.length>0&&(n.elementsOverlap(e.cursor,e.buttons)?e.buttons.find("svg").attr("opacity","0.2"):e.buttons.find("svg").attr("opacity","1.0"))},h=function(t,r){t.queryValid=!0;t.clearGutter("gutterErrorBar");for(var n=null,a=0;a<t.lineCount();++a){var l=!1;t.prevQueryValid||(l=!0);var u=t.getTokenAt({line:a,ch:t.getLine(a).length},l),n=u.state;t.queryType=n.queryType;if(0==n.OK){if(!t.options.syntaxErrorCheck){i(t.getWrapperElement).find(".sp-error").css("color","black");return}var p=o.svg.getElement(s.warning);n.possibleCurrent&&n.possibleCurrent.length>0&&e("./tooltip")(t,p,function(){var e=[];n.possibleCurrent.forEach(function(t){e.push("<strong style='text-decoration:underline'>"+i("<div/>").text(t).html()+"</strong>")});return"This line is invalid. Expected: "+e.join(", ")});p.style.marginTop="2px";p.style.marginLeft="2px";p.className="parseErrorIcon";t.setGutterMarker(a,"gutterErrorBar",p);t.queryValid=!1;break}}t.prevQueryValid=t.queryValid;if(r&&null!=n&&void 0!=n.stack){var c=n.stack,d=n.stack.length;d>1?t.queryValid=!1:1==d&&"solutionModifier"!=c[0]&&"?limitOffsetClauses"!=c[0]&&"?offsetClause"!=c[0]&&(t.queryValid=!1)}};i.extend(a,r);a.Autocompleters={};a.registerAutocompleter=function(e,t){a.Autocompleters[e]=t;p(a.defaults,e)};a.autoComplete=function(e){e.autocompleters.autoComplete(!1)};a.registerAutocompleter("prefixes",e("./autocompleters/prefixes.js"));a.registerAutocompleter("properties",e("./autocompleters/properties.js"));a.registerAutocompleter("classes",e("./autocompleters/classes.js"));a.registerAutocompleter("variables",e("./autocompleters/variables.js"));a.positionButtons=function(e){var t=i(e.getWrapperElement()).find(".CodeMirror-vscrollbar"),r=0;t.is(":visible")&&(r=t.outerWidth());e.buttons.is(":visible")&&e.buttons.css("right",r+6)};a.createShareLink=function(e){var t=i.deparam(window.location.search.substring(1));t.query=e.getValue();return t};a.consumeShareLink=function(e,t){t.query&&e.setValue(t.query)};a.drawButtons=function(e){e.buttons=i("<div class='yasqe_buttons'></div>").appendTo(i(e.getWrapperElement()));if(e.options.createShareLink){var t=i(o.svg.getElement(s.share));t.click(function(r){r.stopPropagation();var n=i("<div class='yasqe_sharePopup'></div>").appendTo(e.buttons);i("html").click(function(){n&&n.remove()});n.click(function(e){e.stopPropagation()});var o=i("<textarea></textarea>").val(location.protocol+"//"+location.host+location.pathname+"?"+i.param(e.options.createShareLink(e)));o.focus(function(){var e=i(this);e.select();e.mouseup(function(){e.unbind("mouseup");return!1})});n.empty().append(o);var s=t.position();n.css("top",s.top+t.outerHeight()+"px").css("left",s.left+t.outerWidth()-n.outerWidth()+"px")}).addClass("yasqe_share").attr("title","Share your query").appendTo(e.buttons)}var r=i("<div>",{"class":"fullscreenToggleBtns"}).append(i(o.svg.getElement(s.fullscreen)).addClass("yasqe_fullscreenBtn").attr("title","Set editor full screen").click(function(){e.setOption("fullScreen",!0)})).append(i(o.svg.getElement(s.smallscreen)).addClass("yasqe_smallscreenBtn").attr("title","Set editor to normale size").click(function(){e.setOption("fullScreen",!1)}));e.buttons.append(r);if(e.options.sparql.showQueryButton){i("<div>",{"class":"yasqe_queryButton"}).click(function(){if(i(this).hasClass("query_busy")){e.xhr&&e.xhr.abort();a.updateQueryButton(e)}else e.query()}).appendTo(e.buttons);a.updateQueryButton(e)}};var E={busy:"loader",valid:"query",error:"queryInvalid"};a.updateQueryButton=function(e,t){var r=i(e.getWrapperElement()).find(".yasqe_queryButton");if(0!=r.length){if(!t){t="valid";e.queryValid===!1&&(t="error")}if(t!=e.queryStatus&&("busy"==t||"valid"==t||"error"==t)){r.empty().removeClass(function(e,t){return t.split(" ").filter(function(e){return 0==e.indexOf("query_")}).join(" ")}).addClass("query_"+t);o.svg.draw(r,s[E[t]]);e.queryStatus=t}}};a.fromTextArea=function(e,t){t=l(t);var n=(i("<div>",{"class":"yasqe"}).insertBefore(i(e)).append(i(e)),u(r.fromTextArea(e,t)));d(n);return n};a.storeQuery=function(e){var t=n.getPersistencyId(e,e.options.persistent);t&&o.storage.set(t,e.getValue(),"month")};a.commentLines=function(e){for(var t=e.getCursor(!0).line,i=e.getCursor(!1).line,r=Math.min(t,i),n=Math.max(t,i),o=!0,s=r;n>=s;s++){var a=e.getLine(s);if(0==a.length||"#"!=a.substring(0,1)){o=!1;break}}for(var s=r;n>=s;s++)o?e.replaceRange("",{line:s,ch:0},{line:s,ch:1}):e.replaceRange("#",{line:s,ch:0})};a.copyLineUp=function(e){var t=e.getCursor(),i=e.lineCount();e.replaceRange("\n",{line:i-1,ch:e.getLine(i-1).length});for(var r=i;r>t.line;r--){var n=e.getLine(r-1);e.replaceRange(n,{line:r,ch:0},{line:r,ch:e.getLine(r).length})}};a.copyLineDown=function(e){a.copyLineUp(e);var t=e.getCursor();t.line++;e.setCursor(t)};a.doAutoFormat=function(e){if(e.somethingSelected()){var t={line:e.getCursor(!1).line,ch:e.getSelection().length};m(e,e.getCursor(!0),t)}else{var i=e.lineCount(),r=e.getTextArea().value.length;m(e,{line:0,ch:0},{line:i,ch:r})}};var m=function(e,t,i){var r=e.indexFromPos(t),n=e.indexFromPos(i),o=g(e.getValue(),r,n);e.operation(function(){e.replaceRange(o,t,i);for(var n=e.posFromIndex(r).line,s=e.posFromIndex(r+o.length).line,a=n;s>=a;a++)e.indentLine(a,"smart")})},g=function(e,t,n){e=e.substring(t,n);var o=[["keyword","ws","prefixed","ws","uri"],["keyword","ws","uri"]],s=["{",".",";"],a=["}"],l=function(e){for(var t=0;t<o.length;t++)if(c.valueOf().toString()==o[t].valueOf().toString())return 1;for(var t=0;t<s.length;t++)if(e==s[t])return 1;for(var t=0;t<a.length;t++)if(""!=i.trim(p)&&e==a[t])return-1;return 0},u="",p="",c=[];r.runMode(e,"sparql11",function(e,t){c.push(t);var i=l(e,t);if(0!=i){if(1==i){u+=e+"\n";p=""}else{u+="\n"+e;p=e}c=[]}else{p+=e;u+=e}1==c.length&&"sp-ws"==c[0]&&(c=[])});return i.trim(u.replace(/\n\s*\n/g,"\n"))};e("./sparql.js"),e("./defaults.js");a.version={CodeMirror:r.version,YASQE:e("../package.json").version,jquery:i.fn.jquery,"yasgui-utils":o.version}},{"../lib/deparam.js":2,"../lib/grammar/tokenizer.js":4,"../package.json":22,"./autocompleters/autocompleterBase.js":23,"./autocompleters/classes.js":24,"./autocompleters/prefixes.js":25,"./autocompleters/properties.js":26,"./autocompleters/variables.js":28,"./defaults.js":29,"./imgs.js":30,"./prefixUtils.js":32,"./sparql.js":33,"./tokenUtils.js":34,"./tooltip":35,"./utils.js":36,codemirror:15,"codemirror/addon/display/fullscreen.js":6,"codemirror/addon/edit/matchbrackets.js":7,"codemirror/addon/fold/brace-fold.js":8,"codemirror/addon/fold/foldcode.js":9,"codemirror/addon/fold/foldgutter.js":10,"codemirror/addon/fold/xml-fold.js":11,"codemirror/addon/hint/show-hint.js":12,"codemirror/addon/runmode/runmode.js":13,"codemirror/addon/search/searchcursor.js":14,jquery:16,"yasgui-utils":19}],32:[function(e,t){"use strict";var i=function(e,t){var i=e.getPrefixesFromQuery();if("string"==typeof t)r(e,t);else for(var n in t)n in i||r(e,n+": <"+t[n]+">")},r=function(e,t){for(var i=null,r=0,n=e.lineCount(),o=0;n>o;o++){var a=e.getNextNonWsToken(o);if(null!=a&&("PREFIX"==a.string||"BASE"==a.string)){i=a;r=o}}if(null==i)e.replaceRange("PREFIX "+t+"\n",{line:0,ch:0});else{var l=s(e,r);e.replaceRange("\n"+l+"PREFIX "+t,{line:r})}},n=function(e,t){var i=function(e){return e.replace(/[-\/\\^$*+?.()|[\]{}]/g,"\\$&")};for(var r in t)e.setValue(e.getValue().replace(new RegExp("PREFIX\\s*"+r+":\\s*"+i("<"+t[r]+">")+"\\s*","ig"),""))},o=function(e){for(var t={},i=!0,r=function(n,s){if(i){s||(s=1);var a=e.getNextNonWsToken(o,s);if(a){-1==a.state.possibleCurrent.indexOf("PREFIX")&&-1==a.state.possibleNext.indexOf("PREFIX")&&(i=!1);if("PREFIX"==a.string.toUpperCase()){var l=e.getNextNonWsToken(o,a.end+1);if(l){var u=e.getNextNonWsToken(o,l.end+1);if(u){var p=u.string;0==p.indexOf("<")&&(p=p.substring(1));">"==p.slice(-1)&&(p=p.substring(0,p.length-1));t[l.string.slice(0,-1)]=p;r(n,u.end+1)}else r(n,l.end+1)}else r(n,a.end+1)}else r(n,a.end+1)}}},n=e.lineCount(),o=0;n>o&&i;o++)r(o);return t},s=function(e,t,i){void 0==i&&(i=1);var r=e.getTokenAt({line:t,ch:i});return null==r||void 0==r||"ws"!=r.type?"":r.string+s(e,t,r.end+1)};t.exports={addPrefixes:i,getPrefixesFromQuery:o,removePrefixes:n}},{}],33:[function(e){"use strict";var t=e("jquery"),i=e("./main.js");i.executeQuery=function(e,n){var o="function"==typeof n?n:null,s="object"==typeof n?n:{};e.options.sparql&&(s=t.extend({},e.options.sparql,s));s.handlers&&t.extend(!0,s.callbacks,s.handlers);if(s.endpoint&&0!=s.endpoint.length){var a={url:"function"==typeof s.endpoint?s.endpoint(e):s.endpoint,type:"function"==typeof s.requestMethod?s.requestMethod(e):s.requestMethod,headers:{Accept:r(e,s)}},l=!1;if(s.callbacks)for(var u in s.callbacks)if(s.callbacks[u]){l=!0;a[u]=s.callbacks[u]}a.data=e.getUrlArguments(s);if(l||o){o&&(a.complete=o);s.headers&&!t.isEmptyObject(s.headers)&&t.extend(a.headers,s.headers);i.updateQueryButton(e,"busy");e.setBackdrop(!0);var p=function(){i.updateQueryButton(e);e.setBackdrop(!1)};a.complete=a.complete?[p,a.complete]:p;e.xhr=t.ajax(a)}}};i.getUrlArguments=function(e,i){var r=e.getQueryMode(),n=[{name:e.getQueryMode(),value:e.getValue()}];if(i.namedGraphs&&i.namedGraphs.length>0)for(var o="query"==r?"named-graph-uri":"using-named-graph-uri ",s=0;s<i.namedGraphs.length;s++)n.push({name:o,value:i.namedGraphs[s]});if(i.defaultGraphs&&i.defaultGraphs.length>0)for(var o="query"==r?"default-graph-uri":"using-graph-uri ",s=0;s<i.defaultGraphs.length;s++)n.push({name:o,value:i.defaultGraphs[s]});i.args&&i.args.length>0&&t.merge(n,i.args);return n};var r=function(e,t){var i=null;if(!t.acceptHeader||t.acceptHeaderGraph||t.acceptHeaderSelect||t.acceptHeaderUpdate)if("update"==e.getQueryMode())i="function"==typeof t.acceptHeader?t.acceptHeaderUpdate(e):t.acceptHeaderUpdate;else{var r=e.getQueryType();i="DESCRIBE"==r||"CONSTRUCT"==r?"function"==typeof t.acceptHeaderGraph?t.acceptHeaderGraph(e):t.acceptHeaderGraph:"function"==typeof t.acceptHeaderSelect?t.acceptHeaderSelect(e):t.acceptHeaderSelect}else i="function"==typeof t.acceptHeader?t.acceptHeader(e):t.acceptHeader;return i}},{"./main.js":31,jquery:16}],34:[function(e,t){"use strict";var i=function(e,t,r){r||(r=e.getCursor());t||(t=e.getTokenAt(r));var n=e.getTokenAt({line:r.line,ch:t.start});if(null!=n.type&&"ws"!=n.type&&null!=t.type&&"ws"!=t.type){t.start=n.start;t.string=n.string+t.string;return i(e,t,{line:r.line,ch:n.start})}if(null!=t.type&&"ws"==t.type){t.start=t.start+1;t.string=t.string.substring(1);return t}return t},r=function(e,t,i){var n=e.getTokenAt({line:t,ch:i.start});null!=n&&"ws"==n.type&&(n=r(e,t,n));return n},n=function(e,t,i){void 0==i&&(i=1);var r=e.getTokenAt({line:t,ch:i});return null==r||void 0==r||r.end<i?null:"ws"==r.type?n(e,t,r.end+1):r};t.exports={getPreviousNonWsToken:r,getCompleteToken:i,getNextNonWsToken:n}},{}],35:[function(e,t){"use strict";{var i=e("jquery");e("./utils.js")}t.exports=function(e,t,r){var n,t=i(t);t.hover(function(){"function"==typeof r&&(r=r());n=i("<div>").addClass("yasqe_tooltip").html(r).appendTo(t);o()},function(){i(".yasqe_tooltip").remove()});var o=function(){if(i(e.getWrapperElement()).offset().top>=n.offset().top){n.css("bottom","auto");n.css("top","26px")}}}},{"./utils.js":36,jquery:16}],36:[function(e,t){"use strict";var i=e("jquery"),r=function(e,t){var i=!1;try{void 0!==e[t]&&(i=!0)}catch(r){}return i},n=function(e,t){var i=null;t&&(i="string"==typeof t?t:t(e));return i},o=function(){function e(e){var t,r,n;t=i(e).offset();r=i(e).width();n=i(e).height();return[[t.left,t.left+r],[t.top,t.top+n]]}function t(e,t){var i,r;i=e[0]<t[0]?e:t;r=e[0]<t[0]?t:e;return i[1]>r[0]||i[0]===r[0]}return function(i,r){var n=e(i),o=e(r);return t(n[0],o[0])&&t(n[1],o[1])}}();t.exports={keyExists:r,getPersistencyId:n,elementsOverlap:o}},{jquery:16}]},{},[1])(1)});
//# sourceMappingURL=yasqe.bundled.min.js.map |
pathfinder/architecturestack/src/Checkbox.js | leanix/leanix-custom-reports | import React, { Component } from 'react';
import PropTypes from 'prop-types';
class Checkbox extends Component {
constructor(props) {
super(props);
this._onChange = this._onChange.bind(this);
}
_onChange(event) {
let val = event.target.checked;
if (typeof val === 'string') {
val = val === 'true';
}
this.props.onChange(val);
}
render() {
return (
<div className={ 'checkbox' + (this.props.useSmallerFontSize ? ' small' : '') }>
<label htmlFor={this.props.id}>
<input type='checkbox'
id={this.props.id}
name={'Checkbox-' + this.props.id}
checked={this.props.value}
onChange={this._onChange}
/>
{this.props.label}
</label>
</div>
);
}
}
Checkbox.propTypes = {
id: PropTypes.string.isRequired,
label: PropTypes.string.isRequired,
onChange: PropTypes.func,
value: PropTypes.bool.isRequired,
useSmallerFontSize: PropTypes.bool
};
export default Checkbox; |
webpack.config.dev.babel.js | Hovakimyan/Drag-and-drop-tree-react | import HtmlWebpackPlugin from 'html-webpack-plugin';
import path from 'path';
import webpack from 'webpack';
import autoprefixer from 'autoprefixer';
module.exports = {
devtool: 'source-map',
entry: {
demo: './src/examples/basicExample/app',
},
output: {
path: 'build',
filename: 'static/[name].js',
},
plugins: [
new HtmlWebpackPlugin({
filename: 'index.html',
inject: true,
template: './src/examples/basicExample/index.html'
}),
new webpack.EnvironmentPlugin([
"NODE_ENV",
]),
new webpack.NoErrorsPlugin(),
],
postcss: [
autoprefixer({ browsers: ['IE >= 9', 'last 2 versions', '> 1%'] }),
],
module: {
loaders: [
{
test: /\.jsx?$/,
loaders: ['react-hot', 'babel'],
include: path.join(__dirname, 'src')
},
{
test: /\.scss$/,
loaders: [
'style-loader?insertAt=top',
'css-loader?modules&-autoprefixer&importLoaders=1&localIdentName=rst__[local]',
'postcss-loader',
'sass-loader',
],
include: path.join(__dirname, 'src')
},
{
test: /\.css$/,
loaders: [
'style-loader?insertAt=top',
'css-loader?-autoprefixer',
'postcss-loader',
],
},
{
test: /\.(jpe?g|png|gif|ico|svg)$/,
loaders: [
'file-loader?name=static/[name].[ext]',
],
include: path.join(__dirname, 'src')
},
],
},
devServer: {
contentBase: 'build',
port: 3001,
stats: {
chunks: false,
hash: false,
version: false,
assets: false,
children: false,
},
},
};
|
Ethereum-based-Roll4Win/node_modules/react-bootstrap/es/CloseButton.js | brett-harvey/Smart-Contracts | import _inheritsLoose from "@babel/runtime/helpers/esm/inheritsLoose";
import React from 'react';
var defaultProps = {
label: 'Close'
};
var CloseButton =
/*#__PURE__*/
function (_React$Component) {
_inheritsLoose(CloseButton, _React$Component);
function CloseButton() {
return _React$Component.apply(this, arguments) || this;
}
var _proto = CloseButton.prototype;
_proto.render = function render() {
var _this$props = this.props,
label = _this$props.label,
onClick = _this$props.onClick;
return React.createElement("button", {
type: "button",
className: "close",
onClick: onClick
}, React.createElement("span", {
"aria-hidden": "true"
}, "\xD7"), React.createElement("span", {
className: "sr-only"
}, label));
};
return CloseButton;
}(React.Component);
CloseButton.defaultProps = defaultProps;
export default CloseButton; |
ajax/libs/styled-components/3.2.6/styled-components-primitives.es.js | sashberd/cdnjs | import reactPrimitives from 'react-primitives';
import transformDeclPairs from 'css-to-react-native';
import isPlainObject from 'is-plain-object';
import supportsColor from 'supports-color';
import React, { Component, createElement } from 'react';
import PropTypes from 'prop-types';
import { isValidElementType } from 'react-is';
import hoistStatics from 'hoist-non-react-statics';
// Source: https://github.com/garycourt/murmurhash-js/blob/master/murmurhash2_gc.js
function murmurhash(str) {
var l = str.length | 0,
h = l | 0,
i = 0,
k;
while (l >= 4) {
k = str.charCodeAt(i) & 0xff | (str.charCodeAt(++i) & 0xff) << 8 | (str.charCodeAt(++i) & 0xff) << 16 | (str.charCodeAt(++i) & 0xff) << 24;
k = (k & 0xffff) * 0x5bd1e995 + (((k >>> 16) * 0x5bd1e995 & 0xffff) << 16);
k ^= k >>> 24;
k = (k & 0xffff) * 0x5bd1e995 + (((k >>> 16) * 0x5bd1e995 & 0xffff) << 16);
h = (h & 0xffff) * 0x5bd1e995 + (((h >>> 16) * 0x5bd1e995 & 0xffff) << 16) ^ k;
l -= 4;
++i;
}
switch (l) {
case 3:
h ^= (str.charCodeAt(i + 2) & 0xff) << 16;
case 2:
h ^= (str.charCodeAt(i + 1) & 0xff) << 8;
case 1:
h ^= str.charCodeAt(i) & 0xff;
h = (h & 0xffff) * 0x5bd1e995 + (((h >>> 16) * 0x5bd1e995 & 0xffff) << 16);
}
h ^= h >>> 13;
h = (h & 0xffff) * 0x5bd1e995 + (((h >>> 16) * 0x5bd1e995 & 0xffff) << 16);
h ^= h >>> 15;
return h >>> 0;
}
/**
* Copyright (c) 2013-present, Facebook, Inc.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*
* @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$2(string) {
return string.replace(_uppercasePattern, '-$1').toLowerCase();
}
var hyphenate_1 = hyphenate$2;
var hyphenate = hyphenate_1;
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-');
}
var hyphenateStyleName_1 = hyphenateStyleName;
//
var objToCss = function objToCss(obj, prevKey) {
var css = Object.keys(obj).filter(function (key) {
var chunk = obj[key];
return chunk !== undefined && chunk !== null && chunk !== false && chunk !== '';
}).map(function (key) {
if (isPlainObject(obj[key])) return objToCss(obj[key], key);
return hyphenateStyleName_1(key) + ': ' + obj[key] + ';';
}).join(' ');
return prevKey ? prevKey + ' {\n ' + css + '\n}' : css;
};
var flatten = function flatten(chunks, executionContext) {
return chunks.reduce(function (ruleSet, chunk) {
/* Remove falsey values */
if (chunk === undefined || chunk === null || chunk === false || chunk === '') {
return ruleSet;
}
/* Flatten ruleSet */
if (Array.isArray(chunk)) {
return [].concat(ruleSet, flatten(chunk, executionContext));
}
/* Handle other components */
if (chunk.hasOwnProperty('styledComponentId')) {
// $FlowFixMe not sure how to make this pass
return [].concat(ruleSet, ['.' + chunk.styledComponentId]);
}
/* Either execute or defer the function */
if (typeof chunk === 'function') {
return executionContext ? ruleSet.concat.apply(ruleSet, flatten([chunk(executionContext)], executionContext)) : ruleSet.concat(chunk);
}
/* Handle objects */
return ruleSet.concat(
// $FlowFixMe have to add %checks somehow to isPlainObject
isPlainObject(chunk) ? objToCss(chunk) : chunk.toString());
}, []);
};
var printed = {};
function warnOnce(message) {
if (printed[message]) return;
printed[message] = true;
if (typeof console !== 'undefined' && console.warn) console.warn(message);
}
var SINGLE_QUOTE = '\''.charCodeAt(0);
var DOUBLE_QUOTE = '"'.charCodeAt(0);
var BACKSLASH = '\\'.charCodeAt(0);
var SLASH = '/'.charCodeAt(0);
var NEWLINE = '\n'.charCodeAt(0);
var SPACE = ' '.charCodeAt(0);
var FEED = '\f'.charCodeAt(0);
var TAB = '\t'.charCodeAt(0);
var CR = '\r'.charCodeAt(0);
var OPEN_SQUARE = '['.charCodeAt(0);
var CLOSE_SQUARE = ']'.charCodeAt(0);
var OPEN_PARENTHESES = '('.charCodeAt(0);
var CLOSE_PARENTHESES = ')'.charCodeAt(0);
var OPEN_CURLY = '{'.charCodeAt(0);
var CLOSE_CURLY = '}'.charCodeAt(0);
var SEMICOLON = ';'.charCodeAt(0);
var ASTERISK = '*'.charCodeAt(0);
var COLON = ':'.charCodeAt(0);
var AT = '@'.charCodeAt(0);
var RE_AT_END = /[ \n\t\r\f\{\(\)'"\\;/\[\]#]/g;
var RE_WORD_END = /[ \n\t\r\f\(\)\{\}:;@!'"\\\]\[#]|\/(?=\*)/g;
var RE_BAD_BRACKET = /.[\\\/\("'\n]/;
function tokenize(input) {
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
var tokens = [];
var css = input.css.valueOf();
var ignore = options.ignoreErrors;
var code = void 0,
next = void 0,
quote = void 0,
lines = void 0,
last = void 0,
content = void 0,
escape = void 0,
nextLine = void 0,
nextOffset = void 0,
escaped = void 0,
escapePos = void 0,
prev = void 0,
n = void 0;
var length = css.length;
var offset = -1;
var line = 1;
var pos = 0;
function unclosed(what) {
throw input.error('Unclosed ' + what, line, pos - offset);
}
while (pos < length) {
code = css.charCodeAt(pos);
if (code === NEWLINE || code === FEED || code === CR && css.charCodeAt(pos + 1) !== NEWLINE) {
offset = pos;
line += 1;
}
switch (code) {
case NEWLINE:
case SPACE:
case TAB:
case CR:
case FEED:
next = pos;
do {
next += 1;
code = css.charCodeAt(next);
if (code === NEWLINE) {
offset = next;
line += 1;
}
} while (code === SPACE || code === NEWLINE || code === TAB || code === CR || code === FEED);
tokens.push(['space', css.slice(pos, next)]);
pos = next - 1;
break;
case OPEN_SQUARE:
tokens.push(['[', '[', line, pos - offset]);
break;
case CLOSE_SQUARE:
tokens.push([']', ']', line, pos - offset]);
break;
case OPEN_CURLY:
tokens.push(['{', '{', line, pos - offset]);
break;
case CLOSE_CURLY:
tokens.push(['}', '}', line, pos - offset]);
break;
case COLON:
tokens.push([':', ':', line, pos - offset]);
break;
case SEMICOLON:
tokens.push([';', ';', line, pos - offset]);
break;
case OPEN_PARENTHESES:
prev = tokens.length ? tokens[tokens.length - 1][1] : '';
n = css.charCodeAt(pos + 1);
if (prev === 'url' && n !== SINGLE_QUOTE && n !== DOUBLE_QUOTE && n !== SPACE && n !== NEWLINE && n !== TAB && n !== FEED && n !== CR) {
next = pos;
do {
escaped = false;
next = css.indexOf(')', next + 1);
if (next === -1) {
if (ignore) {
next = pos;
break;
} else {
unclosed('bracket');
}
}
escapePos = next;
while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
escapePos -= 1;
escaped = !escaped;
}
} while (escaped);
tokens.push(['brackets', css.slice(pos, next + 1), line, pos - offset, line, next - offset]);
pos = next;
} else {
next = css.indexOf(')', pos + 1);
content = css.slice(pos, next + 1);
if (next === -1 || RE_BAD_BRACKET.test(content)) {
tokens.push(['(', '(', line, pos - offset]);
} else {
tokens.push(['brackets', content, line, pos - offset, line, next - offset]);
pos = next;
}
}
break;
case CLOSE_PARENTHESES:
tokens.push([')', ')', line, pos - offset]);
break;
case SINGLE_QUOTE:
case DOUBLE_QUOTE:
quote = code === SINGLE_QUOTE ? '\'' : '"';
next = pos;
do {
escaped = false;
next = css.indexOf(quote, next + 1);
if (next === -1) {
if (ignore) {
next = pos + 1;
break;
} else {
unclosed('quote');
}
}
escapePos = next;
while (css.charCodeAt(escapePos - 1) === BACKSLASH) {
escapePos -= 1;
escaped = !escaped;
}
} while (escaped);
content = css.slice(pos, next + 1);
lines = content.split('\n');
last = lines.length - 1;
if (last > 0) {
nextLine = line + last;
nextOffset = next - lines[last].length;
} else {
nextLine = line;
nextOffset = offset;
}
tokens.push(['string', css.slice(pos, next + 1), line, pos - offset, nextLine, next - nextOffset]);
offset = nextOffset;
line = nextLine;
pos = next;
break;
case AT:
RE_AT_END.lastIndex = pos + 1;
RE_AT_END.test(css);
if (RE_AT_END.lastIndex === 0) {
next = css.length - 1;
} else {
next = RE_AT_END.lastIndex - 2;
}
tokens.push(['at-word', css.slice(pos, next + 1), line, pos - offset, line, next - offset]);
pos = next;
break;
case BACKSLASH:
next = pos;
escape = true;
while (css.charCodeAt(next + 1) === BACKSLASH) {
next += 1;
escape = !escape;
}
code = css.charCodeAt(next + 1);
if (escape && code !== SLASH && code !== SPACE && code !== NEWLINE && code !== TAB && code !== CR && code !== FEED) {
next += 1;
}
tokens.push(['word', css.slice(pos, next + 1), line, pos - offset, line, next - offset]);
pos = next;
break;
default:
if (code === SLASH && css.charCodeAt(pos + 1) === ASTERISK) {
next = css.indexOf('*/', pos + 2) + 1;
if (next === 0) {
if (ignore) {
next = css.length;
} else {
unclosed('comment');
}
}
content = css.slice(pos, next + 1);
lines = content.split('\n');
last = lines.length - 1;
if (last > 0) {
nextLine = line + last;
nextOffset = next - lines[last].length;
} else {
nextLine = line;
nextOffset = offset;
}
tokens.push(['comment', content, line, pos - offset, nextLine, next - nextOffset]);
offset = nextOffset;
line = nextLine;
pos = next;
} else {
RE_WORD_END.lastIndex = pos + 1;
RE_WORD_END.test(css);
if (RE_WORD_END.lastIndex === 0) {
next = css.length - 1;
} else {
next = RE_WORD_END.lastIndex - 2;
}
tokens.push(['word', css.slice(pos, next + 1), line, pos - offset, line, next - offset]);
pos = next;
}
break;
}
pos++;
}
return tokens;
}
var HIGHLIGHT_THEME = {
'brackets': [36, 39], // cyan
'string': [31, 39], // red
'at-word': [31, 39], // red
'comment': [90, 39], // gray
'{': [32, 39], // green
'}': [32, 39], // green
':': [1, 22], // bold
';': [1, 22], // bold
'(': [1, 22], // bold
')': [1, 22] // bold
};
function code(color) {
return '\x1B[' + color + 'm';
}
function terminalHighlight(css) {
var tokens = tokenize(new Input(css), { ignoreErrors: true });
var result = [];
tokens.forEach(function (token) {
var color = HIGHLIGHT_THEME[token[0]];
if (color) {
result.push(token[1].split(/\r?\n/).map(function (i) {
return code(color[0]) + i + code(color[1]);
}).join('\n'));
} else {
result.push(token[1]);
}
});
return result.join('');
}
var _typeof = typeof Symbol === "function" && typeof Symbol.iterator === "symbol" ? function (obj) {
return typeof obj;
} : function (obj) {
return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj;
};
var classCallCheck = function (instance, Constructor) {
if (!(instance instanceof Constructor)) {
throw new TypeError("Cannot call a class as a function");
}
};
var createClass = function () {
function defineProperties(target, props) {
for (var i = 0; i < props.length; i++) {
var descriptor = props[i];
descriptor.enumerable = descriptor.enumerable || false;
descriptor.configurable = true;
if ("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 _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 inherits = function (subClass, superClass) {
if (typeof superClass !== "function" && superClass !== null) {
throw new TypeError("Super expression must either be null or a function, not " + typeof superClass);
}
subClass.prototype = Object.create(superClass && superClass.prototype, {
constructor: {
value: subClass,
enumerable: false,
writable: true,
configurable: true
}
});
if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass;
};
var objectWithoutProperties = function (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 possibleConstructorReturn = function (self, call) {
if (!self) {
throw new ReferenceError("this hasn't been initialised - super() hasn't been called");
}
return call && (typeof call === "object" || typeof call === "function") ? call : self;
};
/**
* The CSS parser throws this error for broken CSS.
*
* Custom parsers can throw this error for broken custom syntax using
* the {@link Node#error} method.
*
* PostCSS will use the input source map to detect the original error location.
* If you wrote a Sass file, compiled it to CSS and then parsed it with PostCSS,
* PostCSS will show the original position in the Sass file.
*
* If you need the position in the PostCSS input
* (e.g., to debug the previous compiler), use `error.input.file`.
*
* @example
* // Catching and checking syntax error
* try {
* postcss.parse('a{')
* } catch (error) {
* if ( error.name === 'CssSyntaxError' ) {
* error //=> CssSyntaxError
* }
* }
*
* @example
* // Raising error from plugin
* throw node.error('Unknown variable', { plugin: 'postcss-vars' });
*/
var CssSyntaxError = function () {
/**
* @param {string} message - error message
* @param {number} [line] - source line of the error
* @param {number} [column] - source column of the error
* @param {string} [source] - source code of the broken file
* @param {string} [file] - absolute path to the broken file
* @param {string} [plugin] - PostCSS plugin name, if error came from plugin
*/
function CssSyntaxError(message, line, column, source, file, plugin) {
classCallCheck(this, CssSyntaxError);
/**
* @member {string} - Always equal to `'CssSyntaxError'`. You should
* always check error type
* by `error.name === 'CssSyntaxError'` instead of
* `error instanceof CssSyntaxError`, because
* npm could have several PostCSS versions.
*
* @example
* if ( error.name === 'CssSyntaxError' ) {
* error //=> CssSyntaxError
* }
*/
this.name = 'CssSyntaxError';
/**
* @member {string} - Error message.
*
* @example
* error.message //=> 'Unclosed block'
*/
this.reason = message;
if (file) {
/**
* @member {string} - Absolute path to the broken file.
*
* @example
* error.file //=> 'a.sass'
* error.input.file //=> 'a.css'
*/
this.file = file;
}
if (source) {
/**
* @member {string} - Source code of the broken file.
*
* @example
* error.source //=> 'a { b {} }'
* error.input.column //=> 'a b { }'
*/
this.source = source;
}
if (plugin) {
/**
* @member {string} - Plugin name, if error came from plugin.
*
* @example
* error.plugin //=> 'postcss-vars'
*/
this.plugin = plugin;
}
if (typeof line !== 'undefined' && typeof column !== 'undefined') {
/**
* @member {number} - Source line of the error.
*
* @example
* error.line //=> 2
* error.input.line //=> 4
*/
this.line = line;
/**
* @member {number} - Source column of the error.
*
* @example
* error.column //=> 1
* error.input.column //=> 4
*/
this.column = column;
}
this.setMessage();
if (Error.captureStackTrace) {
Error.captureStackTrace(this, CssSyntaxError);
}
}
CssSyntaxError.prototype.setMessage = function setMessage() {
/**
* @member {string} - Full error text in the GNU error format
* with plugin, file, line and column.
*
* @example
* error.message //=> 'a.css:1:1: Unclosed block'
*/
this.message = this.plugin ? this.plugin + ': ' : '';
this.message += this.file ? this.file : '<css input>';
if (typeof this.line !== 'undefined') {
this.message += ':' + this.line + ':' + this.column;
}
this.message += ': ' + this.reason;
};
/**
* Returns a few lines of CSS source that caused the error.
*
* If the CSS has an input source map without `sourceContent`,
* this method will return an empty string.
*
* @param {boolean} [color] whether arrow will be colored red by terminal
* color codes. By default, PostCSS will detect
* color support by `process.stdout.isTTY`
* and `process.env.NODE_DISABLE_COLORS`.
*
* @example
* error.showSourceCode() //=> " 4 | }
* // 5 | a {
* // > 6 | bad
* // | ^
* // 7 | }
* // 8 | b {"
*
* @return {string} few lines of CSS source that caused the error
*/
CssSyntaxError.prototype.showSourceCode = function showSourceCode(color) {
var _this = this;
if (!this.source) return '';
var css = this.source;
if (typeof color === 'undefined') color = supportsColor;
if (color) css = terminalHighlight(css);
var lines = css.split(/\r?\n/);
var start = Math.max(this.line - 3, 0);
var end = Math.min(this.line + 2, lines.length);
var maxWidth = String(end).length;
return lines.slice(start, end).map(function (line, index) {
var number = start + 1 + index;
var padded = (' ' + number).slice(-maxWidth);
var gutter = ' ' + padded + ' | ';
if (number === _this.line) {
var spacing = gutter.replace(/\d/g, ' ') + line.slice(0, _this.column - 1).replace(/[^\t]/g, ' ');
return '>' + gutter + line + '\n ' + spacing + '^';
} else {
return ' ' + gutter + line;
}
}).join('\n');
};
/**
* Returns error position, message and source code of the broken part.
*
* @example
* error.toString() //=> "CssSyntaxError: app.css:1:1: Unclosed block
* // > 1 | a {
* // | ^"
*
* @return {string} error position, message and source code
*/
CssSyntaxError.prototype.toString = function toString() {
var code = this.showSourceCode();
if (code) {
code = '\n\n' + code + '\n';
}
return this.name + ': ' + this.message + code;
};
createClass(CssSyntaxError, [{
key: 'generated',
get: function get$$1() {
warnOnce('CssSyntaxError#generated is depreacted. Use input instead.');
return this.input;
}
/**
* @memberof CssSyntaxError#
* @member {Input} input - Input object with PostCSS internal information
* about input file. If input has source map
* from previous tool, PostCSS will use origin
* (for example, Sass) source. You can use this
* object to get PostCSS input source.
*
* @example
* error.input.file //=> 'a.css'
* error.file //=> 'a.sass'
*/
}]);
return CssSyntaxError;
}();
/* eslint-disable valid-jsdoc */
var defaultRaw = {
colon: ': ',
indent: ' ',
beforeDecl: '\n',
beforeRule: '\n',
beforeOpen: ' ',
beforeClose: '\n',
beforeComment: '\n',
after: '\n',
emptyBody: '',
commentLeft: ' ',
commentRight: ' '
};
function capitalize(str) {
return str[0].toUpperCase() + str.slice(1);
}
var Stringifier = function () {
function Stringifier(builder) {
classCallCheck(this, Stringifier);
this.builder = builder;
}
Stringifier.prototype.stringify = function stringify(node, semicolon) {
this[node.type](node, semicolon);
};
Stringifier.prototype.root = function root(node) {
this.body(node);
if (node.raws.after) this.builder(node.raws.after);
};
Stringifier.prototype.comment = function comment(node) {
var left = this.raw(node, 'left', 'commentLeft');
var right = this.raw(node, 'right', 'commentRight');
this.builder('/*' + left + node.text + right + '*/', node);
};
Stringifier.prototype.decl = function decl(node, semicolon) {
var between = this.raw(node, 'between', 'colon');
var string = node.prop + between + this.rawValue(node, 'value');
if (node.important) {
string += node.raws.important || ' !important';
}
if (semicolon) string += ';';
this.builder(string, node);
};
Stringifier.prototype.rule = function rule(node) {
this.block(node, this.rawValue(node, 'selector'));
};
Stringifier.prototype.atrule = function atrule(node, semicolon) {
var name = '@' + node.name;
var params = node.params ? this.rawValue(node, 'params') : '';
if (typeof node.raws.afterName !== 'undefined') {
name += node.raws.afterName;
} else if (params) {
name += ' ';
}
if (node.nodes) {
this.block(node, name + params);
} else {
var end = (node.raws.between || '') + (semicolon ? ';' : '');
this.builder(name + params + end, node);
}
};
Stringifier.prototype.body = function body(node) {
var last = node.nodes.length - 1;
while (last > 0) {
if (node.nodes[last].type !== 'comment') break;
last -= 1;
}
var semicolon = this.raw(node, 'semicolon');
for (var i = 0; i < node.nodes.length; i++) {
var child = node.nodes[i];
var before = this.raw(child, 'before');
if (before) this.builder(before);
this.stringify(child, last !== i || semicolon);
}
};
Stringifier.prototype.block = function block(node, start) {
var between = this.raw(node, 'between', 'beforeOpen');
this.builder(start + between + '{', node, 'start');
var after = void 0;
if (node.nodes && node.nodes.length) {
this.body(node);
after = this.raw(node, 'after');
} else {
after = this.raw(node, 'after', 'emptyBody');
}
if (after) this.builder(after);
this.builder('}', node, 'end');
};
Stringifier.prototype.raw = function raw(node, own, detect) {
var value = void 0;
if (!detect) detect = own;
// Already had
if (own) {
value = node.raws[own];
if (typeof value !== 'undefined') return value;
}
var parent = node.parent;
// Hack for first rule in CSS
if (detect === 'before') {
if (!parent || parent.type === 'root' && parent.first === node) {
return '';
}
}
// Floating child without parent
if (!parent) return defaultRaw[detect];
// Detect style by other nodes
var root = node.root();
if (!root.rawCache) root.rawCache = {};
if (typeof root.rawCache[detect] !== 'undefined') {
return root.rawCache[detect];
}
if (detect === 'before' || detect === 'after') {
return this.beforeAfter(node, detect);
} else {
var method = 'raw' + capitalize(detect);
if (this[method]) {
value = this[method](root, node);
} else {
root.walk(function (i) {
value = i.raws[own];
if (typeof value !== 'undefined') return false;
});
}
}
if (typeof value === 'undefined') value = defaultRaw[detect];
root.rawCache[detect] = value;
return value;
};
Stringifier.prototype.rawSemicolon = function rawSemicolon(root) {
var value = void 0;
root.walk(function (i) {
if (i.nodes && i.nodes.length && i.last.type === 'decl') {
value = i.raws.semicolon;
if (typeof value !== 'undefined') return false;
}
});
return value;
};
Stringifier.prototype.rawEmptyBody = function rawEmptyBody(root) {
var value = void 0;
root.walk(function (i) {
if (i.nodes && i.nodes.length === 0) {
value = i.raws.after;
if (typeof value !== 'undefined') return false;
}
});
return value;
};
Stringifier.prototype.rawIndent = function rawIndent(root) {
if (root.raws.indent) return root.raws.indent;
var value = void 0;
root.walk(function (i) {
var p = i.parent;
if (p && p !== root && p.parent && p.parent === root) {
if (typeof i.raws.before !== 'undefined') {
var parts = i.raws.before.split('\n');
value = parts[parts.length - 1];
value = value.replace(/[^\s]/g, '');
return false;
}
}
});
return value;
};
Stringifier.prototype.rawBeforeComment = function rawBeforeComment(root, node) {
var value = void 0;
root.walkComments(function (i) {
if (typeof i.raws.before !== 'undefined') {
value = i.raws.before;
if (value.indexOf('\n') !== -1) {
value = value.replace(/[^\n]+$/, '');
}
return false;
}
});
if (typeof value === 'undefined') {
value = this.raw(node, null, 'beforeDecl');
}
return value;
};
Stringifier.prototype.rawBeforeDecl = function rawBeforeDecl(root, node) {
var value = void 0;
root.walkDecls(function (i) {
if (typeof i.raws.before !== 'undefined') {
value = i.raws.before;
if (value.indexOf('\n') !== -1) {
value = value.replace(/[^\n]+$/, '');
}
return false;
}
});
if (typeof value === 'undefined') {
value = this.raw(node, null, 'beforeRule');
}
return value;
};
Stringifier.prototype.rawBeforeRule = function rawBeforeRule(root) {
var value = void 0;
root.walk(function (i) {
if (i.nodes && (i.parent !== root || root.first !== i)) {
if (typeof i.raws.before !== 'undefined') {
value = i.raws.before;
if (value.indexOf('\n') !== -1) {
value = value.replace(/[^\n]+$/, '');
}
return false;
}
}
});
return value;
};
Stringifier.prototype.rawBeforeClose = function rawBeforeClose(root) {
var value = void 0;
root.walk(function (i) {
if (i.nodes && i.nodes.length > 0) {
if (typeof i.raws.after !== 'undefined') {
value = i.raws.after;
if (value.indexOf('\n') !== -1) {
value = value.replace(/[^\n]+$/, '');
}
return false;
}
}
});
return value;
};
Stringifier.prototype.rawBeforeOpen = function rawBeforeOpen(root) {
var value = void 0;
root.walk(function (i) {
if (i.type !== 'decl') {
value = i.raws.between;
if (typeof value !== 'undefined') return false;
}
});
return value;
};
Stringifier.prototype.rawColon = function rawColon(root) {
var value = void 0;
root.walkDecls(function (i) {
if (typeof i.raws.between !== 'undefined') {
value = i.raws.between.replace(/[^\s:]/g, '');
return false;
}
});
return value;
};
Stringifier.prototype.beforeAfter = function beforeAfter(node, detect) {
var value = void 0;
if (node.type === 'decl') {
value = this.raw(node, null, 'beforeDecl');
} else if (node.type === 'comment') {
value = this.raw(node, null, 'beforeComment');
} else if (detect === 'before') {
value = this.raw(node, null, 'beforeRule');
} else {
value = this.raw(node, null, 'beforeClose');
}
var buf = node.parent;
var depth = 0;
while (buf && buf.type !== 'root') {
depth += 1;
buf = buf.parent;
}
if (value.indexOf('\n') !== -1) {
var indent = this.raw(node, null, 'indent');
if (indent.length) {
for (var step = 0; step < depth; step++) {
value += indent;
}
}
}
return value;
};
Stringifier.prototype.rawValue = function rawValue(node, prop) {
var value = node[prop];
var raw = node.raws[prop];
if (raw && raw.value === value) {
return raw.raw;
} else {
return value;
}
};
return Stringifier;
}();
function stringify(node, builder) {
var str = new Stringifier(builder);
str.stringify(node);
}
/**
* @typedef {object} position
* @property {number} line - source line in file
* @property {number} column - source column in file
*/
/**
* @typedef {object} source
* @property {Input} input - {@link Input} with input file
* @property {position} start - The starting position of the node’s source
* @property {position} end - The ending position of the node’s source
*/
var cloneNode = function cloneNode(obj, parent) {
var cloned = new obj.constructor();
for (var i in obj) {
if (!obj.hasOwnProperty(i)) continue;
var value = obj[i];
var type = typeof value === 'undefined' ? 'undefined' : _typeof(value);
if (i === 'parent' && type === 'object') {
if (parent) cloned[i] = parent;
} else if (i === 'source') {
cloned[i] = value;
} else if (value instanceof Array) {
cloned[i] = value.map(function (j) {
return cloneNode(j, cloned);
});
} else if (i !== 'before' && i !== 'after' && i !== 'between' && i !== 'semicolon') {
if (type === 'object' && value !== null) value = cloneNode(value);
cloned[i] = value;
}
}
return cloned;
};
/**
* All node classes inherit the following common methods.
*
* @abstract
*/
var Node = function () {
/**
* @param {object} [defaults] - value for node properties
*/
function Node() {
var defaults$$1 = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
classCallCheck(this, Node);
this.raws = {};
for (var name in defaults$$1) {
this[name] = defaults$$1[name];
}
}
/**
* Returns a CssSyntaxError instance containing the original position
* of the node in the source, showing line and column numbers and also
* a small excerpt to facilitate debugging.
*
* If present, an input source map will be used to get the original position
* of the source, even from a previous compilation step
* (e.g., from Sass compilation).
*
* This method produces very useful error messages.
*
* @param {string} message - error description
* @param {object} [opts] - options
* @param {string} opts.plugin - plugin name that created this error.
* PostCSS will set it automatically.
* @param {string} opts.word - a word inside a node’s string that should
* be highlighted as the source of the error
* @param {number} opts.index - an index inside a node’s string that should
* be highlighted as the source of the error
*
* @return {CssSyntaxError} error object to throw it
*
* @example
* if ( !variables[name] ) {
* throw decl.error('Unknown variable ' + name, { word: name });
* // CssSyntaxError: postcss-vars:a.sass:4:3: Unknown variable $black
* // color: $black
* // a
* // ^
* // background: white
* }
*/
Node.prototype.error = function error(message) {
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if (this.source) {
var pos = this.positionBy(opts);
return this.source.input.error(message, pos.line, pos.column, opts);
} else {
return new CssSyntaxError(message);
}
};
/**
* This method is provided as a convenience wrapper for {@link Result#warn}.
*
* @param {Result} result - the {@link Result} instance
* that will receive the warning
* @param {string} text - warning message
* @param {object} [opts] - options
* @param {string} opts.plugin - plugin name that created this warning.
* PostCSS will set it automatically.
* @param {string} opts.word - a word inside a node’s string that should
* be highlighted as the source of the warning
* @param {number} opts.index - an index inside a node’s string that should
* be highlighted as the source of the warning
*
* @return {Warning} created warning object
*
* @example
* const plugin = postcss.plugin('postcss-deprecated', () => {
* return (root, result) => {
* root.walkDecls('bad', decl => {
* decl.warn(result, 'Deprecated property bad');
* });
* };
* });
*/
Node.prototype.warn = function warn(result, text, opts) {
var data = { node: this };
for (var i in opts) {
data[i] = opts[i];
}return result.warn(text, data);
};
/**
* Removes the node from its parent and cleans the parent properties
* from the node and its children.
*
* @example
* if ( decl.prop.match(/^-webkit-/) ) {
* decl.remove();
* }
*
* @return {Node} node to make calls chain
*/
Node.prototype.remove = function remove() {
if (this.parent) {
this.parent.removeChild(this);
}
this.parent = undefined;
return this;
};
/**
* Returns a CSS string representing the node.
*
* @param {stringifier|syntax} [stringifier] - a syntax to use
* in string generation
*
* @return {string} CSS string of this node
*
* @example
* postcss.rule({ selector: 'a' }).toString() //=> "a {}"
*/
Node.prototype.toString = function toString() {
var stringifier = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : stringify;
if (stringifier.stringify) stringifier = stringifier.stringify;
var result = '';
stringifier(this, function (i) {
result += i;
});
return result;
};
/**
* Returns a clone of the node.
*
* The resulting cloned node and its (cloned) children will have
* a clean parent and code style properties.
*
* @param {object} [overrides] - new properties to override in the clone.
*
* @example
* const cloned = decl.clone({ prop: '-moz-' + decl.prop });
* cloned.raws.before //=> undefined
* cloned.parent //=> undefined
* cloned.toString() //=> -moz-transform: scale(0)
*
* @return {Node} clone of the node
*/
Node.prototype.clone = function clone() {
var overrides = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var cloned = cloneNode(this);
for (var name in overrides) {
cloned[name] = overrides[name];
}
return cloned;
};
/**
* Shortcut to clone the node and insert the resulting cloned node
* before the current node.
*
* @param {object} [overrides] - new properties to override in the clone.
*
* @example
* decl.cloneBefore({ prop: '-moz-' + decl.prop });
*
* @return {Node} - new node
*/
Node.prototype.cloneBefore = function cloneBefore() {
var overrides = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var cloned = this.clone(overrides);
this.parent.insertBefore(this, cloned);
return cloned;
};
/**
* Shortcut to clone the node and insert the resulting cloned node
* after the current node.
*
* @param {object} [overrides] - new properties to override in the clone.
*
* @return {Node} - new node
*/
Node.prototype.cloneAfter = function cloneAfter() {
var overrides = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var cloned = this.clone(overrides);
this.parent.insertAfter(this, cloned);
return cloned;
};
/**
* Inserts node(s) before the current node and removes the current node.
*
* @param {...Node} nodes - node(s) to replace current one
*
* @example
* if ( atrule.name == 'mixin' ) {
* atrule.replaceWith(mixinRules[atrule.params]);
* }
*
* @return {Node} current node to methods chain
*/
Node.prototype.replaceWith = function replaceWith() {
var _this = this;
if (this.parent) {
for (var _len = arguments.length, nodes = Array(_len), _key = 0; _key < _len; _key++) {
nodes[_key] = arguments[_key];
}
nodes.forEach(function (node) {
_this.parent.insertBefore(_this, node);
});
this.remove();
}
return this;
};
/**
* Removes the node from its current parent and inserts it
* at the end of `newParent`.
*
* This will clean the `before` and `after` code {@link Node#raws} data
* from the node and replace them with the indentation style of `newParent`.
* It will also clean the `between` property
* if `newParent` is in another {@link Root}.
*
* @param {Container} newParent - container node where the current node
* will be moved
*
* @example
* atrule.moveTo(atrule.root());
*
* @return {Node} current node to methods chain
*/
Node.prototype.moveTo = function moveTo(newParent) {
this.cleanRaws(this.root() === newParent.root());
this.remove();
newParent.append(this);
return this;
};
/**
* Removes the node from its current parent and inserts it into
* a new parent before `otherNode`.
*
* This will also clean the node’s code style properties just as it would
* in {@link Node#moveTo}.
*
* @param {Node} otherNode - node that will be before current node
*
* @return {Node} current node to methods chain
*/
Node.prototype.moveBefore = function moveBefore(otherNode) {
this.cleanRaws(this.root() === otherNode.root());
this.remove();
otherNode.parent.insertBefore(otherNode, this);
return this;
};
/**
* Removes the node from its current parent and inserts it into
* a new parent after `otherNode`.
*
* This will also clean the node’s code style properties just as it would
* in {@link Node#moveTo}.
*
* @param {Node} otherNode - node that will be after current node
*
* @return {Node} current node to methods chain
*/
Node.prototype.moveAfter = function moveAfter(otherNode) {
this.cleanRaws(this.root() === otherNode.root());
this.remove();
otherNode.parent.insertAfter(otherNode, this);
return this;
};
/**
* Returns the next child of the node’s parent.
* Returns `undefined` if the current node is the last child.
*
* @return {Node|undefined} next node
*
* @example
* if ( comment.text === 'delete next' ) {
* const next = comment.next();
* if ( next ) {
* next.remove();
* }
* }
*/
Node.prototype.next = function next() {
var index = this.parent.index(this);
return this.parent.nodes[index + 1];
};
/**
* Returns the previous child of the node’s parent.
* Returns `undefined` if the current node is the first child.
*
* @return {Node|undefined} previous node
*
* @example
* const annotation = decl.prev();
* if ( annotation.type == 'comment' ) {
* readAnnotation(annotation.text);
* }
*/
Node.prototype.prev = function prev() {
var index = this.parent.index(this);
return this.parent.nodes[index - 1];
};
Node.prototype.toJSON = function toJSON() {
var fixed = {};
for (var name in this) {
if (!this.hasOwnProperty(name)) continue;
if (name === 'parent') continue;
var value = this[name];
if (value instanceof Array) {
fixed[name] = value.map(function (i) {
if ((typeof i === 'undefined' ? 'undefined' : _typeof(i)) === 'object' && i.toJSON) {
return i.toJSON();
} else {
return i;
}
});
} else if ((typeof value === 'undefined' ? 'undefined' : _typeof(value)) === 'object' && value.toJSON) {
fixed[name] = value.toJSON();
} else {
fixed[name] = value;
}
}
return fixed;
};
/**
* Returns a {@link Node#raws} value. If the node is missing
* the code style property (because the node was manually built or cloned),
* PostCSS will try to autodetect the code style property by looking
* at other nodes in the tree.
*
* @param {string} prop - name of code style property
* @param {string} [defaultType] - name of default value, it can be missed
* if the value is the same as prop
*
* @example
* const root = postcss.parse('a { background: white }');
* root.nodes[0].append({ prop: 'color', value: 'black' });
* root.nodes[0].nodes[1].raws.before //=> undefined
* root.nodes[0].nodes[1].raw('before') //=> ' '
*
* @return {string} code style value
*/
Node.prototype.raw = function raw(prop, defaultType) {
var str = new Stringifier();
return str.raw(this, prop, defaultType);
};
/**
* Finds the Root instance of the node’s tree.
*
* @example
* root.nodes[0].nodes[0].root() === root
*
* @return {Root} root parent
*/
Node.prototype.root = function root() {
var result = this;
while (result.parent) {
result = result.parent;
}return result;
};
Node.prototype.cleanRaws = function cleanRaws(keepBetween) {
delete this.raws.before;
delete this.raws.after;
if (!keepBetween) delete this.raws.between;
};
Node.prototype.positionInside = function positionInside(index) {
var string = this.toString();
var column = this.source.start.column;
var line = this.source.start.line;
for (var i = 0; i < index; i++) {
if (string[i] === '\n') {
column = 1;
line += 1;
} else {
column += 1;
}
}
return { line: line, column: column };
};
Node.prototype.positionBy = function positionBy(opts) {
var pos = this.source.start;
if (opts.index) {
pos = this.positionInside(opts.index);
} else if (opts.word) {
var index = this.toString().indexOf(opts.word);
if (index !== -1) pos = this.positionInside(index);
}
return pos;
};
Node.prototype.removeSelf = function removeSelf() {
warnOnce('Node#removeSelf is deprecated. Use Node#remove.');
return this.remove();
};
Node.prototype.replace = function replace(nodes) {
warnOnce('Node#replace is deprecated. Use Node#replaceWith');
return this.replaceWith(nodes);
};
Node.prototype.style = function style(own, detect) {
warnOnce('Node#style() is deprecated. Use Node#raw()');
return this.raw(own, detect);
};
Node.prototype.cleanStyles = function cleanStyles(keepBetween) {
warnOnce('Node#cleanStyles() is deprecated. Use Node#cleanRaws()');
return this.cleanRaws(keepBetween);
};
createClass(Node, [{
key: 'before',
get: function get$$1() {
warnOnce('Node#before is deprecated. Use Node#raws.before');
return this.raws.before;
},
set: function set$$1(val) {
warnOnce('Node#before is deprecated. Use Node#raws.before');
this.raws.before = val;
}
}, {
key: 'between',
get: function get$$1() {
warnOnce('Node#between is deprecated. Use Node#raws.between');
return this.raws.between;
},
set: function set$$1(val) {
warnOnce('Node#between is deprecated. Use Node#raws.between');
this.raws.between = val;
}
/**
* @memberof Node#
* @member {string} type - String representing the node’s type.
* Possible values are `root`, `atrule`, `rule`,
* `decl`, or `comment`.
*
* @example
* postcss.decl({ prop: 'color', value: 'black' }).type //=> 'decl'
*/
/**
* @memberof Node#
* @member {Container} parent - the node’s parent node.
*
* @example
* root.nodes[0].parent == root;
*/
/**
* @memberof Node#
* @member {source} source - the input source of the node
*
* The property is used in source map generation.
*
* If you create a node manually (e.g., with `postcss.decl()`),
* that node will not have a `source` property and will be absent
* from the source map. For this reason, the plugin developer should
* consider cloning nodes to create new ones (in which case the new node’s
* source will reference the original, cloned node) or setting
* the `source` property manually.
*
* ```js
* // Bad
* const prefixed = postcss.decl({
* prop: '-moz-' + decl.prop,
* value: decl.value
* });
*
* // Good
* const prefixed = decl.clone({ prop: '-moz-' + decl.prop });
* ```
*
* ```js
* if ( atrule.name == 'add-link' ) {
* const rule = postcss.rule({ selector: 'a', source: atrule.source });
* atrule.parent.insertBefore(atrule, rule);
* }
* ```
*
* @example
* decl.source.input.from //=> '/home/ai/a.sass'
* decl.source.start //=> { line: 10, column: 2 }
* decl.source.end //=> { line: 10, column: 12 }
*/
/**
* @memberof Node#
* @member {object} raws - Information to generate byte-to-byte equal
* node string as it was in the origin input.
*
* Every parser saves its own properties,
* but the default CSS parser uses:
*
* * `before`: the space symbols before the node. It also stores `*`
* and `_` symbols before the declaration (IE hack).
* * `after`: the space symbols after the last child of the node
* to the end of the node.
* * `between`: the symbols between the property and value
* for declarations, selector and `{` for rules, or last parameter
* and `{` for at-rules.
* * `semicolon`: contains true if the last child has
* an (optional) semicolon.
* * `afterName`: the space between the at-rule name and its parameters.
* * `left`: the space symbols between `/*` and the comment’s text.
* * `right`: the space symbols between the comment’s text
* and <code>*/</code>.
* * `important`: the content of the important statement,
* if it is not just `!important`.
*
* PostCSS cleans selectors, declaration values and at-rule parameters
* from comments and extra spaces, but it stores origin content in raws
* properties. As such, if you don’t change a declaration’s value,
* PostCSS will use the raw value with comments.
*
* @example
* const root = postcss.parse('a {\n color:black\n}')
* root.first.first.raws //=> { before: '\n ', between: ':' }
*/
}]);
return Node;
}();
/**
* Represents a CSS declaration.
*
* @extends Node
*
* @example
* const root = postcss.parse('a { color: black }');
* const decl = root.first.first;
* decl.type //=> 'decl'
* decl.toString() //=> ' color: black'
*/
var Declaration = function (_Node) {
inherits(Declaration, _Node);
function Declaration(defaults$$1) {
classCallCheck(this, Declaration);
var _this = possibleConstructorReturn(this, _Node.call(this, defaults$$1));
_this.type = 'decl';
return _this;
}
createClass(Declaration, [{
key: '_value',
get: function get$$1() {
warnOnce('Node#_value was deprecated. Use Node#raws.value');
return this.raws.value;
},
set: function set$$1(val) {
warnOnce('Node#_value was deprecated. Use Node#raws.value');
this.raws.value = val;
}
}, {
key: '_important',
get: function get$$1() {
warnOnce('Node#_important was deprecated. Use Node#raws.important');
return this.raws.important;
},
set: function set$$1(val) {
warnOnce('Node#_important was deprecated. Use Node#raws.important');
this.raws.important = val;
}
/**
* @memberof Declaration#
* @member {string} prop - the declaration’s property name
*
* @example
* const root = postcss.parse('a { color: black }');
* const decl = root.first.first;
* decl.prop //=> 'color'
*/
/**
* @memberof Declaration#
* @member {string} value - the declaration’s value
*
* @example
* const root = postcss.parse('a { color: black }');
* const decl = root.first.first;
* decl.value //=> 'black'
*/
/**
* @memberof Declaration#
* @member {boolean} important - `true` if the declaration
* has an !important annotation.
*
* @example
* const root = postcss.parse('a { color: black !important; color: red }');
* root.first.first.important //=> true
* root.first.last.important //=> undefined
*/
/**
* @memberof Declaration#
* @member {object} raws - Information to generate byte-to-byte equal
* node string as it was in the origin input.
*
* Every parser saves its own properties,
* but the default CSS parser uses:
*
* * `before`: the space symbols before the node. It also stores `*`
* and `_` symbols before the declaration (IE hack).
* * `between`: the symbols between the property and value
* for declarations, selector and `{` for rules, or last parameter
* and `{` for at-rules.
* * `important`: the content of the important statement,
* if it is not just `!important`.
*
* PostCSS cleans declaration from comments and extra spaces,
* but it stores origin content in raws properties.
* As such, if you don’t change a declaration’s value,
* PostCSS will use the raw value with comments.
*
* @example
* const root = postcss.parse('a {\n color:black\n}')
* root.first.first.raws //=> { before: '\n ', between: ':' }
*/
}]);
return Declaration;
}(Node);
/**
* Represents a comment between declarations or statements (rule and at-rules).
*
* Comments inside selectors, at-rule parameters, or declaration values
* will be stored in the `raws` properties explained above.
*
* @extends Node
*/
var Comment = function (_Node) {
inherits(Comment, _Node);
function Comment(defaults$$1) {
classCallCheck(this, Comment);
var _this = possibleConstructorReturn(this, _Node.call(this, defaults$$1));
_this.type = 'comment';
return _this;
}
createClass(Comment, [{
key: 'left',
get: function get$$1() {
warnOnce('Comment#left was deprecated. Use Comment#raws.left');
return this.raws.left;
},
set: function set$$1(val) {
warnOnce('Comment#left was deprecated. Use Comment#raws.left');
this.raws.left = val;
}
}, {
key: 'right',
get: function get$$1() {
warnOnce('Comment#right was deprecated. Use Comment#raws.right');
return this.raws.right;
},
set: function set$$1(val) {
warnOnce('Comment#right was deprecated. Use Comment#raws.right');
this.raws.right = val;
}
/**
* @memberof Comment#
* @member {string} text - the comment’s text
*/
/**
* @memberof Comment#
* @member {object} raws - Information to generate byte-to-byte equal
* node string as it was in the origin input.
*
* Every parser saves its own properties,
* but the default CSS parser uses:
*
* * `before`: the space symbols before the node.
* * `left`: the space symbols between `/*` and the comment’s text.
* * `right`: the space symbols between the comment’s text.
*/
}]);
return Comment;
}(Node);
var Parser = function () {
function Parser(input) {
classCallCheck(this, Parser);
this.input = input;
this.pos = 0;
this.root = new Root();
this.current = this.root;
this.spaces = '';
this.semicolon = false;
this.root.source = { input: input, start: { line: 1, column: 1 } };
}
Parser.prototype.tokenize = function tokenize$$1() {
this.tokens = tokenize(this.input);
};
Parser.prototype.loop = function loop() {
var token = void 0;
while (this.pos < this.tokens.length) {
token = this.tokens[this.pos];
switch (token[0]) {
case 'space':
case ';':
this.spaces += token[1];
break;
case '}':
this.end(token);
break;
case 'comment':
this.comment(token);
break;
case 'at-word':
this.atrule(token);
break;
case '{':
this.emptyRule(token);
break;
default:
this.other();
break;
}
this.pos += 1;
}
this.endFile();
};
Parser.prototype.comment = function comment(token) {
var node = new Comment();
this.init(node, token[2], token[3]);
node.source.end = { line: token[4], column: token[5] };
var text = token[1].slice(2, -2);
if (/^\s*$/.test(text)) {
node.text = '';
node.raws.left = text;
node.raws.right = '';
} else {
var match = text.match(/^(\s*)([^]*[^\s])(\s*)$/);
node.text = match[2];
node.raws.left = match[1];
node.raws.right = match[3];
}
};
Parser.prototype.emptyRule = function emptyRule(token) {
var node = new Rule();
this.init(node, token[2], token[3]);
node.selector = '';
node.raws.between = '';
this.current = node;
};
Parser.prototype.other = function other() {
var token = void 0;
var end = false;
var type = null;
var colon = false;
var bracket = null;
var brackets = [];
var start = this.pos;
while (this.pos < this.tokens.length) {
token = this.tokens[this.pos];
type = token[0];
if (type === '(' || type === '[') {
if (!bracket) bracket = token;
brackets.push(type === '(' ? ')' : ']');
} else if (brackets.length === 0) {
if (type === ';') {
if (colon) {
this.decl(this.tokens.slice(start, this.pos + 1));
return;
} else {
break;
}
} else if (type === '{') {
this.rule(this.tokens.slice(start, this.pos + 1));
return;
} else if (type === '}') {
this.pos -= 1;
end = true;
break;
} else if (type === ':') {
colon = true;
}
} else if (type === brackets[brackets.length - 1]) {
brackets.pop();
if (brackets.length === 0) bracket = null;
}
this.pos += 1;
}
if (this.pos === this.tokens.length) {
this.pos -= 1;
end = true;
}
if (brackets.length > 0) this.unclosedBracket(bracket);
if (end && colon) {
while (this.pos > start) {
token = this.tokens[this.pos][0];
if (token !== 'space' && token !== 'comment') break;
this.pos -= 1;
}
this.decl(this.tokens.slice(start, this.pos + 1));
return;
}
this.unknownWord(start);
};
Parser.prototype.rule = function rule(tokens) {
tokens.pop();
var node = new Rule();
this.init(node, tokens[0][2], tokens[0][3]);
node.raws.between = this.spacesFromEnd(tokens);
this.raw(node, 'selector', tokens);
this.current = node;
};
Parser.prototype.decl = function decl(tokens) {
var node = new Declaration();
this.init(node);
var last = tokens[tokens.length - 1];
if (last[0] === ';') {
this.semicolon = true;
tokens.pop();
}
if (last[4]) {
node.source.end = { line: last[4], column: last[5] };
} else {
node.source.end = { line: last[2], column: last[3] };
}
while (tokens[0][0] !== 'word') {
node.raws.before += tokens.shift()[1];
}
node.source.start = { line: tokens[0][2], column: tokens[0][3] };
node.prop = '';
while (tokens.length) {
var type = tokens[0][0];
if (type === ':' || type === 'space' || type === 'comment') {
break;
}
node.prop += tokens.shift()[1];
}
node.raws.between = '';
var token = void 0;
while (tokens.length) {
token = tokens.shift();
if (token[0] === ':') {
node.raws.between += token[1];
break;
} else {
node.raws.between += token[1];
}
}
if (node.prop[0] === '_' || node.prop[0] === '*') {
node.raws.before += node.prop[0];
node.prop = node.prop.slice(1);
}
node.raws.between += this.spacesFromStart(tokens);
this.precheckMissedSemicolon(tokens);
for (var i = tokens.length - 1; i > 0; i--) {
token = tokens[i];
if (token[1] === '!important') {
node.important = true;
var string = this.stringFrom(tokens, i);
string = this.spacesFromEnd(tokens) + string;
if (string !== ' !important') node.raws.important = string;
break;
} else if (token[1] === 'important') {
var cache = tokens.slice(0);
var str = '';
for (var j = i; j > 0; j--) {
var _type = cache[j][0];
if (str.trim().indexOf('!') === 0 && _type !== 'space') {
break;
}
str = cache.pop()[1] + str;
}
if (str.trim().indexOf('!') === 0) {
node.important = true;
node.raws.important = str;
tokens = cache;
}
}
if (token[0] !== 'space' && token[0] !== 'comment') {
break;
}
}
this.raw(node, 'value', tokens);
if (node.value.indexOf(':') !== -1) this.checkMissedSemicolon(tokens);
};
Parser.prototype.atrule = function atrule(token) {
var node = new AtRule();
node.name = token[1].slice(1);
if (node.name === '') {
this.unnamedAtrule(node, token);
}
this.init(node, token[2], token[3]);
var last = false;
var open = false;
var params = [];
this.pos += 1;
while (this.pos < this.tokens.length) {
token = this.tokens[this.pos];
if (token[0] === ';') {
node.source.end = { line: token[2], column: token[3] };
this.semicolon = true;
break;
} else if (token[0] === '{') {
open = true;
break;
} else if (token[0] === '}') {
this.end(token);
break;
} else {
params.push(token);
}
this.pos += 1;
}
if (this.pos === this.tokens.length) {
last = true;
}
node.raws.between = this.spacesFromEnd(params);
if (params.length) {
node.raws.afterName = this.spacesFromStart(params);
this.raw(node, 'params', params);
if (last) {
token = params[params.length - 1];
node.source.end = { line: token[4], column: token[5] };
this.spaces = node.raws.between;
node.raws.between = '';
}
} else {
node.raws.afterName = '';
node.params = '';
}
if (open) {
node.nodes = [];
this.current = node;
}
};
Parser.prototype.end = function end(token) {
if (this.current.nodes && this.current.nodes.length) {
this.current.raws.semicolon = this.semicolon;
}
this.semicolon = false;
this.current.raws.after = (this.current.raws.after || '') + this.spaces;
this.spaces = '';
if (this.current.parent) {
this.current.source.end = { line: token[2], column: token[3] };
this.current = this.current.parent;
} else {
this.unexpectedClose(token);
}
};
Parser.prototype.endFile = function endFile() {
if (this.current.parent) this.unclosedBlock();
if (this.current.nodes && this.current.nodes.length) {
this.current.raws.semicolon = this.semicolon;
}
this.current.raws.after = (this.current.raws.after || '') + this.spaces;
};
// Helpers
Parser.prototype.init = function init(node, line, column) {
this.current.push(node);
node.source = { start: { line: line, column: column }, input: this.input };
node.raws.before = this.spaces;
this.spaces = '';
if (node.type !== 'comment') this.semicolon = false;
};
Parser.prototype.raw = function raw(node, prop, tokens) {
var token = void 0,
type = void 0;
var length = tokens.length;
var value = '';
var clean = true;
for (var i = 0; i < length; i += 1) {
token = tokens[i];
type = token[0];
if (type === 'comment' || type === 'space' && i === length - 1) {
clean = false;
} else {
value += token[1];
}
}
if (!clean) {
var raw = tokens.reduce(function (all, i) {
return all + i[1];
}, '');
node.raws[prop] = { value: value, raw: raw };
}
node[prop] = value;
};
Parser.prototype.spacesFromEnd = function spacesFromEnd(tokens) {
var lastTokenType = void 0;
var spaces = '';
while (tokens.length) {
lastTokenType = tokens[tokens.length - 1][0];
if (lastTokenType !== 'space' && lastTokenType !== 'comment') break;
spaces = tokens.pop()[1] + spaces;
}
return spaces;
};
Parser.prototype.spacesFromStart = function spacesFromStart(tokens) {
var next = void 0;
var spaces = '';
while (tokens.length) {
next = tokens[0][0];
if (next !== 'space' && next !== 'comment') break;
spaces += tokens.shift()[1];
}
return spaces;
};
Parser.prototype.stringFrom = function stringFrom(tokens, from) {
var result = '';
for (var i = from; i < tokens.length; i++) {
result += tokens[i][1];
}
tokens.splice(from, tokens.length - from);
return result;
};
Parser.prototype.colon = function colon(tokens) {
var brackets = 0;
var token = void 0,
type = void 0,
prev = void 0;
for (var i = 0; i < tokens.length; i++) {
token = tokens[i];
type = token[0];
if (type === '(') {
brackets += 1;
} else if (type === ')') {
brackets -= 1;
} else if (brackets === 0 && type === ':') {
if (!prev) {
this.doubleColon(token);
} else if (prev[0] === 'word' && prev[1] === 'progid') {
continue;
} else {
return i;
}
}
prev = token;
}
return false;
};
// Errors
Parser.prototype.unclosedBracket = function unclosedBracket(bracket) {
throw this.input.error('Unclosed bracket', bracket[2], bracket[3]);
};
Parser.prototype.unknownWord = function unknownWord(start) {
var token = this.tokens[start];
throw this.input.error('Unknown word', token[2], token[3]);
};
Parser.prototype.unexpectedClose = function unexpectedClose(token) {
throw this.input.error('Unexpected }', token[2], token[3]);
};
Parser.prototype.unclosedBlock = function unclosedBlock() {
var pos = this.current.source.start;
throw this.input.error('Unclosed block', pos.line, pos.column);
};
Parser.prototype.doubleColon = function doubleColon(token) {
throw this.input.error('Double colon', token[2], token[3]);
};
Parser.prototype.unnamedAtrule = function unnamedAtrule(node, token) {
throw this.input.error('At-rule without name', token[2], token[3]);
};
Parser.prototype.precheckMissedSemicolon = function precheckMissedSemicolon(tokens) {
// Hook for Safe Parser
};
Parser.prototype.checkMissedSemicolon = function checkMissedSemicolon(tokens) {
var colon = this.colon(tokens);
if (colon === false) return;
var founded = 0;
var token = void 0;
for (var j = colon - 1; j >= 0; j--) {
token = tokens[j];
if (token[0] !== 'space') {
founded += 1;
if (founded === 2) break;
}
}
throw this.input.error('Missed semicolon', token[2], token[3]);
};
return Parser;
}();
function parse(css, opts) {
if (opts && opts.safe) {
throw new Error('Option safe was removed. ' + 'Use parser: require("postcss-safe-parser")');
}
var input = new Input(css, opts);
var parser = new Parser(input);
try {
parser.tokenize();
parser.loop();
} catch (e) {
if (e.name === 'CssSyntaxError' && opts && opts.from) {
if (/\.scss$/i.test(opts.from)) {
e.message += '\nYou tried to parse SCSS with ' + 'the standard CSS parser; ' + 'try again with the postcss-scss parser';
} else if (/\.less$/i.test(opts.from)) {
e.message += '\nYou tried to parse Less with ' + 'the standard CSS parser; ' + 'try again with the postcss-less parser';
}
}
throw e;
}
return parser.root;
}
function cleanSource(nodes) {
return nodes.map(function (i) {
if (i.nodes) i.nodes = cleanSource(i.nodes);
delete i.source;
return i;
});
}
/**
* @callback childCondition
* @param {Node} node - container child
* @param {number} index - child index
* @param {Node[]} nodes - all container children
* @return {boolean}
*/
/**
* @callback childIterator
* @param {Node} node - container child
* @param {number} index - child index
* @return {false|undefined} returning `false` will break iteration
*/
/**
* The {@link Root}, {@link AtRule}, and {@link Rule} container nodes
* inherit some common methods to help work with their children.
*
* Note that all containers can store any content. If you write a rule inside
* a rule, PostCSS will parse it.
*
* @extends Node
* @abstract
*/
var Container = function (_Node) {
inherits(Container, _Node);
function Container() {
classCallCheck(this, Container);
return possibleConstructorReturn(this, _Node.apply(this, arguments));
}
Container.prototype.push = function push(child) {
child.parent = this;
this.nodes.push(child);
return this;
};
/**
* Iterates through the container’s immediate children,
* calling `callback` for each child.
*
* Returning `false` in the callback will break iteration.
*
* This method only iterates through the container’s immediate children.
* If you need to recursively iterate through all the container’s descendant
* nodes, use {@link Container#walk}.
*
* Unlike the for `{}`-cycle or `Array#forEach` this iterator is safe
* if you are mutating the array of child nodes during iteration.
* PostCSS will adjust the current index to match the mutations.
*
* @param {childIterator} callback - iterator receives each node and index
*
* @return {false|undefined} returns `false` if iteration was broke
*
* @example
* const root = postcss.parse('a { color: black; z-index: 1 }');
* const rule = root.first;
*
* for ( let decl of rule.nodes ) {
* decl.cloneBefore({ prop: '-webkit-' + decl.prop });
* // Cycle will be infinite, because cloneBefore moves the current node
* // to the next index
* }
*
* rule.each(decl => {
* decl.cloneBefore({ prop: '-webkit-' + decl.prop });
* // Will be executed only for color and z-index
* });
*/
Container.prototype.each = function each(callback) {
if (!this.lastEach) this.lastEach = 0;
if (!this.indexes) this.indexes = {};
this.lastEach += 1;
var id = this.lastEach;
this.indexes[id] = 0;
if (!this.nodes) return undefined;
var index = void 0,
result = void 0;
while (this.indexes[id] < this.nodes.length) {
index = this.indexes[id];
result = callback(this.nodes[index], index);
if (result === false) break;
this.indexes[id] += 1;
}
delete this.indexes[id];
return result;
};
/**
* Traverses the container’s descendant nodes, calling callback
* for each node.
*
* Like container.each(), this method is safe to use
* if you are mutating arrays during iteration.
*
* If you only need to iterate through the container’s immediate children,
* use {@link Container#each}.
*
* @param {childIterator} callback - iterator receives each node and index
*
* @return {false|undefined} returns `false` if iteration was broke
*
* @example
* root.walk(node => {
* // Traverses all descendant nodes.
* });
*/
Container.prototype.walk = function walk(callback) {
return this.each(function (child, i) {
var result = callback(child, i);
if (result !== false && child.walk) {
result = child.walk(callback);
}
return result;
});
};
/**
* Traverses the container’s descendant nodes, calling callback
* for each declaration node.
*
* If you pass a filter, iteration will only happen over declarations
* with matching properties.
*
* Like {@link Container#each}, this method is safe
* to use if you are mutating arrays during iteration.
*
* @param {string|RegExp} [prop] - string or regular expression
* to filter declarations by property name
* @param {childIterator} callback - iterator receives each node and index
*
* @return {false|undefined} returns `false` if iteration was broke
*
* @example
* root.walkDecls(decl => {
* checkPropertySupport(decl.prop);
* });
*
* root.walkDecls('border-radius', decl => {
* decl.remove();
* });
*
* root.walkDecls(/^background/, decl => {
* decl.value = takeFirstColorFromGradient(decl.value);
* });
*/
Container.prototype.walkDecls = function walkDecls(prop, callback) {
if (!callback) {
callback = prop;
return this.walk(function (child, i) {
if (child.type === 'decl') {
return callback(child, i);
}
});
} else if (prop instanceof RegExp) {
return this.walk(function (child, i) {
if (child.type === 'decl' && prop.test(child.prop)) {
return callback(child, i);
}
});
} else {
return this.walk(function (child, i) {
if (child.type === 'decl' && child.prop === prop) {
return callback(child, i);
}
});
}
};
/**
* Traverses the container’s descendant nodes, calling callback
* for each rule node.
*
* If you pass a filter, iteration will only happen over rules
* with matching selectors.
*
* Like {@link Container#each}, this method is safe
* to use if you are mutating arrays during iteration.
*
* @param {string|RegExp} [selector] - string or regular expression
* to filter rules by selector
* @param {childIterator} callback - iterator receives each node and index
*
* @return {false|undefined} returns `false` if iteration was broke
*
* @example
* const selectors = [];
* root.walkRules(rule => {
* selectors.push(rule.selector);
* });
* console.log(`Your CSS uses ${selectors.length} selectors`);
*/
Container.prototype.walkRules = function walkRules(selector, callback) {
if (!callback) {
callback = selector;
return this.walk(function (child, i) {
if (child.type === 'rule') {
return callback(child, i);
}
});
} else if (selector instanceof RegExp) {
return this.walk(function (child, i) {
if (child.type === 'rule' && selector.test(child.selector)) {
return callback(child, i);
}
});
} else {
return this.walk(function (child, i) {
if (child.type === 'rule' && child.selector === selector) {
return callback(child, i);
}
});
}
};
/**
* Traverses the container’s descendant nodes, calling callback
* for each at-rule node.
*
* If you pass a filter, iteration will only happen over at-rules
* that have matching names.
*
* Like {@link Container#each}, this method is safe
* to use if you are mutating arrays during iteration.
*
* @param {string|RegExp} [name] - string or regular expression
* to filter at-rules by name
* @param {childIterator} callback - iterator receives each node and index
*
* @return {false|undefined} returns `false` if iteration was broke
*
* @example
* root.walkAtRules(rule => {
* if ( isOld(rule.name) ) rule.remove();
* });
*
* let first = false;
* root.walkAtRules('charset', rule => {
* if ( !first ) {
* first = true;
* } else {
* rule.remove();
* }
* });
*/
Container.prototype.walkAtRules = function walkAtRules(name, callback) {
if (!callback) {
callback = name;
return this.walk(function (child, i) {
if (child.type === 'atrule') {
return callback(child, i);
}
});
} else if (name instanceof RegExp) {
return this.walk(function (child, i) {
if (child.type === 'atrule' && name.test(child.name)) {
return callback(child, i);
}
});
} else {
return this.walk(function (child, i) {
if (child.type === 'atrule' && child.name === name) {
return callback(child, i);
}
});
}
};
/**
* Traverses the container’s descendant nodes, calling callback
* for each comment node.
*
* Like {@link Container#each}, this method is safe
* to use if you are mutating arrays during iteration.
*
* @param {childIterator} callback - iterator receives each node and index
*
* @return {false|undefined} returns `false` if iteration was broke
*
* @example
* root.walkComments(comment => {
* comment.remove();
* });
*/
Container.prototype.walkComments = function walkComments(callback) {
return this.walk(function (child, i) {
if (child.type === 'comment') {
return callback(child, i);
}
});
};
/**
* Inserts new nodes to the start of the container.
*
* @param {...(Node|object|string|Node[])} children - new nodes
*
* @return {Node} this node for methods chain
*
* @example
* const decl1 = postcss.decl({ prop: 'color', value: 'black' });
* const decl2 = postcss.decl({ prop: 'background-color', value: 'white' });
* rule.append(decl1, decl2);
*
* root.append({ name: 'charset', params: '"UTF-8"' }); // at-rule
* root.append({ selector: 'a' }); // rule
* rule.append({ prop: 'color', value: 'black' }); // declaration
* rule.append({ text: 'Comment' }) // comment
*
* root.append('a {}');
* root.first.append('color: black; z-index: 1');
*/
Container.prototype.append = function append() {
var _this2 = this;
for (var _len = arguments.length, children = Array(_len), _key = 0; _key < _len; _key++) {
children[_key] = arguments[_key];
}
children.forEach(function (child) {
var nodes = _this2.normalize(child, _this2.last);
nodes.forEach(function (node) {
return _this2.nodes.push(node);
});
});
return this;
};
/**
* Inserts new nodes to the end of the container.
*
* @param {...(Node|object|string|Node[])} children - new nodes
*
* @return {Node} this node for methods chain
*
* @example
* const decl1 = postcss.decl({ prop: 'color', value: 'black' });
* const decl2 = postcss.decl({ prop: 'background-color', value: 'white' });
* rule.prepend(decl1, decl2);
*
* root.append({ name: 'charset', params: '"UTF-8"' }); // at-rule
* root.append({ selector: 'a' }); // rule
* rule.append({ prop: 'color', value: 'black' }); // declaration
* rule.append({ text: 'Comment' }) // comment
*
* root.append('a {}');
* root.first.append('color: black; z-index: 1');
*/
Container.prototype.prepend = function prepend() {
var _this3 = this;
for (var _len2 = arguments.length, children = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
children[_key2] = arguments[_key2];
}
children = children.reverse();
children.forEach(function (child) {
var nodes = _this3.normalize(child, _this3.first, 'prepend').reverse();
nodes.forEach(function (node) {
return _this3.nodes.unshift(node);
});
for (var id in _this3.indexes) {
_this3.indexes[id] = _this3.indexes[id] + nodes.length;
}
});
return this;
};
Container.prototype.cleanRaws = function cleanRaws(keepBetween) {
_Node.prototype.cleanRaws.call(this, keepBetween);
if (this.nodes) {
this.nodes.forEach(function (node) {
return node.cleanRaws(keepBetween);
});
}
};
/**
* Insert new node before old node within the container.
*
* @param {Node|number} exist - child or child’s index.
* @param {Node|object|string|Node[]} add - new node
*
* @return {Node} this node for methods chain
*
* @example
* rule.insertBefore(decl, decl.clone({ prop: '-webkit-' + decl.prop }));
*/
Container.prototype.insertBefore = function insertBefore(exist, add) {
var _this4 = this;
exist = this.index(exist);
var type = exist === 0 ? 'prepend' : false;
var nodes = this.normalize(add, this.nodes[exist], type).reverse();
nodes.forEach(function (node) {
return _this4.nodes.splice(exist, 0, node);
});
var index = void 0;
for (var id in this.indexes) {
index = this.indexes[id];
if (exist <= index) {
this.indexes[id] = index + nodes.length;
}
}
return this;
};
/**
* Insert new node after old node within the container.
*
* @param {Node|number} exist - child or child’s index
* @param {Node|object|string|Node[]} add - new node
*
* @return {Node} this node for methods chain
*/
Container.prototype.insertAfter = function insertAfter(exist, add) {
var _this5 = this;
exist = this.index(exist);
var nodes = this.normalize(add, this.nodes[exist]).reverse();
nodes.forEach(function (node) {
return _this5.nodes.splice(exist + 1, 0, node);
});
var index = void 0;
for (var id in this.indexes) {
index = this.indexes[id];
if (exist < index) {
this.indexes[id] = index + nodes.length;
}
}
return this;
};
Container.prototype.remove = function remove(child) {
if (typeof child !== 'undefined') {
warnOnce('Container#remove is deprecated. ' + 'Use Container#removeChild');
this.removeChild(child);
} else {
_Node.prototype.remove.call(this);
}
return this;
};
/**
* Removes node from the container and cleans the parent properties
* from the node and its children.
*
* @param {Node|number} child - child or child’s index
*
* @return {Node} this node for methods chain
*
* @example
* rule.nodes.length //=> 5
* rule.removeChild(decl);
* rule.nodes.length //=> 4
* decl.parent //=> undefined
*/
Container.prototype.removeChild = function removeChild(child) {
child = this.index(child);
this.nodes[child].parent = undefined;
this.nodes.splice(child, 1);
var index = void 0;
for (var id in this.indexes) {
index = this.indexes[id];
if (index >= child) {
this.indexes[id] = index - 1;
}
}
return this;
};
/**
* Removes all children from the container
* and cleans their parent properties.
*
* @return {Node} this node for methods chain
*
* @example
* rule.removeAll();
* rule.nodes.length //=> 0
*/
Container.prototype.removeAll = function removeAll() {
this.nodes.forEach(function (node) {
return node.parent = undefined;
});
this.nodes = [];
return this;
};
/**
* Passes all declaration values within the container that match pattern
* through callback, replacing those values with the returned result
* of callback.
*
* This method is useful if you are using a custom unit or function
* and need to iterate through all values.
*
* @param {string|RegExp} pattern - replace pattern
* @param {object} opts - options to speed up the search
* @param {string|string[]} opts.props - an array of property names
* @param {string} opts.fast - string that’s used
* to narrow down values and speed up
the regexp search
* @param {function|string} callback - string to replace pattern
* or callback that returns a new
* value.
* The callback will receive
* the same arguments as those
* passed to a function parameter
* of `String#replace`.
*
* @return {Node} this node for methods chain
*
* @example
* root.replaceValues(/\d+rem/, { fast: 'rem' }, string => {
* return 15 * parseInt(string) + 'px';
* });
*/
Container.prototype.replaceValues = function replaceValues(pattern, opts, callback) {
if (!callback) {
callback = opts;
opts = {};
}
this.walkDecls(function (decl) {
if (opts.props && opts.props.indexOf(decl.prop) === -1) return;
if (opts.fast && decl.value.indexOf(opts.fast) === -1) return;
decl.value = decl.value.replace(pattern, callback);
});
return this;
};
/**
* Returns `true` if callback returns `true`
* for all of the container’s children.
*
* @param {childCondition} condition - iterator returns true or false.
*
* @return {boolean} is every child pass condition
*
* @example
* const noPrefixes = rule.every(i => i.prop[0] !== '-');
*/
Container.prototype.every = function every(condition) {
return this.nodes.every(condition);
};
/**
* Returns `true` if callback returns `true` for (at least) one
* of the container’s children.
*
* @param {childCondition} condition - iterator returns true or false.
*
* @return {boolean} is some child pass condition
*
* @example
* const hasPrefix = rule.some(i => i.prop[0] === '-');
*/
Container.prototype.some = function some(condition) {
return this.nodes.some(condition);
};
/**
* Returns a `child`’s index within the {@link Container#nodes} array.
*
* @param {Node} child - child of the current container.
*
* @return {number} child index
*
* @example
* rule.index( rule.nodes[2] ) //=> 2
*/
Container.prototype.index = function index(child) {
if (typeof child === 'number') {
return child;
} else {
return this.nodes.indexOf(child);
}
};
/**
* The container’s first child.
*
* @type {Node}
*
* @example
* rule.first == rules.nodes[0];
*/
Container.prototype.normalize = function normalize(nodes, sample) {
var _this6 = this;
if (typeof nodes === 'string') {
nodes = cleanSource(parse(nodes).nodes);
} else if (!Array.isArray(nodes)) {
if (nodes.type === 'root') {
nodes = nodes.nodes;
} else if (nodes.type) {
nodes = [nodes];
} else if (nodes.prop) {
if (typeof nodes.value === 'undefined') {
throw new Error('Value field is missed in node creation');
} else if (typeof nodes.value !== 'string') {
nodes.value = String(nodes.value);
}
nodes = [new Declaration(nodes)];
} else if (nodes.selector) {
nodes = [new Rule(nodes)];
} else if (nodes.name) {
nodes = [new AtRule(nodes)];
} else if (nodes.text) {
nodes = [new Comment(nodes)];
} else {
throw new Error('Unknown node type in node creation');
}
}
var processed = nodes.map(function (i) {
if (typeof i.raws === 'undefined') i = _this6.rebuild(i);
if (i.parent) i = i.clone();
if (typeof i.raws.before === 'undefined') {
if (sample && typeof sample.raws.before !== 'undefined') {
i.raws.before = sample.raws.before.replace(/[^\s]/g, '');
}
}
i.parent = _this6;
return i;
});
return processed;
};
Container.prototype.rebuild = function rebuild(node, parent) {
var _this7 = this;
var fix = void 0;
if (node.type === 'root') {
fix = new Root();
} else if (node.type === 'atrule') {
fix = new AtRule();
} else if (node.type === 'rule') {
fix = new Rule();
} else if (node.type === 'decl') {
fix = new Declaration();
} else if (node.type === 'comment') {
fix = new Comment();
}
for (var i in node) {
if (i === 'nodes') {
fix.nodes = node.nodes.map(function (j) {
return _this7.rebuild(j, fix);
});
} else if (i === 'parent' && parent) {
fix.parent = parent;
} else if (node.hasOwnProperty(i)) {
fix[i] = node[i];
}
}
return fix;
};
Container.prototype.eachInside = function eachInside(callback) {
warnOnce('Container#eachInside is deprecated. ' + 'Use Container#walk instead.');
return this.walk(callback);
};
Container.prototype.eachDecl = function eachDecl(prop, callback) {
warnOnce('Container#eachDecl is deprecated. ' + 'Use Container#walkDecls instead.');
return this.walkDecls(prop, callback);
};
Container.prototype.eachRule = function eachRule(selector, callback) {
warnOnce('Container#eachRule is deprecated. ' + 'Use Container#walkRules instead.');
return this.walkRules(selector, callback);
};
Container.prototype.eachAtRule = function eachAtRule(name, callback) {
warnOnce('Container#eachAtRule is deprecated. ' + 'Use Container#walkAtRules instead.');
return this.walkAtRules(name, callback);
};
Container.prototype.eachComment = function eachComment(callback) {
warnOnce('Container#eachComment is deprecated. ' + 'Use Container#walkComments instead.');
return this.walkComments(callback);
};
createClass(Container, [{
key: 'first',
get: function get$$1() {
if (!this.nodes) return undefined;
return this.nodes[0];
}
/**
* The container’s last child.
*
* @type {Node}
*
* @example
* rule.last == rule.nodes[rule.nodes.length - 1];
*/
}, {
key: 'last',
get: function get$$1() {
if (!this.nodes) return undefined;
return this.nodes[this.nodes.length - 1];
}
}, {
key: 'semicolon',
get: function get$$1() {
warnOnce('Node#semicolon is deprecated. Use Node#raws.semicolon');
return this.raws.semicolon;
},
set: function set$$1(val) {
warnOnce('Node#semicolon is deprecated. Use Node#raws.semicolon');
this.raws.semicolon = val;
}
}, {
key: 'after',
get: function get$$1() {
warnOnce('Node#after is deprecated. Use Node#raws.after');
return this.raws.after;
},
set: function set$$1(val) {
warnOnce('Node#after is deprecated. Use Node#raws.after');
this.raws.after = val;
}
/**
* @memberof Container#
* @member {Node[]} nodes - an array containing the container’s children
*
* @example
* const root = postcss.parse('a { color: black }');
* root.nodes.length //=> 1
* root.nodes[0].selector //=> 'a'
* root.nodes[0].nodes[0].prop //=> 'color'
*/
}]);
return Container;
}(Node);
/**
* Represents an at-rule.
*
* If it’s followed in the CSS by a {} block, this node will have
* a nodes property representing its children.
*
* @extends Container
*
* @example
* const root = postcss.parse('@charset "UTF-8"; @media print {}');
*
* const charset = root.first;
* charset.type //=> 'atrule'
* charset.nodes //=> undefined
*
* const media = root.last;
* media.nodes //=> []
*/
var AtRule = function (_Container) {
inherits(AtRule, _Container);
function AtRule(defaults$$1) {
classCallCheck(this, AtRule);
var _this = possibleConstructorReturn(this, _Container.call(this, defaults$$1));
_this.type = 'atrule';
return _this;
}
AtRule.prototype.append = function append() {
var _Container$prototype$;
if (!this.nodes) this.nodes = [];
for (var _len = arguments.length, children = Array(_len), _key = 0; _key < _len; _key++) {
children[_key] = arguments[_key];
}
return (_Container$prototype$ = _Container.prototype.append).call.apply(_Container$prototype$, [this].concat(children));
};
AtRule.prototype.prepend = function prepend() {
var _Container$prototype$2;
if (!this.nodes) this.nodes = [];
for (var _len2 = arguments.length, children = Array(_len2), _key2 = 0; _key2 < _len2; _key2++) {
children[_key2] = arguments[_key2];
}
return (_Container$prototype$2 = _Container.prototype.prepend).call.apply(_Container$prototype$2, [this].concat(children));
};
createClass(AtRule, [{
key: 'afterName',
get: function get$$1() {
warnOnce('AtRule#afterName was deprecated. Use AtRule#raws.afterName');
return this.raws.afterName;
},
set: function set$$1(val) {
warnOnce('AtRule#afterName was deprecated. Use AtRule#raws.afterName');
this.raws.afterName = val;
}
}, {
key: '_params',
get: function get$$1() {
warnOnce('AtRule#_params was deprecated. Use AtRule#raws.params');
return this.raws.params;
},
set: function set$$1(val) {
warnOnce('AtRule#_params was deprecated. Use AtRule#raws.params');
this.raws.params = val;
}
/**
* @memberof AtRule#
* @member {string} name - the at-rule’s name immediately follows the `@`
*
* @example
* const root = postcss.parse('@media print {}');
* media.name //=> 'media'
* const media = root.first;
*/
/**
* @memberof AtRule#
* @member {string} params - the at-rule’s parameters, the values
* that follow the at-rule’s name but precede
* any {} block
*
* @example
* const root = postcss.parse('@media print, screen {}');
* const media = root.first;
* media.params //=> 'print, screen'
*/
/**
* @memberof AtRule#
* @member {object} raws - Information to generate byte-to-byte equal
* node string as it was in the origin input.
*
* Every parser saves its own properties,
* but the default CSS parser uses:
*
* * `before`: the space symbols before the node. It also stores `*`
* and `_` symbols before the declaration (IE hack).
* * `after`: the space symbols after the last child of the node
* to the end of the node.
* * `between`: the symbols between the property and value
* for declarations, selector and `{` for rules, or last parameter
* and `{` for at-rules.
* * `semicolon`: contains true if the last child has
* an (optional) semicolon.
* * `afterName`: the space between the at-rule name and its parameters.
*
* PostCSS cleans at-rule parameters from comments and extra spaces,
* but it stores origin content in raws properties.
* As such, if you don’t change a declaration’s value,
* PostCSS will use the raw value with comments.
*
* @example
* const root = postcss.parse(' @media\nprint {\n}')
* root.first.first.raws //=> { before: ' ',
* // between: ' ',
* // afterName: '\n',
* // after: '\n' }
*/
}]);
return AtRule;
}(Container);
/**
* Contains helpers for safely splitting lists of CSS values,
* preserving parentheses and quotes.
*
* @example
* const list = postcss.list;
*
* @namespace list
*/
var list = {
split: function split(string, separators, last) {
var array = [];
var current = '';
var split = false;
var func = 0;
var quote = false;
var escape = false;
for (var i = 0; i < string.length; i++) {
var letter = string[i];
if (quote) {
if (escape) {
escape = false;
} else if (letter === '\\') {
escape = true;
} else if (letter === quote) {
quote = false;
}
} else if (letter === '"' || letter === '\'') {
quote = letter;
} else if (letter === '(') {
func += 1;
} else if (letter === ')') {
if (func > 0) func -= 1;
} else if (func === 0) {
if (separators.indexOf(letter) !== -1) split = true;
}
if (split) {
if (current !== '') array.push(current.trim());
current = '';
split = false;
} else {
current += letter;
}
}
if (last || current !== '') array.push(current.trim());
return array;
},
/**
* Safely splits space-separated values (such as those for `background`,
* `border-radius`, and other shorthand properties).
*
* @param {string} string - space-separated values
*
* @return {string[]} splitted values
*
* @example
* postcss.list.space('1px calc(10% + 1px)') //=> ['1px', 'calc(10% + 1px)']
*/
space: function space(string) {
var spaces = [' ', '\n', '\t'];
return list.split(string, spaces);
},
/**
* Safely splits comma-separated values (such as those for `transition-*`
* and `background` properties).
*
* @param {string} string - comma-separated values
*
* @return {string[]} splitted values
*
* @example
* postcss.list.comma('black, linear-gradient(white, black)')
* //=> ['black', 'linear-gradient(white, black)']
*/
comma: function comma(string) {
var comma = ',';
return list.split(string, [comma], true);
}
};
/**
* Represents a CSS rule: a selector followed by a declaration block.
*
* @extends Container
*
* @example
* const root = postcss.parse('a{}');
* const rule = root.first;
* rule.type //=> 'rule'
* rule.toString() //=> 'a{}'
*/
var Rule = function (_Container) {
inherits(Rule, _Container);
function Rule(defaults$$1) {
classCallCheck(this, Rule);
var _this = possibleConstructorReturn(this, _Container.call(this, defaults$$1));
_this.type = 'rule';
if (!_this.nodes) _this.nodes = [];
return _this;
}
/**
* An array containing the rule’s individual selectors.
* Groups of selectors are split at commas.
*
* @type {string[]}
*
* @example
* const root = postcss.parse('a, b { }');
* const rule = root.first;
*
* rule.selector //=> 'a, b'
* rule.selectors //=> ['a', 'b']
*
* rule.selectors = ['a', 'strong'];
* rule.selector //=> 'a, strong'
*/
createClass(Rule, [{
key: 'selectors',
get: function get$$1() {
return list.comma(this.selector);
},
set: function set$$1(values) {
var match = this.selector ? this.selector.match(/,\s*/) : null;
var sep = match ? match[0] : ',' + this.raw('between', 'beforeOpen');
this.selector = values.join(sep);
}
}, {
key: '_selector',
get: function get$$1() {
warnOnce('Rule#_selector is deprecated. Use Rule#raws.selector');
return this.raws.selector;
},
set: function set$$1(val) {
warnOnce('Rule#_selector is deprecated. Use Rule#raws.selector');
this.raws.selector = val;
}
/**
* @memberof Rule#
* @member {string} selector - the rule’s full selector represented
* as a string
*
* @example
* const root = postcss.parse('a, b { }');
* const rule = root.first;
* rule.selector //=> 'a, b'
*/
/**
* @memberof Rule#
* @member {object} raws - Information to generate byte-to-byte equal
* node string as it was in the origin input.
*
* Every parser saves its own properties,
* but the default CSS parser uses:
*
* * `before`: the space symbols before the node. It also stores `*`
* and `_` symbols before the declaration (IE hack).
* * `after`: the space symbols after the last child of the node
* to the end of the node.
* * `between`: the symbols between the property and value
* for declarations, selector and `{` for rules, or last parameter
* and `{` for at-rules.
* * `semicolon`: contains true if the last child has
* an (optional) semicolon.
*
* PostCSS cleans selectors from comments and extra spaces,
* but it stores origin content in raws properties.
* As such, if you don’t change a declaration’s value,
* PostCSS will use the raw value with comments.
*
* @example
* const root = postcss.parse('a {\n color:black\n}')
* root.first.first.raws //=> { before: '', between: ' ', after: '\n' }
*/
}]);
return Rule;
}(Container);
/**
* Represents a plugin’s warning. It can be created using {@link Node#warn}.
*
* @example
* if ( decl.important ) {
* decl.warn(result, 'Avoid !important', { word: '!important' });
* }
*/
var Warning = function () {
/**
* @param {string} text - warning message
* @param {Object} [opts] - warning options
* @param {Node} opts.node - CSS node that caused the warning
* @param {string} opts.word - word in CSS source that caused the warning
* @param {number} opts.index - index in CSS node string that caused
* the warning
* @param {string} opts.plugin - name of the plugin that created
* this warning. {@link Result#warn} fills
* this property automatically.
*/
function Warning(text) {
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
classCallCheck(this, Warning);
/**
* @member {string} - Type to filter warnings from
* {@link Result#messages}. Always equal
* to `"warning"`.
*
* @example
* const nonWarning = result.messages.filter(i => i.type !== 'warning')
*/
this.type = 'warning';
/**
* @member {string} - The warning message.
*
* @example
* warning.text //=> 'Try to avoid !important'
*/
this.text = text;
if (opts.node && opts.node.source) {
var pos = opts.node.positionBy(opts);
/**
* @member {number} - Line in the input file
* with this warning’s source
*
* @example
* warning.line //=> 5
*/
this.line = pos.line;
/**
* @member {number} - Column in the input file
* with this warning’s source.
*
* @example
* warning.column //=> 6
*/
this.column = pos.column;
}
for (var opt in opts) {
this[opt] = opts[opt];
}
}
/**
* Returns a warning position and message.
*
* @example
* warning.toString() //=> 'postcss-lint:a.css:10:14: Avoid !important'
*
* @return {string} warning position and message
*/
Warning.prototype.toString = function toString() {
if (this.node) {
return this.node.error(this.text, {
plugin: this.plugin,
index: this.index,
word: this.word
}).message;
} else if (this.plugin) {
return this.plugin + ': ' + this.text;
} else {
return this.text;
}
};
/**
* @memberof Warning#
* @member {string} plugin - The name of the plugin that created
* it will fill this property automatically.
* this warning. When you call {@link Node#warn}
*
* @example
* warning.plugin //=> 'postcss-important'
*/
/**
* @memberof Warning#
* @member {Node} node - Contains the CSS node that caused the warning.
*
* @example
* warning.node.toString() //=> 'color: white !important'
*/
return Warning;
}();
/**
* @typedef {object} Message
* @property {string} type - message type
* @property {string} plugin - source PostCSS plugin name
*/
/**
* Provides the result of the PostCSS transformations.
*
* A Result instance is returned by {@link LazyResult#then}
* or {@link Root#toResult} methods.
*
* @example
* postcss([cssnext]).process(css).then(function (result) {
* console.log(result.css);
* });
*
* @example
* var result2 = postcss.parse(css).toResult();
*/
var Result = function () {
/**
* @param {Processor} processor - processor used for this transformation.
* @param {Root} root - Root node after all transformations.
* @param {processOptions} opts - options from the {@link Processor#process}
* or {@link Root#toResult}
*/
function Result(processor, root, opts) {
classCallCheck(this, Result);
/**
* @member {Processor} - The Processor instance used
* for this transformation.
*
* @example
* for ( let plugin of result.processor.plugins) {
* if ( plugin.postcssPlugin === 'postcss-bad' ) {
* throw 'postcss-good is incompatible with postcss-bad';
* }
* });
*/
this.processor = processor;
/**
* @member {Message[]} - Contains messages from plugins
* (e.g., warnings or custom messages).
* Each message should have type
* and plugin properties.
*
* @example
* postcss.plugin('postcss-min-browser', () => {
* return (root, result) => {
* var browsers = detectMinBrowsersByCanIUse(root);
* result.messages.push({
* type: 'min-browser',
* plugin: 'postcss-min-browser',
* browsers: browsers
* });
* };
* });
*/
this.messages = [];
/**
* @member {Root} - Root node after all transformations.
*
* @example
* root.toResult().root == root;
*/
this.root = root;
/**
* @member {processOptions} - Options from the {@link Processor#process}
* or {@link Root#toResult} call
* that produced this Result instance.
*
* @example
* root.toResult(opts).opts == opts;
*/
this.opts = opts;
/**
* @member {string} - A CSS string representing of {@link Result#root}.
*
* @example
* postcss.parse('a{}').toResult().css //=> "a{}"
*/
this.css = undefined;
/**
* @member {SourceMapGenerator} - An instance of `SourceMapGenerator`
* class from the `source-map` library,
* representing changes
* to the {@link Result#root} instance.
*
* @example
* result.map.toJSON() //=> { version: 3, file: 'a.css', … }
*
* @example
* if ( result.map ) {
* fs.writeFileSync(result.opts.to + '.map', result.map.toString());
* }
*/
this.map = undefined;
}
/**
* Returns for @{link Result#css} content.
*
* @example
* result + '' === result.css
*
* @return {string} string representing of {@link Result#root}
*/
Result.prototype.toString = function toString() {
return this.css;
};
/**
* Creates an instance of {@link Warning} and adds it
* to {@link Result#messages}.
*
* @param {string} text - warning message
* @param {Object} [opts] - warning options
* @param {Node} opts.node - CSS node that caused the warning
* @param {string} opts.word - word in CSS source that caused the warning
* @param {number} opts.index - index in CSS node string that caused
* the warning
* @param {string} opts.plugin - name of the plugin that created
* this warning. {@link Result#warn} fills
* this property automatically.
*
* @return {Warning} created warning
*/
Result.prototype.warn = function warn(text) {
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if (!opts.plugin) {
if (this.lastPlugin && this.lastPlugin.postcssPlugin) {
opts.plugin = this.lastPlugin.postcssPlugin;
}
}
var warning = new Warning(text, opts);
this.messages.push(warning);
return warning;
};
/**
* Returns warnings from plugins. Filters {@link Warning} instances
* from {@link Result#messages}.
*
* @example
* result.warnings().forEach(warn => {
* console.warn(warn.toString());
* });
*
* @return {Warning[]} warnings from plugins
*/
Result.prototype.warnings = function warnings() {
return this.messages.filter(function (i) {
return i.type === 'warning';
});
};
/**
* An alias for the {@link Result#css} property.
* Use it with syntaxes that generate non-CSS output.
* @type {string}
*
* @example
* result.css === result.content;
*/
createClass(Result, [{
key: 'content',
get: function get$$1() {
return this.css;
}
}]);
return Result;
}();
function isPromise(obj) {
return (typeof obj === 'undefined' ? 'undefined' : _typeof(obj)) === 'object' && typeof obj.then === 'function';
}
/**
* @callback onFulfilled
* @param {Result} result
*/
/**
* @callback onRejected
* @param {Error} error
*/
/**
* A Promise proxy for the result of PostCSS transformations.
*
* A `LazyResult` instance is returned by {@link Processor#process}.
*
* @example
* const lazy = postcss([cssnext]).process(css);
*/
var LazyResult = function () {
function LazyResult(processor, css, opts) {
classCallCheck(this, LazyResult);
this.stringified = false;
this.processed = false;
var root = void 0;
if ((typeof css === 'undefined' ? 'undefined' : _typeof(css)) === 'object' && css.type === 'root') {
root = css;
} else if (css instanceof LazyResult || css instanceof Result) {
root = css.root;
if (css.map) {
if (typeof opts.map === 'undefined') opts.map = {};
if (!opts.map.inline) opts.map.inline = false;
opts.map.prev = css.map;
}
} else {
var parser = parse;
if (opts.syntax) parser = opts.syntax.parse;
if (opts.parser) parser = opts.parser;
if (parser.parse) parser = parser.parse;
try {
root = parser(css, opts);
} catch (error) {
this.error = error;
}
}
this.result = new Result(processor, root, opts);
}
/**
* Returns a {@link Processor} instance, which will be used
* for CSS transformations.
* @type {Processor}
*/
/**
* Processes input CSS through synchronous plugins
* and calls {@link Result#warnings()}.
*
* @return {Warning[]} warnings from plugins
*/
LazyResult.prototype.warnings = function warnings() {
return this.sync().warnings();
};
/**
* Alias for the {@link LazyResult#css} property.
*
* @example
* lazy + '' === lazy.css;
*
* @return {string} output CSS
*/
LazyResult.prototype.toString = function toString() {
return this.css;
};
/**
* Processes input CSS through synchronous and asynchronous plugins
* and calls `onFulfilled` with a Result instance. If a plugin throws
* an error, the `onRejected` callback will be executed.
*
* It implements standard Promise API.
*
* @param {onFulfilled} onFulfilled - callback will be executed
* when all plugins will finish work
* @param {onRejected} onRejected - callback will be execited on any error
*
* @return {Promise} Promise API to make queue
*
* @example
* postcss([cssnext]).process(css).then(result => {
* console.log(result.css);
* });
*/
LazyResult.prototype.then = function then(onFulfilled, onRejected) {
return this.async().then(onFulfilled, onRejected);
};
/**
* Processes input CSS through synchronous and asynchronous plugins
* and calls onRejected for each error thrown in any plugin.
*
* It implements standard Promise API.
*
* @param {onRejected} onRejected - callback will be execited on any error
*
* @return {Promise} Promise API to make queue
*
* @example
* postcss([cssnext]).process(css).then(result => {
* console.log(result.css);
* }).catch(error => {
* console.error(error);
* });
*/
LazyResult.prototype.catch = function _catch(onRejected) {
return this.async().catch(onRejected);
};
LazyResult.prototype.handleError = function handleError(error, plugin) {
try {
this.error = error;
if (error.name === 'CssSyntaxError' && !error.plugin) {
error.plugin = plugin.postcssPlugin;
error.setMessage();
} else if (plugin.postcssVersion) {
var pluginName = plugin.postcssPlugin;
var pluginVer = plugin.postcssVersion;
var runtimeVer = this.result.processor.version;
var a = pluginVer.split('.');
var b = runtimeVer.split('.');
if (a[0] !== b[0] || parseInt(a[1]) > parseInt(b[1])) {
warnOnce('Your current PostCSS version ' + 'is ' + runtimeVer + ', but ' + pluginName + ' ' + 'uses ' + pluginVer + '. Perhaps this is ' + 'the source of the error below.');
}
}
} catch (err) {
if (console && console.error) console.error(err);
}
};
LazyResult.prototype.asyncTick = function asyncTick(resolve, reject) {
var _this = this;
if (this.plugin >= this.processor.plugins.length) {
this.processed = true;
return resolve();
}
try {
var plugin = this.processor.plugins[this.plugin];
var promise = this.run(plugin);
this.plugin += 1;
if (isPromise(promise)) {
promise.then(function () {
_this.asyncTick(resolve, reject);
}).catch(function (error) {
_this.handleError(error, plugin);
_this.processed = true;
reject(error);
});
} else {
this.asyncTick(resolve, reject);
}
} catch (error) {
this.processed = true;
reject(error);
}
};
LazyResult.prototype.async = function async() {
var _this2 = this;
if (this.processed) {
return new Promise(function (resolve, reject) {
if (_this2.error) {
reject(_this2.error);
} else {
resolve(_this2.stringify());
}
});
}
if (this.processing) {
return this.processing;
}
this.processing = new Promise(function (resolve, reject) {
if (_this2.error) return reject(_this2.error);
_this2.plugin = 0;
_this2.asyncTick(resolve, reject);
}).then(function () {
_this2.processed = true;
return _this2.stringify();
});
return this.processing;
};
LazyResult.prototype.sync = function sync() {
var _this3 = this;
if (this.processed) return this.result;
this.processed = true;
if (this.processing) {
throw new Error('Use process(css).then(cb) to work with async plugins');
}
if (this.error) throw this.error;
this.result.processor.plugins.forEach(function (plugin) {
var promise = _this3.run(plugin);
if (isPromise(promise)) {
throw new Error('Use process(css).then(cb) to work with async plugins');
}
});
return this.result;
};
LazyResult.prototype.run = function run(plugin) {
this.result.lastPlugin = plugin;
try {
return plugin(this.result.root, this.result);
} catch (error) {
this.handleError(error, plugin);
throw error;
}
};
LazyResult.prototype.stringify = function stringify$$1() {
if (this.stringified) return this.result;
this.stringified = true;
this.sync();
var opts = this.result.opts;
var str = stringify;
if (opts.syntax) str = opts.syntax.stringify;
if (opts.stringifier) str = opts.stringifier;
if (str.stringify) str = str.stringify;
var result = '';
str(this.root, function (i) {
result += i;
});
this.result.css = result;
return this.result;
};
createClass(LazyResult, [{
key: 'processor',
get: function get$$1() {
return this.result.processor;
}
/**
* Options from the {@link Processor#process} call.
* @type {processOptions}
*/
}, {
key: 'opts',
get: function get$$1() {
return this.result.opts;
}
/**
* Processes input CSS through synchronous plugins, converts `Root`
* to a CSS string and returns {@link Result#css}.
*
* This property will only work with synchronous plugins.
* If the processor contains any asynchronous plugins
* it will throw an error. This is why this method is only
* for debug purpose, you should always use {@link LazyResult#then}.
*
* @type {string}
* @see Result#css
*/
}, {
key: 'css',
get: function get$$1() {
return this.stringify().css;
}
/**
* An alias for the `css` property. Use it with syntaxes
* that generate non-CSS output.
*
* This property will only work with synchronous plugins.
* If the processor contains any asynchronous plugins
* it will throw an error. This is why this method is only
* for debug purpose, you should always use {@link LazyResult#then}.
*
* @type {string}
* @see Result#content
*/
}, {
key: 'content',
get: function get$$1() {
return this.stringify().content;
}
/**
* Processes input CSS through synchronous plugins
* and returns {@link Result#map}.
*
* This property will only work with synchronous plugins.
* If the processor contains any asynchronous plugins
* it will throw an error. This is why this method is only
* for debug purpose, you should always use {@link LazyResult#then}.
*
* @type {SourceMapGenerator}
* @see Result#map
*/
}, {
key: 'map',
get: function get$$1() {
return this.stringify().map;
}
/**
* Processes input CSS through synchronous plugins
* and returns {@link Result#root}.
*
* This property will only work with synchronous plugins. If the processor
* contains any asynchronous plugins it will throw an error.
*
* This is why this method is only for debug purpose,
* you should always use {@link LazyResult#then}.
*
* @type {Root}
* @see Result#root
*/
}, {
key: 'root',
get: function get$$1() {
return this.sync().root;
}
/**
* Processes input CSS through synchronous plugins
* and returns {@link Result#messages}.
*
* This property will only work with synchronous plugins. If the processor
* contains any asynchronous plugins it will throw an error.
*
* This is why this method is only for debug purpose,
* you should always use {@link LazyResult#then}.
*
* @type {Message[]}
* @see Result#messages
*/
}, {
key: 'messages',
get: function get$$1() {
return this.sync().messages;
}
}]);
return LazyResult;
}();
/**
* @callback builder
* @param {string} part - part of generated CSS connected to this node
* @param {Node} node - AST node
* @param {"start"|"end"} [type] - node’s part type
*/
/**
* @callback parser
*
* @param {string|toString} css - string with input CSS or any object
* with toString() method, like a Buffer
* @param {processOptions} [opts] - options with only `from` and `map` keys
*
* @return {Root} PostCSS AST
*/
/**
* @callback stringifier
*
* @param {Node} node - start node for stringifing. Usually {@link Root}.
* @param {builder} builder - function to concatenate CSS from node’s parts
* or generate string and source map
*
* @return {void}
*/
/**
* @typedef {object} syntax
* @property {parser} parse - function to generate AST by string
* @property {stringifier} stringify - function to generate string by AST
*/
/**
* @typedef {object} toString
* @property {function} toString
*/
/**
* @callback pluginFunction
* @param {Root} root - parsed input CSS
* @param {Result} result - result to set warnings or check other plugins
*/
/**
* @typedef {object} Plugin
* @property {function} postcss - PostCSS plugin function
*/
/**
* @typedef {object} processOptions
* @property {string} from - the path of the CSS source file.
* You should always set `from`,
* because it is used in source map
* generation and syntax error messages.
* @property {string} to - the path where you’ll put the output
* CSS file. You should always set `to`
* to generate correct source maps.
* @property {parser} parser - function to generate AST by string
* @property {stringifier} stringifier - class to generate string by AST
* @property {syntax} syntax - object with `parse` and `stringify`
* @property {object} map - source map options
* @property {boolean} map.inline - does source map should
* be embedded in the output
* CSS as a base64-encoded
* comment
* @property {string|object|false|function} map.prev - source map content
* from a previous
* processing step
* (for example, Sass).
* PostCSS will try to find
* previous map
* automatically, so you
* could disable it by
* `false` value.
* @property {boolean} map.sourcesContent - does PostCSS should set
* the origin content to map
* @property {string|false} map.annotation - does PostCSS should set
* annotation comment to map
* @property {string} map.from - override `from` in map’s
* `sources`
*/
/**
* Contains plugins to process CSS. Create one `Processor` instance,
* initialize its plugins, and then use that instance on numerous CSS files.
*
* @example
* const processor = postcss([autoprefixer, precss]);
* processor.process(css1).then(result => console.log(result.css));
* processor.process(css2).then(result => console.log(result.css));
*/
var Processor = function () {
/**
* @param {Array.<Plugin|pluginFunction>|Processor} plugins - PostCSS
* plugins. See {@link Processor#use} for plugin format.
*/
function Processor() {
var plugins = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : [];
classCallCheck(this, Processor);
/**
* @member {string} - Current PostCSS version.
*
* @example
* if ( result.processor.version.split('.')[0] !== '5' ) {
* throw new Error('This plugin works only with PostCSS 5');
* }
*/
this.version = '5.2.0';
/**
* @member {pluginFunction[]} - Plugins added to this processor.
*
* @example
* const processor = postcss([autoprefixer, precss]);
* processor.plugins.length //=> 2
*/
this.plugins = this.normalize(plugins);
}
/**
* Adds a plugin to be used as a CSS processor.
*
* PostCSS plugin can be in 4 formats:
* * A plugin created by {@link postcss.plugin} method.
* * A function. PostCSS will pass the function a @{link Root}
* as the first argument and current {@link Result} instance
* as the second.
* * An object with a `postcss` method. PostCSS will use that method
* as described in #2.
* * Another {@link Processor} instance. PostCSS will copy plugins
* from that instance into this one.
*
* Plugins can also be added by passing them as arguments when creating
* a `postcss` instance (see [`postcss(plugins)`]).
*
* Asynchronous plugins should return a `Promise` instance.
*
* @param {Plugin|pluginFunction|Processor} plugin - PostCSS plugin
* or {@link Processor}
* with plugins
*
* @example
* const processor = postcss()
* .use(autoprefixer)
* .use(precss);
*
* @return {Processes} current processor to make methods chain
*/
Processor.prototype.use = function use(plugin) {
this.plugins = this.plugins.concat(this.normalize([plugin]));
return this;
};
/**
* Parses source CSS and returns a {@link LazyResult} Promise proxy.
* Because some plugins can be asynchronous it doesn’t make
* any transformations. Transformations will be applied
* in the {@link LazyResult} methods.
*
* @param {string|toString|Result} css - String with input CSS or
* any object with a `toString()`
* method, like a Buffer.
* Optionally, send a {@link Result}
* instance and the processor will
* take the {@link Root} from it.
* @param {processOptions} [opts] - options
*
* @return {LazyResult} Promise proxy
*
* @example
* processor.process(css, { from: 'a.css', to: 'a.out.css' })
* .then(result => {
* console.log(result.css);
* });
*/
Processor.prototype.process = function process(css) {
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
return new LazyResult(this, css, opts);
};
Processor.prototype.normalize = function normalize(plugins) {
var normalized = [];
plugins.forEach(function (i) {
if (i.postcss) i = i.postcss;
if ((typeof i === 'undefined' ? 'undefined' : _typeof(i)) === 'object' && Array.isArray(i.plugins)) {
normalized = normalized.concat(i.plugins);
} else if (typeof i === 'function') {
normalized.push(i);
} else {
throw new Error(i + ' is not a PostCSS plugin');
}
});
return normalized;
};
return Processor;
}();
/**
* Represents a CSS file and contains all its parsed nodes.
*
* @extends Container
*
* @example
* const root = postcss.parse('a{color:black} b{z-index:2}');
* root.type //=> 'root'
* root.nodes.length //=> 2
*/
var Root = function (_Container) {
inherits(Root, _Container);
function Root(defaults$$1) {
classCallCheck(this, Root);
var _this = possibleConstructorReturn(this, _Container.call(this, defaults$$1));
_this.type = 'root';
if (!_this.nodes) _this.nodes = [];
return _this;
}
Root.prototype.removeChild = function removeChild(child) {
child = this.index(child);
if (child === 0 && this.nodes.length > 1) {
this.nodes[1].raws.before = this.nodes[child].raws.before;
}
return _Container.prototype.removeChild.call(this, child);
};
Root.prototype.normalize = function normalize(child, sample, type) {
var nodes = _Container.prototype.normalize.call(this, child);
if (sample) {
if (type === 'prepend') {
if (this.nodes.length > 1) {
sample.raws.before = this.nodes[1].raws.before;
} else {
delete sample.raws.before;
}
} else if (this.first !== sample) {
nodes.forEach(function (node) {
node.raws.before = sample.raws.before;
});
}
}
return nodes;
};
/**
* Returns a {@link Result} instance representing the root’s CSS.
*
* @param {processOptions} [opts] - options with only `to` and `map` keys
*
* @return {Result} result with current root’s CSS
*
* @example
* const root1 = postcss.parse(css1, { from: 'a.css' });
* const root2 = postcss.parse(css2, { from: 'b.css' });
* root1.append(root2);
* const result = root1.toResult({ to: 'all.css', map: true });
*/
Root.prototype.toResult = function toResult() {
var opts = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {};
var lazy = new LazyResult(new Processor(), this, opts);
return lazy.stringify();
};
Root.prototype.remove = function remove(child) {
warnOnce('Root#remove is deprecated. Use Root#removeChild');
this.removeChild(child);
};
Root.prototype.prevMap = function prevMap() {
warnOnce('Root#prevMap is deprecated. Use Root#source.input.map');
return this.source.input.map;
};
/**
* @memberof Root#
* @member {object} raws - Information to generate byte-to-byte equal
* node string as it was in the origin input.
*
* Every parser saves its own properties,
* but the default CSS parser uses:
*
* * `after`: the space symbols after the last child to the end of file.
* * `semicolon`: is the last child has an (optional) semicolon.
*
* @example
* postcss.parse('a {}\n').raws //=> { after: '\n' }
* postcss.parse('a {}').raws //=> { after: '' }
*/
return Root;
}(Container);
// import PreviousMap from './previous-map';
var sequence = 0;
/**
* @typedef {object} filePosition
* @property {string} file - path to file
* @property {number} line - source line in file
* @property {number} column - source column in file
*/
/**
* Represents the source CSS.
*
* @example
* const root = postcss.parse(css, { from: file });
* const input = root.source.input;
*/
var Input = function () {
/**
* @param {string} css - input CSS source
* @param {object} [opts] - {@link Processor#process} options
*/
function Input(css) {
var opts = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
classCallCheck(this, Input);
/**
* @member {string} - input CSS source
*
* @example
* const input = postcss.parse('a{}', { from: file }).input;
* input.css //=> "a{}";
*/
this.css = css.toString();
if (this.css[0] === '\uFEFF' || this.css[0] === '\uFFFE') {
this.css = this.css.slice(1);
}
if (opts.from) {
if (/^\w+:\/\//.test(opts.from)) {
/**
* @member {string} - The absolute path to the CSS source file
* defined with the `from` option.
*
* @example
* const root = postcss.parse(css, { from: 'a.css' });
* root.source.input.file //=> '/home/ai/a.css'
*/
this.file = opts.from;
} else {
this.file = path.resolve(opts.from);
}
}
/*
let map = new PreviousMap(this.css, opts);
if ( map.text ) {
/!**
* @member {PreviousMap} - The input source map passed from
* a compilation step before PostCSS
* (for example, from Sass compiler).
*
* @example
* root.source.input.map.consumer().sources //=> ['a.sass']
*!/
this.map = map;
let file = map.consumer().file;
if ( !this.file && file ) this.file = this.mapResolve(file);
}
*/
if (!this.file) {
sequence += 1;
/**
* @member {string} - The unique ID of the CSS source. It will be
* created if `from` option is not provided
* (because PostCSS does not know the file path).
*
* @example
* const root = postcss.parse(css);
* root.source.input.file //=> undefined
* root.source.input.id //=> "<input css 1>"
*/
this.id = '<input css ' + sequence + '>';
}
if (this.map) this.map.file = this.from;
}
Input.prototype.error = function error(message, line, column) {
var opts = arguments.length > 3 && arguments[3] !== undefined ? arguments[3] : {};
var result = void 0;
var origin = this.origin(line, column);
if (origin) {
result = new CssSyntaxError(message, origin.line, origin.column, origin.source, origin.file, opts.plugin);
} else {
result = new CssSyntaxError(message, line, column, this.css, this.file, opts.plugin);
}
result.input = { line: line, column: column, source: this.css };
if (this.file) result.input.file = this.file;
return result;
};
/**
* Reads the input source map and returns a symbol position
* in the input source (e.g., in a Sass file that was compiled
* to CSS before being passed to PostCSS).
*
* @param {number} line - line in input CSS
* @param {number} column - column in input CSS
*
* @return {filePosition} position in input source
*
* @example
* root.source.input.origin(1, 1) //=> { file: 'a.css', line: 3, column: 1 }
*/
Input.prototype.origin = function origin(line, column) {
if (!this.map) return false;
var consumer = this.map.consumer();
var from = consumer.originalPositionFor({ line: line, column: column });
if (!from.source) return false;
var result = {
file: this.mapResolve(from.source),
line: from.line,
column: from.column
};
var source = consumer.sourceContentFor(from.source);
if (source) result.source = source;
return result;
};
Input.prototype.mapResolve = function mapResolve(file) {
if (/^\w+:\/\//.test(file)) {
return file;
} else {
return path.resolve(this.map.consumer().sourceRoot || '.', file);
}
};
/**
* The CSS source identifier. Contains {@link Input#file} if the user
* set the `from` option, or {@link Input#id} if they did not.
* @type {string}
*
* @example
* const root = postcss.parse(css, { from: 'a.css' });
* root.source.input.from //=> "/home/ai/a.css"
*
* const root = postcss.parse(css);
* root.source.input.from //=> "<input css 1>"
*/
createClass(Input, [{
key: 'from',
get: function get$$1() {
return this.file || this.id;
}
}]);
return Input;
}();
var SafeParser = function (_Parser) {
inherits(SafeParser, _Parser);
function SafeParser() {
classCallCheck(this, SafeParser);
return possibleConstructorReturn(this, _Parser.apply(this, arguments));
}
SafeParser.prototype.tokenize = function tokenize$$1() {
this.tokens = tokenize(this.input, { ignoreErrors: true });
};
SafeParser.prototype.comment = function comment(token) {
var node = new Comment();
this.init(node, token[2], token[3]);
node.source.end = { line: token[4], column: token[5] };
var text = token[1].slice(2);
if (text.slice(-2) === '*/') text = text.slice(0, -2);
if (/^\s*$/.test(text)) {
node.text = '';
node.raws.left = text;
node.raws.right = '';
} else {
var match = text.match(/^(\s*)([^]*[^\s])(\s*)$/);
node.text = match[2];
node.raws.left = match[1];
node.raws.right = match[3];
}
};
SafeParser.prototype.unclosedBracket = function unclosedBracket() {};
SafeParser.prototype.unknownWord = function unknownWord(start) {
var buffer = this.tokens.slice(start, this.pos + 1);
this.spaces += buffer.map(function (i) {
return i[1];
}).join('');
};
SafeParser.prototype.unexpectedClose = function unexpectedClose() {
this.current.raws.after += '}';
};
SafeParser.prototype.doubleColon = function doubleColon() {};
SafeParser.prototype.unnamedAtrule = function unnamedAtrule(node) {
node.name = '';
};
SafeParser.prototype.precheckMissedSemicolon = function precheckMissedSemicolon(tokens) {
var colon = this.colon(tokens);
if (colon === false) return;
var split = void 0;
for (split = colon - 1; split >= 0; split--) {
if (tokens[split][0] === 'word') break;
}
for (split -= 1; split >= 0; split--) {
if (tokens[split][0] !== 'space') {
split += 1;
break;
}
}
var other = tokens.splice(split, tokens.length - split);
this.decl(other);
};
SafeParser.prototype.checkMissedSemicolon = function checkMissedSemicolon() {};
SafeParser.prototype.endFile = function endFile() {
if (this.current.nodes && this.current.nodes.length) {
this.current.raws.semicolon = this.semicolon;
}
this.current.raws.after = (this.current.raws.after || '') + this.spaces;
while (this.current.parent) {
this.current = this.current.parent;
this.current.raws.after = '';
}
};
return SafeParser;
}(Parser);
function safeParse(css, opts) {
var input = new Input(css, opts);
var parser = new SafeParser(input);
parser.tokenize();
parser.loop();
return parser.root;
}
//
/* eslint-disable import/no-unresolved */
var generated = {};
/*
InlineStyle takes arbitrary CSS and generates a flat object
*/
var _InlineStyle = (function (styleSheet) {
var InlineStyle = function () {
function InlineStyle(rules) {
classCallCheck(this, InlineStyle);
this.rules = rules;
}
InlineStyle.prototype.generateStyleObject = function generateStyleObject(executionContext) {
var flatCSS = flatten(this.rules, executionContext).join('');
var hash = murmurhash(flatCSS);
if (!generated[hash]) {
var root = safeParse(flatCSS);
var declPairs = [];
root.each(function (node) {
if (node.type === 'decl') {
declPairs.push([node.prop, node.value]);
} else if (node.type !== 'comment' && process.env.NODE_ENV !== 'production') {
/* eslint-disable no-console */
console.warn('Node of type ' + node.type + ' not supported as an inline style');
}
});
// RN currently does not support differing values for the corner radii of Image
// components (but does for View). It is almost impossible to tell whether we'll have
// support, so we'll just disable multiple values here.
// https://github.com/styled-components/css-to-react-native/issues/11
var styleObject = transformDeclPairs(declPairs, ['borderRadius', 'borderWidth', 'borderColor', 'borderStyle']);
var styles = styleSheet.create({
generated: styleObject
});
generated[hash] = styles.generated;
}
return generated[hash];
};
return InlineStyle;
}();
return InlineStyle;
});
//
function isTag(target) /* : %checks */{
return typeof target === 'string';
}
//
function isStyledComponent(target) /* : %checks */{
return typeof target === 'function' && typeof target.styledComponentId === 'string';
}
//
/* eslint-disable no-undef */
function getComponentName(target) {
return target.displayName || target.name || 'Component';
}
//
var determineTheme = (function (props, fallbackTheme, defaultProps) {
// Props should take precedence over ThemeProvider, which should take precedence over
// defaultProps, but React automatically puts defaultProps on props.
/* eslint-disable react/prop-types */
var isDefaultTheme = defaultProps && props.theme === defaultProps.theme;
var theme = props.theme && !isDefaultTheme ? props.theme : fallbackTheme;
/* eslint-enable */
return theme;
});
//
/**
* Creates a broadcast that can be listened to, i.e. simple event emitter
*
* @see https://github.com/ReactTraining/react-broadcast
*/
var createBroadcast = function createBroadcast(initialState) {
var listeners = {};
var id = 0;
var state = initialState;
function publish(nextState) {
state = nextState;
// eslint-disable-next-line guard-for-in, no-restricted-syntax
for (var key in listeners) {
var listener = listeners[key];
if (listener === undefined) {
// eslint-disable-next-line no-continue
continue;
}
listener(state);
}
}
function subscribe(listener) {
var currentId = id;
listeners[currentId] = listener;
id += 1;
listener(state);
return currentId;
}
function unsubscribe(unsubID) {
listeners[unsubID] = undefined;
}
return { publish: publish, subscribe: subscribe, unsubscribe: unsubscribe };
};
//
// Helper to call a given function, only once
var once = (function (cb) {
var called = false;
return function () {
if (!called) {
called = true;
cb();
}
};
});
var _ThemeProvider$childC;
var _ThemeProvider$contex;
//
/* globals React$Element */
// NOTE: DO NOT CHANGE, changing this is a semver major change!
var CHANNEL = '__styled-components__';
var CHANNEL_NEXT = CHANNEL + 'next__';
var CONTEXT_CHANNEL_SHAPE = PropTypes.shape({
getTheme: PropTypes.func,
subscribe: PropTypes.func,
unsubscribe: PropTypes.func
});
var warnChannelDeprecated = void 0;
if (process.env.NODE_ENV !== 'production') {
warnChannelDeprecated = once(function () {
// eslint-disable-next-line no-console
console.error('Warning: Usage of `context.' + CHANNEL + '` as a function is deprecated. It will be replaced with the object on `.context.' + CHANNEL_NEXT + '` in a future version.');
});
}
var isFunction = function isFunction(test) {
return typeof test === 'function';
};
/**
* Provide a theme to an entire react component tree via context and event listeners (have to do
* both context and event emitter as pure components block context updates)
*/
var ThemeProvider = function (_Component) {
inherits(ThemeProvider, _Component);
function ThemeProvider() {
classCallCheck(this, ThemeProvider);
var _this = possibleConstructorReturn(this, _Component.call(this));
_this.unsubscribeToOuterId = -1;
_this.getTheme = _this.getTheme.bind(_this);
return _this;
}
ThemeProvider.prototype.componentWillMount = function componentWillMount() {
var _this2 = this;
// If there is a ThemeProvider wrapper anywhere around this theme provider, merge this theme
// with the outer theme
var outerContext = this.context[CHANNEL_NEXT];
if (outerContext !== undefined) {
this.unsubscribeToOuterId = outerContext.subscribe(function (theme) {
_this2.outerTheme = theme;
if (_this2.broadcast !== undefined) {
_this2.publish(_this2.props.theme);
}
});
}
this.broadcast = createBroadcast(this.getTheme());
};
ThemeProvider.prototype.getChildContext = function getChildContext() {
var _this3 = this,
_babelHelpers$extends;
return _extends({}, this.context, (_babelHelpers$extends = {}, _babelHelpers$extends[CHANNEL_NEXT] = {
getTheme: this.getTheme,
subscribe: this.broadcast.subscribe,
unsubscribe: this.broadcast.unsubscribe
}, _babelHelpers$extends[CHANNEL] = function (subscriber) {
if (process.env.NODE_ENV !== 'production') {
warnChannelDeprecated();
}
// Patch the old `subscribe` provide via `CHANNEL` for older clients.
var unsubscribeId = _this3.broadcast.subscribe(subscriber);
return function () {
return _this3.broadcast.unsubscribe(unsubscribeId);
};
}, _babelHelpers$extends));
};
ThemeProvider.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
if (this.props.theme !== nextProps.theme) {
this.publish(nextProps.theme);
}
};
ThemeProvider.prototype.componentWillUnmount = function componentWillUnmount() {
if (this.unsubscribeToOuterId !== -1) {
this.context[CHANNEL_NEXT].unsubscribe(this.unsubscribeToOuterId);
}
};
// Get the theme from the props, supporting both (outerTheme) => {} as well as object notation
ThemeProvider.prototype.getTheme = function getTheme(passedTheme) {
var theme = passedTheme || this.props.theme;
if (isFunction(theme)) {
var mergedTheme = theme(this.outerTheme);
if (process.env.NODE_ENV !== 'production' && !isPlainObject(mergedTheme)) {
throw new Error(process.env.NODE_ENV !== 'production' ? '[ThemeProvider] Please return an object from your theme function, i.e. theme={() => ({})}!' : '');
}
return mergedTheme;
}
if (!isPlainObject(theme)) {
throw new Error(process.env.NODE_ENV !== 'production' ? '[ThemeProvider] Please make your theme prop a plain object' : '');
}
return _extends({}, this.outerTheme, theme);
};
ThemeProvider.prototype.publish = function publish(theme) {
this.broadcast.publish(this.getTheme(theme));
};
ThemeProvider.prototype.render = function render() {
if (!this.props.children) {
return null;
}
return React.Children.only(this.props.children);
};
return ThemeProvider;
}(Component);
ThemeProvider.childContextTypes = (_ThemeProvider$childC = {}, _ThemeProvider$childC[CHANNEL] = PropTypes.func, _ThemeProvider$childC[CHANNEL_NEXT] = CONTEXT_CHANNEL_SHAPE, _ThemeProvider$childC);
ThemeProvider.contextTypes = (_ThemeProvider$contex = {}, _ThemeProvider$contex[CHANNEL_NEXT] = CONTEXT_CHANNEL_SHAPE, _ThemeProvider$contex);
//
var _StyledNativeComponent = (function (constructWithOptions, InlineStyle) {
var BaseStyledNativeComponent = function (_Component) {
inherits(BaseStyledNativeComponent, _Component);
function BaseStyledNativeComponent() {
var _temp, _this, _ret;
classCallCheck(this, BaseStyledNativeComponent);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = possibleConstructorReturn(this, _Component.call.apply(_Component, [this].concat(args))), _this), _this.attrs = {}, _this.state = {
theme: null,
generatedStyles: undefined
}, _this.unsubscribeId = -1, _this.onRef = function (node) {
// eslint-disable-next-line react/prop-types
var innerRef = _this.props.innerRef;
_this.root = node;
if (typeof innerRef === 'function') {
innerRef(node);
}
}, _temp), possibleConstructorReturn(_this, _ret);
}
BaseStyledNativeComponent.prototype.unsubscribeFromContext = function unsubscribeFromContext() {
if (this.unsubscribeId !== -1) {
this.context[CHANNEL_NEXT].unsubscribe(this.unsubscribeId);
}
};
BaseStyledNativeComponent.prototype.buildExecutionContext = function buildExecutionContext(theme, props) {
var attrs = this.constructor.attrs;
var context = _extends({}, props, { theme: theme });
if (attrs === undefined) {
return context;
}
this.attrs = Object.keys(attrs).reduce(function (acc, key) {
var attr = attrs[key];
// eslint-disable-next-line no-param-reassign
acc[key] = typeof attr === 'function' ? attr(context) : attr;
return acc;
}, {});
return _extends({}, context, this.attrs);
};
BaseStyledNativeComponent.prototype.generateAndInjectStyles = function generateAndInjectStyles(theme, props) {
var inlineStyle = this.constructor.inlineStyle;
var executionContext = this.buildExecutionContext(theme, props);
return inlineStyle.generateStyleObject(executionContext);
};
BaseStyledNativeComponent.prototype.componentWillMount = function componentWillMount() {
var _this2 = this;
// If there is a theme in the context, subscribe to the event emitter. This
// is necessary due to pure components blocking context updates, this circumvents
// that by updating when an event is emitted
var styledContext = this.context[CHANNEL_NEXT];
if (styledContext !== undefined) {
var subscribe = styledContext.subscribe;
this.unsubscribeId = subscribe(function (nextTheme) {
// This will be called once immediately
var theme = determineTheme(_this2.props, nextTheme, _this2.constructor.defaultProps);
var generatedStyles = _this2.generateAndInjectStyles(theme, _this2.props);
_this2.setState({ theme: theme, generatedStyles: generatedStyles });
});
} else {
// eslint-disable-next-line react/prop-types
var theme = this.props.theme || {};
var generatedStyles = this.generateAndInjectStyles(theme, this.props);
this.setState({ theme: theme, generatedStyles: generatedStyles });
}
};
BaseStyledNativeComponent.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
var _this3 = this;
this.setState(function (oldState) {
var theme = determineTheme(nextProps, oldState.theme, _this3.constructor.defaultProps);
var generatedStyles = _this3.generateAndInjectStyles(theme, nextProps);
return { theme: theme, generatedStyles: generatedStyles };
});
};
BaseStyledNativeComponent.prototype.componentWillUnmount = function componentWillUnmount() {
this.unsubscribeFromContext();
};
BaseStyledNativeComponent.prototype.setNativeProps = function setNativeProps(nativeProps) {
if (this.root !== undefined) {
// $FlowFixMe
this.root.setNativeProps(nativeProps);
} else if (process.env.NODE_ENV !== 'production') {
var displayName = this.constructor.displayName;
// eslint-disable-next-line no-console
console.warn('setNativeProps was called on a Styled Component wrapping a stateless functional component. ' + 'In this case no ref will be stored, and instead an innerRef prop will be passed on.\n' + ('Check whether the stateless functional component is passing on innerRef as a ref in ' + displayName + '.'));
}
};
BaseStyledNativeComponent.prototype.render = function render() {
// eslint-disable-next-line react/prop-types
var _props = this.props,
children = _props.children,
style = _props.style;
var generatedStyles = this.state.generatedStyles;
var target = this.constructor.target;
var propsForElement = _extends({}, this.attrs, this.props, {
style: [generatedStyles, style]
});
if (!isStyledComponent(target) && (
// NOTE: We can't pass a ref to a stateless functional component
typeof target !== 'function' || target.prototype && 'isReactComponent' in target.prototype)) {
propsForElement.ref = this.onRef;
delete propsForElement.innerRef;
} else {
propsForElement.innerRef = this.onRef;
}
return createElement(target, propsForElement, children);
};
return BaseStyledNativeComponent;
}(Component);
var createStyledNativeComponent = function createStyledNativeComponent(target, options, rules) {
var _StyledNativeComponen;
var _options$displayName = options.displayName,
displayName = _options$displayName === undefined ? isTag(target) ? 'styled.' + target : 'Styled(' + getComponentName(target) + ')' : _options$displayName,
_options$ParentCompon = options.ParentComponent,
ParentComponent = _options$ParentCompon === undefined ? BaseStyledNativeComponent : _options$ParentCompon,
extendingRules = options.rules,
attrs = options.attrs;
var inlineStyle = new InlineStyle(extendingRules === undefined ? rules : extendingRules.concat(rules));
var StyledNativeComponent = function (_ParentComponent) {
inherits(StyledNativeComponent, _ParentComponent);
function StyledNativeComponent() {
classCallCheck(this, StyledNativeComponent);
return possibleConstructorReturn(this, _ParentComponent.apply(this, arguments));
}
StyledNativeComponent.withComponent = function withComponent(tag) {
var _ = options.displayName,
__ = options.componentId,
optionsToCopy = objectWithoutProperties(options, ['displayName', 'componentId']);
var newOptions = _extends({}, optionsToCopy, {
ParentComponent: StyledNativeComponent
});
return createStyledNativeComponent(tag, newOptions, rules);
};
// NOTE: This is so that isStyledComponent passes for the innerRef unwrapping
createClass(StyledNativeComponent, null, [{
key: 'extend',
get: function get$$1() {
var _ = options.displayName,
__ = options.componentId,
rulesFromOptions = options.rules,
optionsToCopy = objectWithoutProperties(options, ['displayName', 'componentId', 'rules']);
var newRules = rulesFromOptions === undefined ? rules : rulesFromOptions.concat(rules);
var newOptions = _extends({}, optionsToCopy, {
rules: newRules,
ParentComponent: StyledNativeComponent
});
return constructWithOptions(createStyledNativeComponent, target, newOptions);
}
}]);
return StyledNativeComponent;
}(ParentComponent);
StyledNativeComponent.displayName = displayName;
StyledNativeComponent.target = target;
StyledNativeComponent.attrs = attrs;
StyledNativeComponent.inlineStyle = inlineStyle;
StyledNativeComponent.contextTypes = (_StyledNativeComponen = {}, _StyledNativeComponen[CHANNEL] = PropTypes.func, _StyledNativeComponen[CHANNEL_NEXT] = CONTEXT_CHANNEL_SHAPE, _StyledNativeComponen);
StyledNativeComponent.styledComponentId = 'StyledNativeComponent';
return StyledNativeComponent;
};
return createStyledNativeComponent;
});
//
var _constructWithOptions = (function (css) {
var constructWithOptions = function constructWithOptions(componentConstructor, tag) {
var options = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : {};
if (!isValidElementType(tag)) {
throw new Error(process.env.NODE_ENV !== 'production' ? 'Cannot create styled-component for component: ' + String(tag) : '');
}
/* This is callable directly as a template function */
// $FlowFixMe: Not typed to avoid destructuring arguments
var templateFunction = function templateFunction() {
return componentConstructor(tag, options, css.apply(undefined, arguments));
};
/* If config methods are called, wrap up a new template function and merge options */
templateFunction.withConfig = function (config) {
return constructWithOptions(componentConstructor, tag, _extends({}, options, config));
};
templateFunction.attrs = function (attrs) {
return constructWithOptions(componentConstructor, tag, _extends({}, options, {
attrs: _extends({}, options.attrs || {}, attrs)
}));
};
return templateFunction;
};
return constructWithOptions;
});
//
var interleave = (function (strings, interpolations) {
return interpolations.reduce(function (array, interp, i) {
return array.concat(interp, strings[i + 1]);
}, [strings[0]]);
});
//
var css = (function (strings) {
for (var _len = arguments.length, interpolations = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) {
interpolations[_key - 1] = arguments[_key];
}
return flatten(interleave(strings, interpolations));
});
//
/* globals ReactClass */
var wrapWithTheme = function wrapWithTheme(Component$$1) {
var _WithTheme$contextTyp;
var componentName = Component$$1.displayName || Component$$1.name || 'Component';
var isStatelessFunctionalComponent = typeof Component$$1 === 'function' && !(Component$$1.prototype && 'isReactComponent' in Component$$1.prototype);
// NOTE: We can't pass a ref to a stateless functional component
var shouldSetInnerRef = isStyledComponent(Component$$1) || isStatelessFunctionalComponent;
var WithTheme = function (_React$Component) {
inherits(WithTheme, _React$Component);
function WithTheme() {
var _temp, _this, _ret;
classCallCheck(this, WithTheme);
for (var _len = arguments.length, args = Array(_len), _key = 0; _key < _len; _key++) {
args[_key] = arguments[_key];
}
return _ret = (_temp = (_this = possibleConstructorReturn(this, _React$Component.call.apply(_React$Component, [this].concat(args))), _this), _this.state = {}, _this.unsubscribeId = -1, _temp), possibleConstructorReturn(_this, _ret);
}
// NOTE: This is so that isStyledComponent passes for the innerRef unwrapping
WithTheme.prototype.componentWillMount = function componentWillMount() {
var _this2 = this;
var defaultProps = this.constructor.defaultProps;
var styledContext = this.context[CHANNEL_NEXT];
var themeProp = determineTheme(this.props, undefined, defaultProps);
if (styledContext === undefined && themeProp === undefined && process.env.NODE_ENV !== 'production') {
// eslint-disable-next-line no-console
console.warn('[withTheme] You are not using a ThemeProvider nor passing a theme prop or a theme in defaultProps');
} else if (styledContext === undefined && themeProp !== undefined) {
this.setState({ theme: themeProp });
} else {
var subscribe = styledContext.subscribe;
this.unsubscribeId = subscribe(function (nextTheme) {
var theme = determineTheme(_this2.props, nextTheme, defaultProps);
_this2.setState({ theme: theme });
});
}
};
WithTheme.prototype.componentWillReceiveProps = function componentWillReceiveProps(nextProps) {
var defaultProps = this.constructor.defaultProps;
this.setState(function (oldState) {
var theme = determineTheme(nextProps, oldState.theme, defaultProps);
return { theme: theme };
});
};
WithTheme.prototype.componentWillUnmount = function componentWillUnmount() {
if (this.unsubscribeId !== -1) {
this.context[CHANNEL_NEXT].unsubscribe(this.unsubscribeId);
}
};
WithTheme.prototype.render = function render() {
var props = _extends({
theme: this.state.theme
}, this.props);
if (!shouldSetInnerRef) {
props.ref = props.innerRef;
delete props.innerRef;
}
return React.createElement(Component$$1, props);
};
return WithTheme;
}(React.Component);
WithTheme.displayName = 'WithTheme(' + componentName + ')';
WithTheme.styledComponentId = 'withTheme';
WithTheme.contextTypes = (_WithTheme$contextTyp = {}, _WithTheme$contextTyp[CHANNEL] = PropTypes.func, _WithTheme$contextTyp[CHANNEL_NEXT] = CONTEXT_CHANNEL_SHAPE, _WithTheme$contextTyp);
return hoistStatics(WithTheme, Component$$1);
};
//
/* eslint-disable import/no-unresolved */
var constructWithOptions = _constructWithOptions(css);
var InlineStyle = _InlineStyle(reactPrimitives.StyleSheet);
var StyledNativeComponent = _StyledNativeComponent(constructWithOptions, InlineStyle);
var styled = function styled(tag) {
return constructWithOptions(StyledNativeComponent, tag);
};
/* React native lazy-requires each of these modules for some reason, so let's
* assume it's for a good reason and not eagerly load them all */
var aliases = 'Image Text Touchable View ';
/* Define a getter for each alias which simply gets the reactNative component
* and passes it to styled */
aliases.split(/\s+/m).forEach(function (alias) {
return Object.defineProperty(styled, alias, {
enumerable: true,
configurable: false,
get: function get() {
return styled(reactPrimitives[alias]);
}
});
});
export { css, isStyledComponent, ThemeProvider, wrapWithTheme as withTheme };
export default styled;
//# sourceMappingURL=styled-components-primitives.es.js.map
|
test/components/ItemSelectionPanel.spec.js | CodeHubOrg/organisations-database | // import expect from 'expect'
// import React from 'react'
// import { shallow } from 'enzyme'
// import ItemSelectionPanel from '../../src/components/ItemSelectionPanel'
// function setup(selected = null){
// const props = {
// selectedItem: selected
// }
// const component = shallow(
// <ItemSelectionPanel {...props} />
// )
// const heading = component.find('.panel-heading')
// const body = component.find('.panel-body')
// return {
// component: component,
// heading: heading,
// body: body,
// h3: heading.find('h3'),
// h4: heading.find('h4'),
// img: body.find('img'),
// description: body.find('p'),
// link: body.find('a')
// }
// }
// describe('Item Selection Panel', () => {
// it('should display a div with class "panel"', () => {
// const { component } = setup()
// expect(component.is('div')).toBe(true)
// expect(component.hasClass('panel')).toBe(true)
// });
// it('should contain a div with class "panel-heading"', () => {
// const { heading } = setup()
// expect(heading.hasClass('panel-heading')).toBe(true)
// });
// it('should contain a h3 element within the panel-heading, with the class "panel-title"', () => {
// const { h3 } = setup()
// expect(h3.hasClass('panel-title')).toBe(true)
// });
// it('should contain a h3 element within the panel-heading, with text "Selected Item:"', () => {
// const { h3 } = setup()
// expect(h3.text()).toMatch(/^Selected Item/)
// });
// it('should have an h4 element saying "None selected" when props selectedItem not set', () => {
// let { h4 } = setup()
// expect(h4.text()).toMatch(/^None selected/)
// });
// it('should have an h4 element saying name of org "JavaScript 101" when JS101 is selected', () => {
// const selectedOrg = {id: 1, name: "JavaScript 101", description: "Group for learning JavaScript"}
// const { h4 } = setup(selectedOrg)
// expect(h4.text()).toMatch(/^JavaScript 101/)
// });
// it('should contain an img element within the panel-body, with the class "resource-image"', () => {
// const { img } = setup()
// expect(img.hasClass('resource-image')).toBe(true)
// });
// it('should contain an img element within the panel-body where the alt is an empty string when selectedItem not set', () => {
// const { img } = setup()
// expect(img.equals(<img className="resource-image" alt='' src='' />)).toBe(true)
// });
// it('should contain an img element within the panel-body, with the alt "resource_logo" and the src "../constants/javascript101_logo.jpeg" when JS101 is selected', () => {
// const selectedOrg = {id: 1, name: "JavaScript 101", imagepath: "../constants/javascript101_logo.jpeg"}
// const { img } = setup(selectedOrg)
// expect(img.equals(<img className="resource-image" alt='resource_logo' src='../constants/javascript101_logo.jpeg' />)).toBe(true)
// });
// it('should contain a p element within the panel-body, with the class "resource-descrip"', () => {
// const { description } = setup()
// expect(description.hasClass('resource-descrip')).toBe(true)
// });
// it('should contain a p element within the panel-body, with text "Group for learning JavaScript" when JS101 is selected', () => {
// const selectedOrg = {id: 1, name: "JavaScript 101", description: "Group for learning JavaScript"}
// const { description } = setup(selectedOrg)
// expect(description.text()).toMatch(/^Group for learning JavaScript/)
// });
// it('should contain an a element within the panel body where the text is an empty string when props selectedItem not set', () => {
// let { link } = setup()
// expect(link.text()).toMatch(/^/)
// });
// it('should contain an a element within the panel-body, with text "Link to more info" when an item is selected', () => {
// const selectedOrg = {id: 1, name: "JavaScript 101", description: "Group for learning JavaScript"}
// const { link } = setup(selectedOrg)
// expect(link.text()).toMatch(/^Link to more info/)
// });
// }) |
src/svg-icons/notification/ondemand-video.js | matthewoates/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let NotificationOndemandVideo = (props) => (
<SvgIcon {...props}>
<path d="M21 3H3c-1.11 0-2 .89-2 2v12c0 1.1.89 2 2 2h5v2h8v-2h5c1.1 0 1.99-.9 1.99-2L23 5c0-1.11-.9-2-2-2zm0 14H3V5h18v12zm-5-6l-7 4V7z"/>
</SvgIcon>
);
NotificationOndemandVideo = pure(NotificationOndemandVideo);
NotificationOndemandVideo.displayName = 'NotificationOndemandVideo';
NotificationOndemandVideo.muiName = 'SvgIcon';
export default NotificationOndemandVideo;
|
test/regressions/tests/List/SecondaryActionCheckboxListItem.js | Kagami/material-ui | import React from 'react';
import List from '@material-ui/core/List';
import ListItem from '@material-ui/core/ListItem';
import ListItemText from '@material-ui/core/ListItemText';
import ListItemSecondaryAction from '@material-ui/core/ListItemSecondaryAction';
import Checkbox from '@material-ui/core/Checkbox';
export default function SecondaryActionCheckboxListItem() {
return (
<div style={{ backgroundColor: '#fff', width: 300 }}>
<List>
<ListItem button>
<ListItemText primary="Primary" />
<ListItemSecondaryAction>
<Checkbox />
</ListItemSecondaryAction>
</ListItem>
<ListItem button dense>
<ListItemText primary="Primary" />
<ListItemSecondaryAction>
<Checkbox />
</ListItemSecondaryAction>
</ListItem>
<ListItem button selected>
<ListItemText primary="Primary" />
<ListItemSecondaryAction>
<Checkbox />
</ListItemSecondaryAction>
</ListItem>
</List>
</div>
);
}
|
js/jquery-1.11.0.js | dmleong/wedding-website | /*! jQuery v1.11.0 | (c) 2005, 2014 jQuery Foundation, Inc. | jquery.org/license */
!function(a,b){"object"==typeof module&&"object"==typeof module.exports?module.exports=a.document?b(a,!0):function(a){if(!a.document)throw new Error("jQuery requires a window with a document");return b(a)}:b(a)}("undefined"!=typeof window?window:this,function(a,b){var c=[],d=c.slice,e=c.concat,f=c.push,g=c.indexOf,h={},i=h.toString,j=h.hasOwnProperty,k="".trim,l={},m="1.11.0",n=function(a,b){return new n.fn.init(a,b)},o=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,p=/^-ms-/,q=/-([\da-z])/gi,r=function(a,b){return b.toUpperCase()};n.fn=n.prototype={jquery:m,constructor:n,selector:"",length:0,toArray:function(){return d.call(this)},get:function(a){return null!=a?0>a?this[a+this.length]:this[a]:d.call(this)},pushStack:function(a){var b=n.merge(this.constructor(),a);return b.prevObject=this,b.context=this.context,b},each:function(a,b){return n.each(this,a,b)},map:function(a){return this.pushStack(n.map(this,function(b,c){return a.call(b,c,b)}))},slice:function(){return this.pushStack(d.apply(this,arguments))},first:function(){return this.eq(0)},last:function(){return this.eq(-1)},eq:function(a){var b=this.length,c=+a+(0>a?b:0);return this.pushStack(c>=0&&b>c?[this[c]]:[])},end:function(){return this.prevObject||this.constructor(null)},push:f,sort:c.sort,splice:c.splice},n.extend=n.fn.extend=function(){var a,b,c,d,e,f,g=arguments[0]||{},h=1,i=arguments.length,j=!1;for("boolean"==typeof g&&(j=g,g=arguments[h]||{},h++),"object"==typeof g||n.isFunction(g)||(g={}),h===i&&(g=this,h--);i>h;h++)if(null!=(e=arguments[h]))for(d in e)a=g[d],c=e[d],g!==c&&(j&&c&&(n.isPlainObject(c)||(b=n.isArray(c)))?(b?(b=!1,f=a&&n.isArray(a)?a:[]):f=a&&n.isPlainObject(a)?a:{},g[d]=n.extend(j,f,c)):void 0!==c&&(g[d]=c));return g},n.extend({expando:"jQuery"+(m+Math.random()).replace(/\D/g,""),isReady:!0,error:function(a){throw new Error(a)},noop:function(){},isFunction:function(a){return"function"===n.type(a)},isArray:Array.isArray||function(a){return"array"===n.type(a)},isWindow:function(a){return null!=a&&a==a.window},isNumeric:function(a){return a-parseFloat(a)>=0},isEmptyObject:function(a){var b;for(b in a)return!1;return!0},isPlainObject:function(a){var b;if(!a||"object"!==n.type(a)||a.nodeType||n.isWindow(a))return!1;try{if(a.constructor&&!j.call(a,"constructor")&&!j.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}if(l.ownLast)for(b in a)return j.call(a,b);for(b in a);return void 0===b||j.call(a,b)},type:function(a){return null==a?a+"":"object"==typeof a||"function"==typeof a?h[i.call(a)]||"object":typeof a},globalEval:function(b){b&&n.trim(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(p,"ms-").replace(q,r)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toLowerCase()===b.toLowerCase()},each:function(a,b,c){var d,e=0,f=a.length,g=s(a);if(c){if(g){for(;f>e;e++)if(d=b.apply(a[e],c),d===!1)break}else for(e in a)if(d=b.apply(a[e],c),d===!1)break}else if(g){for(;f>e;e++)if(d=b.call(a[e],e,a[e]),d===!1)break}else for(e in a)if(d=b.call(a[e],e,a[e]),d===!1)break;return a},trim:k&&!k.call("\ufeff\xa0")?function(a){return null==a?"":k.call(a)}:function(a){return null==a?"":(a+"").replace(o,"")},makeArray:function(a,b){var c=b||[];return null!=a&&(s(Object(a))?n.merge(c,"string"==typeof a?[a]:a):f.call(c,a)),c},inArray:function(a,b,c){var d;if(b){if(g)return g.call(b,a,c);for(d=b.length,c=c?0>c?Math.max(0,d+c):c:0;d>c;c++)if(c in b&&b[c]===a)return c}return-1},merge:function(a,b){var c=+b.length,d=0,e=a.length;while(c>d)a[e++]=b[d++];if(c!==c)while(void 0!==b[d])a[e++]=b[d++];return a.length=e,a},grep:function(a,b,c){for(var d,e=[],f=0,g=a.length,h=!c;g>f;f++)d=!b(a[f],f),d!==h&&e.push(a[f]);return e},map:function(a,b,c){var d,f=0,g=a.length,h=s(a),i=[];if(h)for(;g>f;f++)d=b(a[f],f,c),null!=d&&i.push(d);else for(f in a)d=b(a[f],f,c),null!=d&&i.push(d);return e.apply([],i)},guid:1,proxy:function(a,b){var c,e,f;return"string"==typeof b&&(f=a[b],b=a,a=f),n.isFunction(a)?(c=d.call(arguments,2),e=function(){return a.apply(b||this,c.concat(d.call(arguments)))},e.guid=a.guid=a.guid||n.guid++,e):void 0},now:function(){return+new Date},support:l}),n.each("Boolean Number String Function Array Date RegExp Object Error".split(" "),function(a,b){h["[object "+b+"]"]=b.toLowerCase()});function s(a){var b=a.length,c=n.type(a);return"function"===c||n.isWindow(a)?!1:1===a.nodeType&&b?!0:"array"===c||0===b||"number"==typeof b&&b>0&&b-1 in a}var t=function(a){var b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s="sizzle"+-new Date,t=a.document,u=0,v=0,w=eb(),x=eb(),y=eb(),z=function(a,b){return a===b&&(j=!0),0},A="undefined",B=1<<31,C={}.hasOwnProperty,D=[],E=D.pop,F=D.push,G=D.push,H=D.slice,I=D.indexOf||function(a){for(var b=0,c=this.length;c>b;b++)if(this[b]===a)return b;return-1},J="checked|selected|async|autofocus|autoplay|controls|defer|disabled|hidden|ismap|loop|multiple|open|readonly|required|scoped",K="[\\x20\\t\\r\\n\\f]",L="(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+",M=L.replace("w","w#"),N="\\["+K+"*("+L+")"+K+"*(?:([*^$|!~]?=)"+K+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+M+")|)|)"+K+"*\\]",O=":("+L+")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|"+N.replace(3,8)+")*)|.*)\\)|)",P=new RegExp("^"+K+"+|((?:^|[^\\\\])(?:\\\\.)*)"+K+"+$","g"),Q=new RegExp("^"+K+"*,"+K+"*"),R=new RegExp("^"+K+"*([>+~]|"+K+")"+K+"*"),S=new RegExp("="+K+"*([^\\]'\"]*?)"+K+"*\\]","g"),T=new RegExp(O),U=new RegExp("^"+M+"$"),V={ID:new RegExp("^#("+L+")"),CLASS:new RegExp("^\\.("+L+")"),TAG:new RegExp("^("+L.replace("w","w*")+")"),ATTR:new RegExp("^"+N),PSEUDO:new RegExp("^"+O),CHILD:new RegExp("^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\("+K+"*(even|odd|(([+-]|)(\\d*)n|)"+K+"*(?:([+-]|)"+K+"*(\\d+)|))"+K+"*\\)|)","i"),bool:new RegExp("^(?:"+J+")$","i"),needsContext:new RegExp("^"+K+"*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\("+K+"*((?:-\\d)?\\d*)"+K+"*\\)|)(?=[^-]|$)","i")},W=/^(?:input|select|textarea|button)$/i,X=/^h\d$/i,Y=/^[^{]+\{\s*\[native \w/,Z=/^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/,$=/[+~]/,_=/'|\\/g,ab=new RegExp("\\\\([\\da-f]{1,6}"+K+"?|("+K+")|.)","ig"),bb=function(a,b,c){var d="0x"+b-65536;return d!==d||c?b:0>d?String.fromCharCode(d+65536):String.fromCharCode(d>>10|55296,1023&d|56320)};try{G.apply(D=H.call(t.childNodes),t.childNodes),D[t.childNodes.length].nodeType}catch(cb){G={apply:D.length?function(a,b){F.apply(a,H.call(b))}:function(a,b){var c=a.length,d=0;while(a[c++]=b[d++]);a.length=c-1}}}function db(a,b,d,e){var f,g,h,i,j,m,p,q,u,v;if((b?b.ownerDocument||b:t)!==l&&k(b),b=b||l,d=d||[],!a||"string"!=typeof a)return d;if(1!==(i=b.nodeType)&&9!==i)return[];if(n&&!e){if(f=Z.exec(a))if(h=f[1]){if(9===i){if(g=b.getElementById(h),!g||!g.parentNode)return d;if(g.id===h)return d.push(g),d}else if(b.ownerDocument&&(g=b.ownerDocument.getElementById(h))&&r(b,g)&&g.id===h)return d.push(g),d}else{if(f[2])return G.apply(d,b.getElementsByTagName(a)),d;if((h=f[3])&&c.getElementsByClassName&&b.getElementsByClassName)return G.apply(d,b.getElementsByClassName(h)),d}if(c.qsa&&(!o||!o.test(a))){if(q=p=s,u=b,v=9===i&&a,1===i&&"object"!==b.nodeName.toLowerCase()){m=ob(a),(p=b.getAttribute("id"))?q=p.replace(_,"\\$&"):b.setAttribute("id",q),q="[id='"+q+"'] ",j=m.length;while(j--)m[j]=q+pb(m[j]);u=$.test(a)&&mb(b.parentNode)||b,v=m.join(",")}if(v)try{return G.apply(d,u.querySelectorAll(v)),d}catch(w){}finally{p||b.removeAttribute("id")}}}return xb(a.replace(P,"$1"),b,d,e)}function eb(){var a=[];function b(c,e){return a.push(c+" ")>d.cacheLength&&delete b[a.shift()],b[c+" "]=e}return b}function fb(a){return a[s]=!0,a}function gb(a){var b=l.createElement("div");try{return!!a(b)}catch(c){return!1}finally{b.parentNode&&b.parentNode.removeChild(b),b=null}}function hb(a,b){var c=a.split("|"),e=a.length;while(e--)d.attrHandle[c[e]]=b}function ib(a,b){var c=b&&a,d=c&&1===a.nodeType&&1===b.nodeType&&(~b.sourceIndex||B)-(~a.sourceIndex||B);if(d)return d;if(c)while(c=c.nextSibling)if(c===b)return-1;return a?1:-1}function jb(a){return function(b){var c=b.nodeName.toLowerCase();return"input"===c&&b.type===a}}function kb(a){return function(b){var c=b.nodeName.toLowerCase();return("input"===c||"button"===c)&&b.type===a}}function lb(a){return fb(function(b){return b=+b,fb(function(c,d){var e,f=a([],c.length,b),g=f.length;while(g--)c[e=f[g]]&&(c[e]=!(d[e]=c[e]))})})}function mb(a){return a&&typeof a.getElementsByTagName!==A&&a}c=db.support={},f=db.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?"HTML"!==b.nodeName:!1},k=db.setDocument=function(a){var b,e=a?a.ownerDocument||a:t,g=e.defaultView;return e!==l&&9===e.nodeType&&e.documentElement?(l=e,m=e.documentElement,n=!f(e),g&&g!==g.top&&(g.addEventListener?g.addEventListener("unload",function(){k()},!1):g.attachEvent&&g.attachEvent("onunload",function(){k()})),c.attributes=gb(function(a){return a.className="i",!a.getAttribute("className")}),c.getElementsByTagName=gb(function(a){return a.appendChild(e.createComment("")),!a.getElementsByTagName("*").length}),c.getElementsByClassName=Y.test(e.getElementsByClassName)&&gb(function(a){return a.innerHTML="<div class='a'></div><div class='a i'></div>",a.firstChild.className="i",2===a.getElementsByClassName("i").length}),c.getById=gb(function(a){return m.appendChild(a).id=s,!e.getElementsByName||!e.getElementsByName(s).length}),c.getById?(d.find.ID=function(a,b){if(typeof b.getElementById!==A&&n){var c=b.getElementById(a);return c&&c.parentNode?[c]:[]}},d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){return a.getAttribute("id")===b}}):(delete d.find.ID,d.filter.ID=function(a){var b=a.replace(ab,bb);return function(a){var c=typeof a.getAttributeNode!==A&&a.getAttributeNode("id");return c&&c.value===b}}),d.find.TAG=c.getElementsByTagName?function(a,b){return typeof b.getElementsByTagName!==A?b.getElementsByTagName(a):void 0}:function(a,b){var c,d=[],e=0,f=b.getElementsByTagName(a);if("*"===a){while(c=f[e++])1===c.nodeType&&d.push(c);return d}return f},d.find.CLASS=c.getElementsByClassName&&function(a,b){return typeof b.getElementsByClassName!==A&&n?b.getElementsByClassName(a):void 0},p=[],o=[],(c.qsa=Y.test(e.querySelectorAll))&&(gb(function(a){a.innerHTML="<select t=''><option selected=''></option></select>",a.querySelectorAll("[t^='']").length&&o.push("[*^$]="+K+"*(?:''|\"\")"),a.querySelectorAll("[selected]").length||o.push("\\["+K+"*(?:value|"+J+")"),a.querySelectorAll(":checked").length||o.push(":checked")}),gb(function(a){var b=e.createElement("input");b.setAttribute("type","hidden"),a.appendChild(b).setAttribute("name","D"),a.querySelectorAll("[name=d]").length&&o.push("name"+K+"*[*^$|!~]?="),a.querySelectorAll(":enabled").length||o.push(":enabled",":disabled"),a.querySelectorAll("*,:x"),o.push(",.*:")})),(c.matchesSelector=Y.test(q=m.webkitMatchesSelector||m.mozMatchesSelector||m.oMatchesSelector||m.msMatchesSelector))&&gb(function(a){c.disconnectedMatch=q.call(a,"div"),q.call(a,"[s!='']:x"),p.push("!=",O)}),o=o.length&&new RegExp(o.join("|")),p=p.length&&new RegExp(p.join("|")),b=Y.test(m.compareDocumentPosition),r=b||Y.test(m.contains)?function(a,b){var c=9===a.nodeType?a.documentElement:a,d=b&&b.parentNode;return a===d||!(!d||1!==d.nodeType||!(c.contains?c.contains(d):a.compareDocumentPosition&&16&a.compareDocumentPosition(d)))}:function(a,b){if(b)while(b=b.parentNode)if(b===a)return!0;return!1},z=b?function(a,b){if(a===b)return j=!0,0;var d=!a.compareDocumentPosition-!b.compareDocumentPosition;return d?d:(d=(a.ownerDocument||a)===(b.ownerDocument||b)?a.compareDocumentPosition(b):1,1&d||!c.sortDetached&&b.compareDocumentPosition(a)===d?a===e||a.ownerDocument===t&&r(t,a)?-1:b===e||b.ownerDocument===t&&r(t,b)?1:i?I.call(i,a)-I.call(i,b):0:4&d?-1:1)}:function(a,b){if(a===b)return j=!0,0;var c,d=0,f=a.parentNode,g=b.parentNode,h=[a],k=[b];if(!f||!g)return a===e?-1:b===e?1:f?-1:g?1:i?I.call(i,a)-I.call(i,b):0;if(f===g)return ib(a,b);c=a;while(c=c.parentNode)h.unshift(c);c=b;while(c=c.parentNode)k.unshift(c);while(h[d]===k[d])d++;return d?ib(h[d],k[d]):h[d]===t?-1:k[d]===t?1:0},e):l},db.matches=function(a,b){return db(a,null,null,b)},db.matchesSelector=function(a,b){if((a.ownerDocument||a)!==l&&k(a),b=b.replace(S,"='$1']"),!(!c.matchesSelector||!n||p&&p.test(b)||o&&o.test(b)))try{var d=q.call(a,b);if(d||c.disconnectedMatch||a.document&&11!==a.document.nodeType)return d}catch(e){}return db(b,l,null,[a]).length>0},db.contains=function(a,b){return(a.ownerDocument||a)!==l&&k(a),r(a,b)},db.attr=function(a,b){(a.ownerDocument||a)!==l&&k(a);var e=d.attrHandle[b.toLowerCase()],f=e&&C.call(d.attrHandle,b.toLowerCase())?e(a,b,!n):void 0;return void 0!==f?f:c.attributes||!n?a.getAttribute(b):(f=a.getAttributeNode(b))&&f.specified?f.value:null},db.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},db.uniqueSort=function(a){var b,d=[],e=0,f=0;if(j=!c.detectDuplicates,i=!c.sortStable&&a.slice(0),a.sort(z),j){while(b=a[f++])b===a[f]&&(e=d.push(f));while(e--)a.splice(d[e],1)}return i=null,a},e=db.getText=function(a){var b,c="",d=0,f=a.nodeType;if(f){if(1===f||9===f||11===f){if("string"==typeof a.textContent)return a.textContent;for(a=a.firstChild;a;a=a.nextSibling)c+=e(a)}else if(3===f||4===f)return a.nodeValue}else while(b=a[d++])c+=e(b);return c},d=db.selectors={cacheLength:50,createPseudo:fb,match:V,attrHandle:{},find:{},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(ab,bb),a[3]=(a[4]||a[5]||"").replace(ab,bb),"~="===a[2]&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),"nth"===a[1].slice(0,3)?(a[3]||db.error(a[0]),a[4]=+(a[4]?a[5]+(a[6]||1):2*("even"===a[3]||"odd"===a[3])),a[5]=+(a[7]+a[8]||"odd"===a[3])):a[3]&&db.error(a[0]),a},PSEUDO:function(a){var b,c=!a[5]&&a[2];return V.CHILD.test(a[0])?null:(a[3]&&void 0!==a[4]?a[2]=a[4]:c&&T.test(c)&&(b=ob(c,!0))&&(b=c.indexOf(")",c.length-b)-c.length)&&(a[0]=a[0].slice(0,b),a[2]=c.slice(0,b)),a.slice(0,3))}},filter:{TAG:function(a){var b=a.replace(ab,bb).toLowerCase();return"*"===a?function(){return!0}:function(a){return a.nodeName&&a.nodeName.toLowerCase()===b}},CLASS:function(a){var b=w[a+" "];return b||(b=new RegExp("(^|"+K+")"+a+"("+K+"|$)"))&&w(a,function(a){return b.test("string"==typeof a.className&&a.className||typeof a.getAttribute!==A&&a.getAttribute("class")||"")})},ATTR:function(a,b,c){return function(d){var e=db.attr(d,a);return null==e?"!="===b:b?(e+="","="===b?e===c:"!="===b?e!==c:"^="===b?c&&0===e.indexOf(c):"*="===b?c&&e.indexOf(c)>-1:"$="===b?c&&e.slice(-c.length)===c:"~="===b?(" "+e+" ").indexOf(c)>-1:"|="===b?e===c||e.slice(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d,e){var f="nth"!==a.slice(0,3),g="last"!==a.slice(-4),h="of-type"===b;return 1===d&&0===e?function(a){return!!a.parentNode}:function(b,c,i){var j,k,l,m,n,o,p=f!==g?"nextSibling":"previousSibling",q=b.parentNode,r=h&&b.nodeName.toLowerCase(),t=!i&&!h;if(q){if(f){while(p){l=b;while(l=l[p])if(h?l.nodeName.toLowerCase()===r:1===l.nodeType)return!1;o=p="only"===a&&!o&&"nextSibling"}return!0}if(o=[g?q.firstChild:q.lastChild],g&&t){k=q[s]||(q[s]={}),j=k[a]||[],n=j[0]===u&&j[1],m=j[0]===u&&j[2],l=n&&q.childNodes[n];while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if(1===l.nodeType&&++m&&l===b){k[a]=[u,n,m];break}}else if(t&&(j=(b[s]||(b[s]={}))[a])&&j[0]===u)m=j[1];else while(l=++n&&l&&l[p]||(m=n=0)||o.pop())if((h?l.nodeName.toLowerCase()===r:1===l.nodeType)&&++m&&(t&&((l[s]||(l[s]={}))[a]=[u,m]),l===b))break;return m-=e,m===d||m%d===0&&m/d>=0}}},PSEUDO:function(a,b){var c,e=d.pseudos[a]||d.setFilters[a.toLowerCase()]||db.error("unsupported pseudo: "+a);return e[s]?e(b):e.length>1?(c=[a,a,"",b],d.setFilters.hasOwnProperty(a.toLowerCase())?fb(function(a,c){var d,f=e(a,b),g=f.length;while(g--)d=I.call(a,f[g]),a[d]=!(c[d]=f[g])}):function(a){return e(a,0,c)}):e}},pseudos:{not:fb(function(a){var b=[],c=[],d=g(a.replace(P,"$1"));return d[s]?fb(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)(f=g[h])&&(a[h]=!(b[h]=f))}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:fb(function(a){return function(b){return db(a,b).length>0}}),contains:fb(function(a){return function(b){return(b.textContent||b.innerText||e(b)).indexOf(a)>-1}}),lang:fb(function(a){return U.test(a||"")||db.error("unsupported lang: "+a),a=a.replace(ab,bb).toLowerCase(),function(b){var c;do if(c=n?b.lang:b.getAttribute("xml:lang")||b.getAttribute("lang"))return c=c.toLowerCase(),c===a||0===c.indexOf(a+"-");while((b=b.parentNode)&&1===b.nodeType);return!1}}),target:function(b){var c=a.location&&a.location.hash;return c&&c.slice(1)===b.id},root:function(a){return a===m},focus:function(a){return a===l.activeElement&&(!l.hasFocus||l.hasFocus())&&!!(a.type||a.href||~a.tabIndex)},enabled:function(a){return a.disabled===!1},disabled:function(a){return a.disabled===!0},checked:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&!!a.checked||"option"===b&&!!a.selected},selected:function(a){return a.parentNode&&a.parentNode.selectedIndex,a.selected===!0},empty:function(a){for(a=a.firstChild;a;a=a.nextSibling)if(a.nodeType<6)return!1;return!0},parent:function(a){return!d.pseudos.empty(a)},header:function(a){return X.test(a.nodeName)},input:function(a){return W.test(a.nodeName)},button:function(a){var b=a.nodeName.toLowerCase();return"input"===b&&"button"===a.type||"button"===b},text:function(a){var b;return"input"===a.nodeName.toLowerCase()&&"text"===a.type&&(null==(b=a.getAttribute("type"))||"text"===b.toLowerCase())},first:lb(function(){return[0]}),last:lb(function(a,b){return[b-1]}),eq:lb(function(a,b,c){return[0>c?c+b:c]}),even:lb(function(a,b){for(var c=0;b>c;c+=2)a.push(c);return a}),odd:lb(function(a,b){for(var c=1;b>c;c+=2)a.push(c);return a}),lt:lb(function(a,b,c){for(var d=0>c?c+b:c;--d>=0;)a.push(d);return a}),gt:lb(function(a,b,c){for(var d=0>c?c+b:c;++d<b;)a.push(d);return a})}},d.pseudos.nth=d.pseudos.eq;for(b in{radio:!0,checkbox:!0,file:!0,password:!0,image:!0})d.pseudos[b]=jb(b);for(b in{submit:!0,reset:!0})d.pseudos[b]=kb(b);function nb(){}nb.prototype=d.filters=d.pseudos,d.setFilters=new nb;function ob(a,b){var c,e,f,g,h,i,j,k=x[a+" "];if(k)return b?0:k.slice(0);h=a,i=[],j=d.preFilter;while(h){(!c||(e=Q.exec(h)))&&(e&&(h=h.slice(e[0].length)||h),i.push(f=[])),c=!1,(e=R.exec(h))&&(c=e.shift(),f.push({value:c,type:e[0].replace(P," ")}),h=h.slice(c.length));for(g in d.filter)!(e=V[g].exec(h))||j[g]&&!(e=j[g](e))||(c=e.shift(),f.push({value:c,type:g,matches:e}),h=h.slice(c.length));if(!c)break}return b?h.length:h?db.error(a):x(a,i).slice(0)}function pb(a){for(var b=0,c=a.length,d="";c>b;b++)d+=a[b].value;return d}function qb(a,b,c){var d=b.dir,e=c&&"parentNode"===d,f=v++;return b.first?function(b,c,f){while(b=b[d])if(1===b.nodeType||e)return a(b,c,f)}:function(b,c,g){var h,i,j=[u,f];if(g){while(b=b[d])if((1===b.nodeType||e)&&a(b,c,g))return!0}else while(b=b[d])if(1===b.nodeType||e){if(i=b[s]||(b[s]={}),(h=i[d])&&h[0]===u&&h[1]===f)return j[2]=h[2];if(i[d]=j,j[2]=a(b,c,g))return!0}}}function rb(a){return a.length>1?function(b,c,d){var e=a.length;while(e--)if(!a[e](b,c,d))return!1;return!0}:a[0]}function sb(a,b,c,d,e){for(var f,g=[],h=0,i=a.length,j=null!=b;i>h;h++)(f=a[h])&&(!c||c(f,d,e))&&(g.push(f),j&&b.push(h));return g}function tb(a,b,c,d,e,f){return d&&!d[s]&&(d=tb(d)),e&&!e[s]&&(e=tb(e,f)),fb(function(f,g,h,i){var j,k,l,m=[],n=[],o=g.length,p=f||wb(b||"*",h.nodeType?[h]:h,[]),q=!a||!f&&b?p:sb(p,m,a,h,i),r=c?e||(f?a:o||d)?[]:g:q;if(c&&c(q,r,h,i),d){j=sb(r,n),d(j,[],h,i),k=j.length;while(k--)(l=j[k])&&(r[n[k]]=!(q[n[k]]=l))}if(f){if(e||a){if(e){j=[],k=r.length;while(k--)(l=r[k])&&j.push(q[k]=l);e(null,r=[],j,i)}k=r.length;while(k--)(l=r[k])&&(j=e?I.call(f,l):m[k])>-1&&(f[j]=!(g[j]=l))}}else r=sb(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):G.apply(g,r)})}function ub(a){for(var b,c,e,f=a.length,g=d.relative[a[0].type],i=g||d.relative[" "],j=g?1:0,k=qb(function(a){return a===b},i,!0),l=qb(function(a){return I.call(b,a)>-1},i,!0),m=[function(a,c,d){return!g&&(d||c!==h)||((b=c).nodeType?k(a,c,d):l(a,c,d))}];f>j;j++)if(c=d.relative[a[j].type])m=[qb(rb(m),c)];else{if(c=d.filter[a[j].type].apply(null,a[j].matches),c[s]){for(e=++j;f>e;e++)if(d.relative[a[e].type])break;return tb(j>1&&rb(m),j>1&&pb(a.slice(0,j-1).concat({value:" "===a[j-2].type?"*":""})).replace(P,"$1"),c,e>j&&ub(a.slice(j,e)),f>e&&ub(a=a.slice(e)),f>e&&pb(a))}m.push(c)}return rb(m)}function vb(a,b){var c=b.length>0,e=a.length>0,f=function(f,g,i,j,k){var m,n,o,p=0,q="0",r=f&&[],s=[],t=h,v=f||e&&d.find.TAG("*",k),w=u+=null==t?1:Math.random()||.1,x=v.length;for(k&&(h=g!==l&&g);q!==x&&null!=(m=v[q]);q++){if(e&&m){n=0;while(o=a[n++])if(o(m,g,i)){j.push(m);break}k&&(u=w)}c&&((m=!o&&m)&&p--,f&&r.push(m))}if(p+=q,c&&q!==p){n=0;while(o=b[n++])o(r,s,g,i);if(f){if(p>0)while(q--)r[q]||s[q]||(s[q]=E.call(j));s=sb(s)}G.apply(j,s),k&&!f&&s.length>0&&p+b.length>1&&db.uniqueSort(j)}return k&&(u=w,h=t),r};return c?fb(f):f}g=db.compile=function(a,b){var c,d=[],e=[],f=y[a+" "];if(!f){b||(b=ob(a)),c=b.length;while(c--)f=ub(b[c]),f[s]?d.push(f):e.push(f);f=y(a,vb(e,d))}return f};function wb(a,b,c){for(var d=0,e=b.length;e>d;d++)db(a,b[d],c);return c}function xb(a,b,e,f){var h,i,j,k,l,m=ob(a);if(!f&&1===m.length){if(i=m[0]=m[0].slice(0),i.length>2&&"ID"===(j=i[0]).type&&c.getById&&9===b.nodeType&&n&&d.relative[i[1].type]){if(b=(d.find.ID(j.matches[0].replace(ab,bb),b)||[])[0],!b)return e;a=a.slice(i.shift().value.length)}h=V.needsContext.test(a)?0:i.length;while(h--){if(j=i[h],d.relative[k=j.type])break;if((l=d.find[k])&&(f=l(j.matches[0].replace(ab,bb),$.test(i[0].type)&&mb(b.parentNode)||b))){if(i.splice(h,1),a=f.length&&pb(i),!a)return G.apply(e,f),e;break}}}return g(a,m)(f,b,!n,e,$.test(a)&&mb(b.parentNode)||b),e}return c.sortStable=s.split("").sort(z).join("")===s,c.detectDuplicates=!!j,k(),c.sortDetached=gb(function(a){return 1&a.compareDocumentPosition(l.createElement("div"))}),gb(function(a){return a.innerHTML="<a href='#'></a>","#"===a.firstChild.getAttribute("href")})||hb("type|href|height|width",function(a,b,c){return c?void 0:a.getAttribute(b,"type"===b.toLowerCase()?1:2)}),c.attributes&&gb(function(a){return a.innerHTML="<input/>",a.firstChild.setAttribute("value",""),""===a.firstChild.getAttribute("value")})||hb("value",function(a,b,c){return c||"input"!==a.nodeName.toLowerCase()?void 0:a.defaultValue}),gb(function(a){return null==a.getAttribute("disabled")})||hb(J,function(a,b,c){var d;return c?void 0:a[b]===!0?b.toLowerCase():(d=a.getAttributeNode(b))&&d.specified?d.value:null}),db}(a);n.find=t,n.expr=t.selectors,n.expr[":"]=n.expr.pseudos,n.unique=t.uniqueSort,n.text=t.getText,n.isXMLDoc=t.isXML,n.contains=t.contains;var u=n.expr.match.needsContext,v=/^<(\w+)\s*\/?>(?:<\/\1>|)$/,w=/^.[^:#\[\.,]*$/;function x(a,b,c){if(n.isFunction(b))return n.grep(a,function(a,d){return!!b.call(a,d,a)!==c});if(b.nodeType)return n.grep(a,function(a){return a===b!==c});if("string"==typeof b){if(w.test(b))return n.filter(b,a,c);b=n.filter(b,a)}return n.grep(a,function(a){return n.inArray(a,b)>=0!==c})}n.filter=function(a,b,c){var d=b[0];return c&&(a=":not("+a+")"),1===b.length&&1===d.nodeType?n.find.matchesSelector(d,a)?[d]:[]:n.find.matches(a,n.grep(b,function(a){return 1===a.nodeType}))},n.fn.extend({find:function(a){var b,c=[],d=this,e=d.length;if("string"!=typeof a)return this.pushStack(n(a).filter(function(){for(b=0;e>b;b++)if(n.contains(d[b],this))return!0}));for(b=0;e>b;b++)n.find(a,d[b],c);return c=this.pushStack(e>1?n.unique(c):c),c.selector=this.selector?this.selector+" "+a:a,c},filter:function(a){return this.pushStack(x(this,a||[],!1))},not:function(a){return this.pushStack(x(this,a||[],!0))},is:function(a){return!!x(this,"string"==typeof a&&u.test(a)?n(a):a||[],!1).length}});var y,z=a.document,A=/^(?:\s*(<[\w\W]+>)[^>]*|#([\w-]*))$/,B=n.fn.init=function(a,b){var c,d;if(!a)return this;if("string"==typeof a){if(c="<"===a.charAt(0)&&">"===a.charAt(a.length-1)&&a.length>=3?[null,a,null]:A.exec(a),!c||!c[1]&&b)return!b||b.jquery?(b||y).find(a):this.constructor(b).find(a);if(c[1]){if(b=b instanceof n?b[0]:b,n.merge(this,n.parseHTML(c[1],b&&b.nodeType?b.ownerDocument||b:z,!0)),v.test(c[1])&&n.isPlainObject(b))for(c in b)n.isFunction(this[c])?this[c](b[c]):this.attr(c,b[c]);return this}if(d=z.getElementById(c[2]),d&&d.parentNode){if(d.id!==c[2])return y.find(a);this.length=1,this[0]=d}return this.context=z,this.selector=a,this}return a.nodeType?(this.context=this[0]=a,this.length=1,this):n.isFunction(a)?"undefined"!=typeof y.ready?y.ready(a):a(n):(void 0!==a.selector&&(this.selector=a.selector,this.context=a.context),n.makeArray(a,this))};B.prototype=n.fn,y=n(z);var C=/^(?:parents|prev(?:Until|All))/,D={children:!0,contents:!0,next:!0,prev:!0};n.extend({dir:function(a,b,c){var d=[],e=a[b];while(e&&9!==e.nodeType&&(void 0===c||1!==e.nodeType||!n(e).is(c)))1===e.nodeType&&d.push(e),e=e[b];return d},sibling:function(a,b){for(var c=[];a;a=a.nextSibling)1===a.nodeType&&a!==b&&c.push(a);return c}}),n.fn.extend({has:function(a){var b,c=n(a,this),d=c.length;return this.filter(function(){for(b=0;d>b;b++)if(n.contains(this,c[b]))return!0})},closest:function(a,b){for(var c,d=0,e=this.length,f=[],g=u.test(a)||"string"!=typeof a?n(a,b||this.context):0;e>d;d++)for(c=this[d];c&&c!==b;c=c.parentNode)if(c.nodeType<11&&(g?g.index(c)>-1:1===c.nodeType&&n.find.matchesSelector(c,a))){f.push(c);break}return this.pushStack(f.length>1?n.unique(f):f)},index:function(a){return a?"string"==typeof a?n.inArray(this[0],n(a)):n.inArray(a.jquery?a[0]:a,this):this[0]&&this[0].parentNode?this.first().prevAll().length:-1},add:function(a,b){return this.pushStack(n.unique(n.merge(this.get(),n(a,b))))},addBack:function(a){return this.add(null==a?this.prevObject:this.prevObject.filter(a))}});function E(a,b){do a=a[b];while(a&&1!==a.nodeType);return a}n.each({parent:function(a){var b=a.parentNode;return b&&11!==b.nodeType?b:null},parents:function(a){return n.dir(a,"parentNode")},parentsUntil:function(a,b,c){return n.dir(a,"parentNode",c)},next:function(a){return E(a,"nextSibling")},prev:function(a){return E(a,"previousSibling")},nextAll:function(a){return n.dir(a,"nextSibling")},prevAll:function(a){return n.dir(a,"previousSibling")},nextUntil:function(a,b,c){return n.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return n.dir(a,"previousSibling",c)},siblings:function(a){return n.sibling((a.parentNode||{}).firstChild,a)},children:function(a){return n.sibling(a.firstChild)},contents:function(a){return n.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:n.merge([],a.childNodes)}},function(a,b){n.fn[a]=function(c,d){var e=n.map(this,b,c);return"Until"!==a.slice(-5)&&(d=c),d&&"string"==typeof d&&(e=n.filter(d,e)),this.length>1&&(D[a]||(e=n.unique(e)),C.test(a)&&(e=e.reverse())),this.pushStack(e)}});var F=/\S+/g,G={};function H(a){var b=G[a]={};return n.each(a.match(F)||[],function(a,c){b[c]=!0}),b}n.Callbacks=function(a){a="string"==typeof a?G[a]||H(a):n.extend({},a);var b,c,d,e,f,g,h=[],i=!a.once&&[],j=function(l){for(c=a.memory&&l,d=!0,f=g||0,g=0,e=h.length,b=!0;h&&e>f;f++)if(h[f].apply(l[0],l[1])===!1&&a.stopOnFalse){c=!1;break}b=!1,h&&(i?i.length&&j(i.shift()):c?h=[]:k.disable())},k={add:function(){if(h){var d=h.length;!function f(b){n.each(b,function(b,c){var d=n.type(c);"function"===d?a.unique&&k.has(c)||h.push(c):c&&c.length&&"string"!==d&&f(c)})}(arguments),b?e=h.length:c&&(g=d,j(c))}return this},remove:function(){return h&&n.each(arguments,function(a,c){var d;while((d=n.inArray(c,h,d))>-1)h.splice(d,1),b&&(e>=d&&e--,f>=d&&f--)}),this},has:function(a){return a?n.inArray(a,h)>-1:!(!h||!h.length)},empty:function(){return h=[],e=0,this},disable:function(){return h=i=c=void 0,this},disabled:function(){return!h},lock:function(){return i=void 0,c||k.disable(),this},locked:function(){return!i},fireWith:function(a,c){return!h||d&&!i||(c=c||[],c=[a,c.slice?c.slice():c],b?i.push(c):j(c)),this},fire:function(){return k.fireWith(this,arguments),this},fired:function(){return!!d}};return k},n.extend({Deferred:function(a){var b=[["resolve","done",n.Callbacks("once memory"),"resolved"],["reject","fail",n.Callbacks("once memory"),"rejected"],["notify","progress",n.Callbacks("memory")]],c="pending",d={state:function(){return c},always:function(){return e.done(arguments).fail(arguments),this},then:function(){var a=arguments;return n.Deferred(function(c){n.each(b,function(b,f){var g=n.isFunction(a[b])&&a[b];e[f[1]](function(){var a=g&&g.apply(this,arguments);a&&n.isFunction(a.promise)?a.promise().done(c.resolve).fail(c.reject).progress(c.notify):c[f[0]+"With"](this===d?c.promise():this,g?[a]:arguments)})}),a=null}).promise()},promise:function(a){return null!=a?n.extend(a,d):d}},e={};return d.pipe=d.then,n.each(b,function(a,f){var g=f[2],h=f[3];d[f[1]]=g.add,h&&g.add(function(){c=h},b[1^a][2].disable,b[2][2].lock),e[f[0]]=function(){return e[f[0]+"With"](this===e?d:this,arguments),this},e[f[0]+"With"]=g.fireWith}),d.promise(e),a&&a.call(e,e),e},when:function(a){var b=0,c=d.call(arguments),e=c.length,f=1!==e||a&&n.isFunction(a.promise)?e:0,g=1===f?a:n.Deferred(),h=function(a,b,c){return function(e){b[a]=this,c[a]=arguments.length>1?d.call(arguments):e,c===i?g.notifyWith(b,c):--f||g.resolveWith(b,c)}},i,j,k;if(e>1)for(i=new Array(e),j=new Array(e),k=new Array(e);e>b;b++)c[b]&&n.isFunction(c[b].promise)?c[b].promise().done(h(b,k,c)).fail(g.reject).progress(h(b,j,i)):--f;return f||g.resolveWith(k,c),g.promise()}});var I;n.fn.ready=function(a){return n.ready.promise().done(a),this},n.extend({isReady:!1,readyWait:1,holdReady:function(a){a?n.readyWait++:n.ready(!0)},ready:function(a){if(a===!0?!--n.readyWait:!n.isReady){if(!z.body)return setTimeout(n.ready);n.isReady=!0,a!==!0&&--n.readyWait>0||(I.resolveWith(z,[n]),n.fn.trigger&&n(z).trigger("ready").off("ready"))}}});function J(){z.addEventListener?(z.removeEventListener("DOMContentLoaded",K,!1),a.removeEventListener("load",K,!1)):(z.detachEvent("onreadystatechange",K),a.detachEvent("onload",K))}function K(){(z.addEventListener||"load"===event.type||"complete"===z.readyState)&&(J(),n.ready())}n.ready.promise=function(b){if(!I)if(I=n.Deferred(),"complete"===z.readyState)setTimeout(n.ready);else if(z.addEventListener)z.addEventListener("DOMContentLoaded",K,!1),a.addEventListener("load",K,!1);else{z.attachEvent("onreadystatechange",K),a.attachEvent("onload",K);var c=!1;try{c=null==a.frameElement&&z.documentElement}catch(d){}c&&c.doScroll&&!function e(){if(!n.isReady){try{c.doScroll("left")}catch(a){return setTimeout(e,50)}J(),n.ready()}}()}return I.promise(b)};var L="undefined",M;for(M in n(l))break;l.ownLast="0"!==M,l.inlineBlockNeedsLayout=!1,n(function(){var a,b,c=z.getElementsByTagName("body")[0];c&&(a=z.createElement("div"),a.style.cssText="border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px",b=z.createElement("div"),c.appendChild(a).appendChild(b),typeof b.style.zoom!==L&&(b.style.cssText="border:0;margin:0;width:1px;padding:1px;display:inline;zoom:1",(l.inlineBlockNeedsLayout=3===b.offsetWidth)&&(c.style.zoom=1)),c.removeChild(a),a=b=null)}),function(){var a=z.createElement("div");if(null==l.deleteExpando){l.deleteExpando=!0;try{delete a.test}catch(b){l.deleteExpando=!1}}a=null}(),n.acceptData=function(a){var b=n.noData[(a.nodeName+" ").toLowerCase()],c=+a.nodeType||1;return 1!==c&&9!==c?!1:!b||b!==!0&&a.getAttribute("classid")===b};var N=/^(?:\{[\w\W]*\}|\[[\w\W]*\])$/,O=/([A-Z])/g;function P(a,b,c){if(void 0===c&&1===a.nodeType){var d="data-"+b.replace(O,"-$1").toLowerCase();if(c=a.getAttribute(d),"string"==typeof c){try{c="true"===c?!0:"false"===c?!1:"null"===c?null:+c+""===c?+c:N.test(c)?n.parseJSON(c):c}catch(e){}n.data(a,b,c)}else c=void 0}return c}function Q(a){var b;for(b in a)if(("data"!==b||!n.isEmptyObject(a[b]))&&"toJSON"!==b)return!1;return!0}function R(a,b,d,e){if(n.acceptData(a)){var f,g,h=n.expando,i=a.nodeType,j=i?n.cache:a,k=i?a[h]:a[h]&&h;if(k&&j[k]&&(e||j[k].data)||void 0!==d||"string"!=typeof b)return k||(k=i?a[h]=c.pop()||n.guid++:h),j[k]||(j[k]=i?{}:{toJSON:n.noop}),("object"==typeof b||"function"==typeof b)&&(e?j[k]=n.extend(j[k],b):j[k].data=n.extend(j[k].data,b)),g=j[k],e||(g.data||(g.data={}),g=g.data),void 0!==d&&(g[n.camelCase(b)]=d),"string"==typeof b?(f=g[b],null==f&&(f=g[n.camelCase(b)])):f=g,f
}}function S(a,b,c){if(n.acceptData(a)){var d,e,f=a.nodeType,g=f?n.cache:a,h=f?a[n.expando]:n.expando;if(g[h]){if(b&&(d=c?g[h]:g[h].data)){n.isArray(b)?b=b.concat(n.map(b,n.camelCase)):b in d?b=[b]:(b=n.camelCase(b),b=b in d?[b]:b.split(" ")),e=b.length;while(e--)delete d[b[e]];if(c?!Q(d):!n.isEmptyObject(d))return}(c||(delete g[h].data,Q(g[h])))&&(f?n.cleanData([a],!0):l.deleteExpando||g!=g.window?delete g[h]:g[h]=null)}}}n.extend({cache:{},noData:{"applet ":!0,"embed ":!0,"object ":"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000"},hasData:function(a){return a=a.nodeType?n.cache[a[n.expando]]:a[n.expando],!!a&&!Q(a)},data:function(a,b,c){return R(a,b,c)},removeData:function(a,b){return S(a,b)},_data:function(a,b,c){return R(a,b,c,!0)},_removeData:function(a,b){return S(a,b,!0)}}),n.fn.extend({data:function(a,b){var c,d,e,f=this[0],g=f&&f.attributes;if(void 0===a){if(this.length&&(e=n.data(f),1===f.nodeType&&!n._data(f,"parsedAttrs"))){c=g.length;while(c--)d=g[c].name,0===d.indexOf("data-")&&(d=n.camelCase(d.slice(5)),P(f,d,e[d]));n._data(f,"parsedAttrs",!0)}return e}return"object"==typeof a?this.each(function(){n.data(this,a)}):arguments.length>1?this.each(function(){n.data(this,a,b)}):f?P(f,a,n.data(f,a)):void 0},removeData:function(a){return this.each(function(){n.removeData(this,a)})}}),n.extend({queue:function(a,b,c){var d;return a?(b=(b||"fx")+"queue",d=n._data(a,b),c&&(!d||n.isArray(c)?d=n._data(a,b,n.makeArray(c)):d.push(c)),d||[]):void 0},dequeue:function(a,b){b=b||"fx";var c=n.queue(a,b),d=c.length,e=c.shift(),f=n._queueHooks(a,b),g=function(){n.dequeue(a,b)};"inprogress"===e&&(e=c.shift(),d--),e&&("fx"===b&&c.unshift("inprogress"),delete f.stop,e.call(a,g,f)),!d&&f&&f.empty.fire()},_queueHooks:function(a,b){var c=b+"queueHooks";return n._data(a,c)||n._data(a,c,{empty:n.Callbacks("once memory").add(function(){n._removeData(a,b+"queue"),n._removeData(a,c)})})}}),n.fn.extend({queue:function(a,b){var c=2;return"string"!=typeof a&&(b=a,a="fx",c--),arguments.length<c?n.queue(this[0],a):void 0===b?this:this.each(function(){var c=n.queue(this,a,b);n._queueHooks(this,a),"fx"===a&&"inprogress"!==c[0]&&n.dequeue(this,a)})},dequeue:function(a){return this.each(function(){n.dequeue(this,a)})},clearQueue:function(a){return this.queue(a||"fx",[])},promise:function(a,b){var c,d=1,e=n.Deferred(),f=this,g=this.length,h=function(){--d||e.resolveWith(f,[f])};"string"!=typeof a&&(b=a,a=void 0),a=a||"fx";while(g--)c=n._data(f[g],a+"queueHooks"),c&&c.empty&&(d++,c.empty.add(h));return h(),e.promise(b)}});var T=/[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source,U=["Top","Right","Bottom","Left"],V=function(a,b){return a=b||a,"none"===n.css(a,"display")||!n.contains(a.ownerDocument,a)},W=n.access=function(a,b,c,d,e,f,g){var h=0,i=a.length,j=null==c;if("object"===n.type(c)){e=!0;for(h in c)n.access(a,b,h,c[h],!0,f,g)}else if(void 0!==d&&(e=!0,n.isFunction(d)||(g=!0),j&&(g?(b.call(a,d),b=null):(j=b,b=function(a,b,c){return j.call(n(a),c)})),b))for(;i>h;h++)b(a[h],c,g?d:d.call(a[h],h,b(a[h],c)));return e?a:j?b.call(a):i?b(a[0],c):f},X=/^(?:checkbox|radio)$/i;!function(){var a=z.createDocumentFragment(),b=z.createElement("div"),c=z.createElement("input");if(b.setAttribute("className","t"),b.innerHTML=" <link/><table></table><a href='/a'>a</a>",l.leadingWhitespace=3===b.firstChild.nodeType,l.tbody=!b.getElementsByTagName("tbody").length,l.htmlSerialize=!!b.getElementsByTagName("link").length,l.html5Clone="<:nav></:nav>"!==z.createElement("nav").cloneNode(!0).outerHTML,c.type="checkbox",c.checked=!0,a.appendChild(c),l.appendChecked=c.checked,b.innerHTML="<textarea>x</textarea>",l.noCloneChecked=!!b.cloneNode(!0).lastChild.defaultValue,a.appendChild(b),b.innerHTML="<input type='radio' checked='checked' name='t'/>",l.checkClone=b.cloneNode(!0).cloneNode(!0).lastChild.checked,l.noCloneEvent=!0,b.attachEvent&&(b.attachEvent("onclick",function(){l.noCloneEvent=!1}),b.cloneNode(!0).click()),null==l.deleteExpando){l.deleteExpando=!0;try{delete b.test}catch(d){l.deleteExpando=!1}}a=b=c=null}(),function(){var b,c,d=z.createElement("div");for(b in{submit:!0,change:!0,focusin:!0})c="on"+b,(l[b+"Bubbles"]=c in a)||(d.setAttribute(c,"t"),l[b+"Bubbles"]=d.attributes[c].expando===!1);d=null}();var Y=/^(?:input|select|textarea)$/i,Z=/^key/,$=/^(?:mouse|contextmenu)|click/,_=/^(?:focusinfocus|focusoutblur)$/,ab=/^([^.]*)(?:\.(.+)|)$/;function bb(){return!0}function cb(){return!1}function db(){try{return z.activeElement}catch(a){}}n.event={global:{},add:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n._data(a);if(r){c.handler&&(i=c,c=i.handler,e=i.selector),c.guid||(c.guid=n.guid++),(g=r.events)||(g=r.events={}),(k=r.handle)||(k=r.handle=function(a){return typeof n===L||a&&n.event.triggered===a.type?void 0:n.event.dispatch.apply(k.elem,arguments)},k.elem=a),b=(b||"").match(F)||[""],h=b.length;while(h--)f=ab.exec(b[h])||[],o=q=f[1],p=(f[2]||"").split(".").sort(),o&&(j=n.event.special[o]||{},o=(e?j.delegateType:j.bindType)||o,j=n.event.special[o]||{},l=n.extend({type:o,origType:q,data:d,handler:c,guid:c.guid,selector:e,needsContext:e&&n.expr.match.needsContext.test(e),namespace:p.join(".")},i),(m=g[o])||(m=g[o]=[],m.delegateCount=0,j.setup&&j.setup.call(a,d,p,k)!==!1||(a.addEventListener?a.addEventListener(o,k,!1):a.attachEvent&&a.attachEvent("on"+o,k))),j.add&&(j.add.call(a,l),l.handler.guid||(l.handler.guid=c.guid)),e?m.splice(m.delegateCount++,0,l):m.push(l),n.event.global[o]=!0);a=null}},remove:function(a,b,c,d,e){var f,g,h,i,j,k,l,m,o,p,q,r=n.hasData(a)&&n._data(a);if(r&&(k=r.events)){b=(b||"").match(F)||[""],j=b.length;while(j--)if(h=ab.exec(b[j])||[],o=q=h[1],p=(h[2]||"").split(".").sort(),o){l=n.event.special[o]||{},o=(d?l.delegateType:l.bindType)||o,m=k[o]||[],h=h[2]&&new RegExp("(^|\\.)"+p.join("\\.(?:.*\\.|)")+"(\\.|$)"),i=f=m.length;while(f--)g=m[f],!e&&q!==g.origType||c&&c.guid!==g.guid||h&&!h.test(g.namespace)||d&&d!==g.selector&&("**"!==d||!g.selector)||(m.splice(f,1),g.selector&&m.delegateCount--,l.remove&&l.remove.call(a,g));i&&!m.length&&(l.teardown&&l.teardown.call(a,p,r.handle)!==!1||n.removeEvent(a,o,r.handle),delete k[o])}else for(o in k)n.event.remove(a,o+b[j],c,d,!0);n.isEmptyObject(k)&&(delete r.handle,n._removeData(a,"events"))}},trigger:function(b,c,d,e){var f,g,h,i,k,l,m,o=[d||z],p=j.call(b,"type")?b.type:b,q=j.call(b,"namespace")?b.namespace.split("."):[];if(h=l=d=d||z,3!==d.nodeType&&8!==d.nodeType&&!_.test(p+n.event.triggered)&&(p.indexOf(".")>=0&&(q=p.split("."),p=q.shift(),q.sort()),g=p.indexOf(":")<0&&"on"+p,b=b[n.expando]?b:new n.Event(p,"object"==typeof b&&b),b.isTrigger=e?2:3,b.namespace=q.join("."),b.namespace_re=b.namespace?new RegExp("(^|\\.)"+q.join("\\.(?:.*\\.|)")+"(\\.|$)"):null,b.result=void 0,b.target||(b.target=d),c=null==c?[b]:n.makeArray(c,[b]),k=n.event.special[p]||{},e||!k.trigger||k.trigger.apply(d,c)!==!1)){if(!e&&!k.noBubble&&!n.isWindow(d)){for(i=k.delegateType||p,_.test(i+p)||(h=h.parentNode);h;h=h.parentNode)o.push(h),l=h;l===(d.ownerDocument||z)&&o.push(l.defaultView||l.parentWindow||a)}m=0;while((h=o[m++])&&!b.isPropagationStopped())b.type=m>1?i:k.bindType||p,f=(n._data(h,"events")||{})[b.type]&&n._data(h,"handle"),f&&f.apply(h,c),f=g&&h[g],f&&f.apply&&n.acceptData(h)&&(b.result=f.apply(h,c),b.result===!1&&b.preventDefault());if(b.type=p,!e&&!b.isDefaultPrevented()&&(!k._default||k._default.apply(o.pop(),c)===!1)&&n.acceptData(d)&&g&&d[p]&&!n.isWindow(d)){l=d[g],l&&(d[g]=null),n.event.triggered=p;try{d[p]()}catch(r){}n.event.triggered=void 0,l&&(d[g]=l)}return b.result}},dispatch:function(a){a=n.event.fix(a);var b,c,e,f,g,h=[],i=d.call(arguments),j=(n._data(this,"events")||{})[a.type]||[],k=n.event.special[a.type]||{};if(i[0]=a,a.delegateTarget=this,!k.preDispatch||k.preDispatch.call(this,a)!==!1){h=n.event.handlers.call(this,a,j),b=0;while((f=h[b++])&&!a.isPropagationStopped()){a.currentTarget=f.elem,g=0;while((e=f.handlers[g++])&&!a.isImmediatePropagationStopped())(!a.namespace_re||a.namespace_re.test(e.namespace))&&(a.handleObj=e,a.data=e.data,c=((n.event.special[e.origType]||{}).handle||e.handler).apply(f.elem,i),void 0!==c&&(a.result=c)===!1&&(a.preventDefault(),a.stopPropagation()))}return k.postDispatch&&k.postDispatch.call(this,a),a.result}},handlers:function(a,b){var c,d,e,f,g=[],h=b.delegateCount,i=a.target;if(h&&i.nodeType&&(!a.button||"click"!==a.type))for(;i!=this;i=i.parentNode||this)if(1===i.nodeType&&(i.disabled!==!0||"click"!==a.type)){for(e=[],f=0;h>f;f++)d=b[f],c=d.selector+" ",void 0===e[c]&&(e[c]=d.needsContext?n(c,this).index(i)>=0:n.find(c,this,null,[i]).length),e[c]&&e.push(d);e.length&&g.push({elem:i,handlers:e})}return h<b.length&&g.push({elem:this,handlers:b.slice(h)}),g},fix:function(a){if(a[n.expando])return a;var b,c,d,e=a.type,f=a,g=this.fixHooks[e];g||(this.fixHooks[e]=g=$.test(e)?this.mouseHooks:Z.test(e)?this.keyHooks:{}),d=g.props?this.props.concat(g.props):this.props,a=new n.Event(f),b=d.length;while(b--)c=d[b],a[c]=f[c];return a.target||(a.target=f.srcElement||z),3===a.target.nodeType&&(a.target=a.target.parentNode),a.metaKey=!!a.metaKey,g.filter?g.filter(a,f):a},props:"altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "),fixHooks:{},keyHooks:{props:"char charCode key keyCode".split(" "),filter:function(a,b){return null==a.which&&(a.which=null!=b.charCode?b.charCode:b.keyCode),a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "),filter:function(a,b){var c,d,e,f=b.button,g=b.fromElement;return null==a.pageX&&null!=b.clientX&&(d=a.target.ownerDocument||z,e=d.documentElement,c=d.body,a.pageX=b.clientX+(e&&e.scrollLeft||c&&c.scrollLeft||0)-(e&&e.clientLeft||c&&c.clientLeft||0),a.pageY=b.clientY+(e&&e.scrollTop||c&&c.scrollTop||0)-(e&&e.clientTop||c&&c.clientTop||0)),!a.relatedTarget&&g&&(a.relatedTarget=g===a.target?b.toElement:g),a.which||void 0===f||(a.which=1&f?1:2&f?3:4&f?2:0),a}},special:{load:{noBubble:!0},focus:{trigger:function(){if(this!==db()&&this.focus)try{return this.focus(),!1}catch(a){}},delegateType:"focusin"},blur:{trigger:function(){return this===db()&&this.blur?(this.blur(),!1):void 0},delegateType:"focusout"},click:{trigger:function(){return n.nodeName(this,"input")&&"checkbox"===this.type&&this.click?(this.click(),!1):void 0},_default:function(a){return n.nodeName(a.target,"a")}},beforeunload:{postDispatch:function(a){void 0!==a.result&&(a.originalEvent.returnValue=a.result)}}},simulate:function(a,b,c,d){var e=n.extend(new n.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?n.event.trigger(e,null,b):n.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},n.removeEvent=z.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){var d="on"+b;a.detachEvent&&(typeof a[d]===L&&(a[d]=null),a.detachEvent(d,c))},n.Event=function(a,b){return this instanceof n.Event?(a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||void 0===a.defaultPrevented&&(a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault())?bb:cb):this.type=a,b&&n.extend(this,b),this.timeStamp=a&&a.timeStamp||n.now(),void(this[n.expando]=!0)):new n.Event(a,b)},n.Event.prototype={isDefaultPrevented:cb,isPropagationStopped:cb,isImmediatePropagationStopped:cb,preventDefault:function(){var a=this.originalEvent;this.isDefaultPrevented=bb,a&&(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){var a=this.originalEvent;this.isPropagationStopped=bb,a&&(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=bb,this.stopPropagation()}},n.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){n.event.special[a]={delegateType:b,bindType:b,handle:function(a){var c,d=this,e=a.relatedTarget,f=a.handleObj;return(!e||e!==d&&!n.contains(d,e))&&(a.type=f.origType,c=f.handler.apply(this,arguments),a.type=b),c}}}),l.submitBubbles||(n.event.special.submit={setup:function(){return n.nodeName(this,"form")?!1:void n.event.add(this,"click._submit keypress._submit",function(a){var b=a.target,c=n.nodeName(b,"input")||n.nodeName(b,"button")?b.form:void 0;c&&!n._data(c,"submitBubbles")&&(n.event.add(c,"submit._submit",function(a){a._submit_bubble=!0}),n._data(c,"submitBubbles",!0))})},postDispatch:function(a){a._submit_bubble&&(delete a._submit_bubble,this.parentNode&&!a.isTrigger&&n.event.simulate("submit",this.parentNode,a,!0))},teardown:function(){return n.nodeName(this,"form")?!1:void n.event.remove(this,"._submit")}}),l.changeBubbles||(n.event.special.change={setup:function(){return Y.test(this.nodeName)?(("checkbox"===this.type||"radio"===this.type)&&(n.event.add(this,"propertychange._change",function(a){"checked"===a.originalEvent.propertyName&&(this._just_changed=!0)}),n.event.add(this,"click._change",function(a){this._just_changed&&!a.isTrigger&&(this._just_changed=!1),n.event.simulate("change",this,a,!0)})),!1):void n.event.add(this,"beforeactivate._change",function(a){var b=a.target;Y.test(b.nodeName)&&!n._data(b,"changeBubbles")&&(n.event.add(b,"change._change",function(a){!this.parentNode||a.isSimulated||a.isTrigger||n.event.simulate("change",this.parentNode,a,!0)}),n._data(b,"changeBubbles",!0))})},handle:function(a){var b=a.target;return this!==b||a.isSimulated||a.isTrigger||"radio"!==b.type&&"checkbox"!==b.type?a.handleObj.handler.apply(this,arguments):void 0},teardown:function(){return n.event.remove(this,"._change"),!Y.test(this.nodeName)}}),l.focusinBubbles||n.each({focus:"focusin",blur:"focusout"},function(a,b){var c=function(a){n.event.simulate(b,a.target,n.event.fix(a),!0)};n.event.special[b]={setup:function(){var d=this.ownerDocument||this,e=n._data(d,b);e||d.addEventListener(a,c,!0),n._data(d,b,(e||0)+1)},teardown:function(){var d=this.ownerDocument||this,e=n._data(d,b)-1;e?n._data(d,b,e):(d.removeEventListener(a,c,!0),n._removeData(d,b))}}}),n.fn.extend({on:function(a,b,c,d,e){var f,g;if("object"==typeof a){"string"!=typeof b&&(c=c||b,b=void 0);for(f in a)this.on(f,b,c,a[f],e);return this}if(null==c&&null==d?(d=b,c=b=void 0):null==d&&("string"==typeof b?(d=c,c=void 0):(d=c,c=b,b=void 0)),d===!1)d=cb;else if(!d)return this;return 1===e&&(g=d,d=function(a){return n().off(a),g.apply(this,arguments)},d.guid=g.guid||(g.guid=n.guid++)),this.each(function(){n.event.add(this,a,d,c,b)})},one:function(a,b,c,d){return this.on(a,b,c,d,1)},off:function(a,b,c){var d,e;if(a&&a.preventDefault&&a.handleObj)return d=a.handleObj,n(a.delegateTarget).off(d.namespace?d.origType+"."+d.namespace:d.origType,d.selector,d.handler),this;if("object"==typeof a){for(e in a)this.off(e,b,a[e]);return this}return(b===!1||"function"==typeof b)&&(c=b,b=void 0),c===!1&&(c=cb),this.each(function(){n.event.remove(this,a,c,b)})},trigger:function(a,b){return this.each(function(){n.event.trigger(a,b,this)})},triggerHandler:function(a,b){var c=this[0];return c?n.event.trigger(a,b,c,!0):void 0}});function eb(a){var b=fb.split("|"),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}var fb="abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|header|hgroup|mark|meter|nav|output|progress|section|summary|time|video",gb=/ jQuery\d+="(?:null|\d+)"/g,hb=new RegExp("<(?:"+fb+")[\\s/>]","i"),ib=/^\s+/,jb=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi,kb=/<([\w:]+)/,lb=/<tbody/i,mb=/<|&#?\w+;/,nb=/<(?:script|style|link)/i,ob=/checked\s*(?:[^=]|=\s*.checked.)/i,pb=/^$|\/(?:java|ecma)script/i,qb=/^true\/(.*)/,rb=/^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g,sb={option:[1,"<select multiple='multiple'>","</select>"],legend:[1,"<fieldset>","</fieldset>"],area:[1,"<map>","</map>"],param:[1,"<object>","</object>"],thead:[1,"<table>","</table>"],tr:[2,"<table><tbody>","</tbody></table>"],col:[2,"<table><tbody></tbody><colgroup>","</colgroup></table>"],td:[3,"<table><tbody><tr>","</tr></tbody></table>"],_default:l.htmlSerialize?[0,"",""]:[1,"X<div>","</div>"]},tb=eb(z),ub=tb.appendChild(z.createElement("div"));sb.optgroup=sb.option,sb.tbody=sb.tfoot=sb.colgroup=sb.caption=sb.thead,sb.th=sb.td;function vb(a,b){var c,d,e=0,f=typeof a.getElementsByTagName!==L?a.getElementsByTagName(b||"*"):typeof a.querySelectorAll!==L?a.querySelectorAll(b||"*"):void 0;if(!f)for(f=[],c=a.childNodes||a;null!=(d=c[e]);e++)!b||n.nodeName(d,b)?f.push(d):n.merge(f,vb(d,b));return void 0===b||b&&n.nodeName(a,b)?n.merge([a],f):f}function wb(a){X.test(a.type)&&(a.defaultChecked=a.checked)}function xb(a,b){return n.nodeName(a,"table")&&n.nodeName(11!==b.nodeType?b:b.firstChild,"tr")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function yb(a){return a.type=(null!==n.find.attr(a,"type"))+"/"+a.type,a}function zb(a){var b=qb.exec(a.type);return b?a.type=b[1]:a.removeAttribute("type"),a}function Ab(a,b){for(var c,d=0;null!=(c=a[d]);d++)n._data(c,"globalEval",!b||n._data(b[d],"globalEval"))}function Bb(a,b){if(1===b.nodeType&&n.hasData(a)){var c,d,e,f=n._data(a),g=n._data(b,f),h=f.events;if(h){delete g.handle,g.events={};for(c in h)for(d=0,e=h[c].length;e>d;d++)n.event.add(b,c,h[c][d])}g.data&&(g.data=n.extend({},g.data))}}function Cb(a,b){var c,d,e;if(1===b.nodeType){if(c=b.nodeName.toLowerCase(),!l.noCloneEvent&&b[n.expando]){e=n._data(b);for(d in e.events)n.removeEvent(b,d,e.handle);b.removeAttribute(n.expando)}"script"===c&&b.text!==a.text?(yb(b).text=a.text,zb(b)):"object"===c?(b.parentNode&&(b.outerHTML=a.outerHTML),l.html5Clone&&a.innerHTML&&!n.trim(b.innerHTML)&&(b.innerHTML=a.innerHTML)):"input"===c&&X.test(a.type)?(b.defaultChecked=b.checked=a.checked,b.value!==a.value&&(b.value=a.value)):"option"===c?b.defaultSelected=b.selected=a.defaultSelected:("input"===c||"textarea"===c)&&(b.defaultValue=a.defaultValue)}}n.extend({clone:function(a,b,c){var d,e,f,g,h,i=n.contains(a.ownerDocument,a);if(l.html5Clone||n.isXMLDoc(a)||!hb.test("<"+a.nodeName+">")?f=a.cloneNode(!0):(ub.innerHTML=a.outerHTML,ub.removeChild(f=ub.firstChild)),!(l.noCloneEvent&&l.noCloneChecked||1!==a.nodeType&&11!==a.nodeType||n.isXMLDoc(a)))for(d=vb(f),h=vb(a),g=0;null!=(e=h[g]);++g)d[g]&&Cb(e,d[g]);if(b)if(c)for(h=h||vb(a),d=d||vb(f),g=0;null!=(e=h[g]);g++)Bb(e,d[g]);else Bb(a,f);return d=vb(f,"script"),d.length>0&&Ab(d,!i&&vb(a,"script")),d=h=e=null,f},buildFragment:function(a,b,c,d){for(var e,f,g,h,i,j,k,m=a.length,o=eb(b),p=[],q=0;m>q;q++)if(f=a[q],f||0===f)if("object"===n.type(f))n.merge(p,f.nodeType?[f]:f);else if(mb.test(f)){h=h||o.appendChild(b.createElement("div")),i=(kb.exec(f)||["",""])[1].toLowerCase(),k=sb[i]||sb._default,h.innerHTML=k[1]+f.replace(jb,"<$1></$2>")+k[2],e=k[0];while(e--)h=h.lastChild;if(!l.leadingWhitespace&&ib.test(f)&&p.push(b.createTextNode(ib.exec(f)[0])),!l.tbody){f="table"!==i||lb.test(f)?"<table>"!==k[1]||lb.test(f)?0:h:h.firstChild,e=f&&f.childNodes.length;while(e--)n.nodeName(j=f.childNodes[e],"tbody")&&!j.childNodes.length&&f.removeChild(j)}n.merge(p,h.childNodes),h.textContent="";while(h.firstChild)h.removeChild(h.firstChild);h=o.lastChild}else p.push(b.createTextNode(f));h&&o.removeChild(h),l.appendChecked||n.grep(vb(p,"input"),wb),q=0;while(f=p[q++])if((!d||-1===n.inArray(f,d))&&(g=n.contains(f.ownerDocument,f),h=vb(o.appendChild(f),"script"),g&&Ab(h),c)){e=0;while(f=h[e++])pb.test(f.type||"")&&c.push(f)}return h=null,o},cleanData:function(a,b){for(var d,e,f,g,h=0,i=n.expando,j=n.cache,k=l.deleteExpando,m=n.event.special;null!=(d=a[h]);h++)if((b||n.acceptData(d))&&(f=d[i],g=f&&j[f])){if(g.events)for(e in g.events)m[e]?n.event.remove(d,e):n.removeEvent(d,e,g.handle);j[f]&&(delete j[f],k?delete d[i]:typeof d.removeAttribute!==L?d.removeAttribute(i):d[i]=null,c.push(f))}}}),n.fn.extend({text:function(a){return W(this,function(a){return void 0===a?n.text(this):this.empty().append((this[0]&&this[0].ownerDocument||z).createTextNode(a))},null,a,arguments.length)},append:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=xb(this,a);b.appendChild(a)}})},prepend:function(){return this.domManip(arguments,function(a){if(1===this.nodeType||11===this.nodeType||9===this.nodeType){var b=xb(this,a);b.insertBefore(a,b.firstChild)}})},before:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this)})},after:function(){return this.domManip(arguments,function(a){this.parentNode&&this.parentNode.insertBefore(a,this.nextSibling)})},remove:function(a,b){for(var c,d=a?n.filter(a,this):this,e=0;null!=(c=d[e]);e++)b||1!==c.nodeType||n.cleanData(vb(c)),c.parentNode&&(b&&n.contains(c.ownerDocument,c)&&Ab(vb(c,"script")),c.parentNode.removeChild(c));return this},empty:function(){for(var a,b=0;null!=(a=this[b]);b++){1===a.nodeType&&n.cleanData(vb(a,!1));while(a.firstChild)a.removeChild(a.firstChild);a.options&&n.nodeName(a,"select")&&(a.options.length=0)}return this},clone:function(a,b){return a=null==a?!1:a,b=null==b?a:b,this.map(function(){return n.clone(this,a,b)})},html:function(a){return W(this,function(a){var b=this[0]||{},c=0,d=this.length;if(void 0===a)return 1===b.nodeType?b.innerHTML.replace(gb,""):void 0;if(!("string"!=typeof a||nb.test(a)||!l.htmlSerialize&&hb.test(a)||!l.leadingWhitespace&&ib.test(a)||sb[(kb.exec(a)||["",""])[1].toLowerCase()])){a=a.replace(jb,"<$1></$2>");try{for(;d>c;c++)b=this[c]||{},1===b.nodeType&&(n.cleanData(vb(b,!1)),b.innerHTML=a);b=0}catch(e){}}b&&this.empty().append(a)},null,a,arguments.length)},replaceWith:function(){var a=arguments[0];return this.domManip(arguments,function(b){a=this.parentNode,n.cleanData(vb(this)),a&&a.replaceChild(b,this)}),a&&(a.length||a.nodeType)?this:this.remove()},detach:function(a){return this.remove(a,!0)},domManip:function(a,b){a=e.apply([],a);var c,d,f,g,h,i,j=0,k=this.length,m=this,o=k-1,p=a[0],q=n.isFunction(p);if(q||k>1&&"string"==typeof p&&!l.checkClone&&ob.test(p))return this.each(function(c){var d=m.eq(c);q&&(a[0]=p.call(this,c,d.html())),d.domManip(a,b)});if(k&&(i=n.buildFragment(a,this[0].ownerDocument,!1,this),c=i.firstChild,1===i.childNodes.length&&(i=c),c)){for(g=n.map(vb(i,"script"),yb),f=g.length;k>j;j++)d=i,j!==o&&(d=n.clone(d,!0,!0),f&&n.merge(g,vb(d,"script"))),b.call(this[j],d,j);if(f)for(h=g[g.length-1].ownerDocument,n.map(g,zb),j=0;f>j;j++)d=g[j],pb.test(d.type||"")&&!n._data(d,"globalEval")&&n.contains(h,d)&&(d.src?n._evalUrl&&n._evalUrl(d.src):n.globalEval((d.text||d.textContent||d.innerHTML||"").replace(rb,"")));i=c=null}return this}}),n.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){n.fn[a]=function(a){for(var c,d=0,e=[],g=n(a),h=g.length-1;h>=d;d++)c=d===h?this:this.clone(!0),n(g[d])[b](c),f.apply(e,c.get());return this.pushStack(e)}});var Db,Eb={};function Fb(b,c){var d=n(c.createElement(b)).appendTo(c.body),e=a.getDefaultComputedStyle?a.getDefaultComputedStyle(d[0]).display:n.css(d[0],"display");return d.detach(),e}function Gb(a){var b=z,c=Eb[a];return c||(c=Fb(a,b),"none"!==c&&c||(Db=(Db||n("<iframe frameborder='0' width='0' height='0'/>")).appendTo(b.documentElement),b=(Db[0].contentWindow||Db[0].contentDocument).document,b.write(),b.close(),c=Fb(a,b),Db.detach()),Eb[a]=c),c}!function(){var a,b,c=z.createElement("div"),d="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;padding:0;margin:0;border:0";c.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=c.getElementsByTagName("a")[0],a.style.cssText="float:left;opacity:.5",l.opacity=/^0.5/.test(a.style.opacity),l.cssFloat=!!a.style.cssFloat,c.style.backgroundClip="content-box",c.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===c.style.backgroundClip,a=c=null,l.shrinkWrapBlocks=function(){var a,c,e,f;if(null==b){if(a=z.getElementsByTagName("body")[0],!a)return;f="border:0;width:0;height:0;position:absolute;top:0;left:-9999px",c=z.createElement("div"),e=z.createElement("div"),a.appendChild(c).appendChild(e),b=!1,typeof e.style.zoom!==L&&(e.style.cssText=d+";width:1px;padding:1px;zoom:1",e.innerHTML="<div></div>",e.firstChild.style.width="5px",b=3!==e.offsetWidth),a.removeChild(c),a=c=e=null}return b}}();var Hb=/^margin/,Ib=new RegExp("^("+T+")(?!px)[a-z%]+$","i"),Jb,Kb,Lb=/^(top|right|bottom|left)$/;a.getComputedStyle?(Jb=function(a){return a.ownerDocument.defaultView.getComputedStyle(a,null)},Kb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Jb(a),g=c?c.getPropertyValue(b)||c[b]:void 0,c&&(""!==g||n.contains(a.ownerDocument,a)||(g=n.style(a,b)),Ib.test(g)&&Hb.test(b)&&(d=h.width,e=h.minWidth,f=h.maxWidth,h.minWidth=h.maxWidth=h.width=g,g=c.width,h.width=d,h.minWidth=e,h.maxWidth=f)),void 0===g?g:g+""}):z.documentElement.currentStyle&&(Jb=function(a){return a.currentStyle},Kb=function(a,b,c){var d,e,f,g,h=a.style;return c=c||Jb(a),g=c?c[b]:void 0,null==g&&h&&h[b]&&(g=h[b]),Ib.test(g)&&!Lb.test(b)&&(d=h.left,e=a.runtimeStyle,f=e&&e.left,f&&(e.left=a.currentStyle.left),h.left="fontSize"===b?"1em":g,g=h.pixelLeft+"px",h.left=d,f&&(e.left=f)),void 0===g?g:g+""||"auto"});function Mb(a,b){return{get:function(){var c=a();if(null!=c)return c?void delete this.get:(this.get=b).apply(this,arguments)}}}!function(){var b,c,d,e,f,g,h=z.createElement("div"),i="border:0;width:0;height:0;position:absolute;top:0;left:-9999px",j="-webkit-box-sizing:content-box;-moz-box-sizing:content-box;box-sizing:content-box;display:block;padding:0;margin:0;border:0";h.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",b=h.getElementsByTagName("a")[0],b.style.cssText="float:left;opacity:.5",l.opacity=/^0.5/.test(b.style.opacity),l.cssFloat=!!b.style.cssFloat,h.style.backgroundClip="content-box",h.cloneNode(!0).style.backgroundClip="",l.clearCloneStyle="content-box"===h.style.backgroundClip,b=h=null,n.extend(l,{reliableHiddenOffsets:function(){if(null!=c)return c;var a,b,d,e=z.createElement("div"),f=z.getElementsByTagName("body")[0];if(f)return e.setAttribute("className","t"),e.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=z.createElement("div"),a.style.cssText=i,f.appendChild(a).appendChild(e),e.innerHTML="<table><tr><td></td><td>t</td></tr></table>",b=e.getElementsByTagName("td"),b[0].style.cssText="padding:0;margin:0;border:0;display:none",d=0===b[0].offsetHeight,b[0].style.display="",b[1].style.display="none",c=d&&0===b[0].offsetHeight,f.removeChild(a),e=f=null,c},boxSizing:function(){return null==d&&k(),d},boxSizingReliable:function(){return null==e&&k(),e},pixelPosition:function(){return null==f&&k(),f},reliableMarginRight:function(){var b,c,d,e;if(null==g&&a.getComputedStyle){if(b=z.getElementsByTagName("body")[0],!b)return;c=z.createElement("div"),d=z.createElement("div"),c.style.cssText=i,b.appendChild(c).appendChild(d),e=d.appendChild(z.createElement("div")),e.style.cssText=d.style.cssText=j,e.style.marginRight=e.style.width="0",d.style.width="1px",g=!parseFloat((a.getComputedStyle(e,null)||{}).marginRight),b.removeChild(c)}return g}});function k(){var b,c,h=z.getElementsByTagName("body")[0];h&&(b=z.createElement("div"),c=z.createElement("div"),b.style.cssText=i,h.appendChild(b).appendChild(c),c.style.cssText="-webkit-box-sizing:border-box;-moz-box-sizing:border-box;box-sizing:border-box;position:absolute;display:block;padding:1px;border:1px;width:4px;margin-top:1%;top:1%",n.swap(h,null!=h.style.zoom?{zoom:1}:{},function(){d=4===c.offsetWidth}),e=!0,f=!1,g=!0,a.getComputedStyle&&(f="1%"!==(a.getComputedStyle(c,null)||{}).top,e="4px"===(a.getComputedStyle(c,null)||{width:"4px"}).width),h.removeChild(b),c=h=null)}}(),n.swap=function(a,b,c,d){var e,f,g={};for(f in b)g[f]=a.style[f],a.style[f]=b[f];e=c.apply(a,d||[]);for(f in b)a.style[f]=g[f];return e};var Nb=/alpha\([^)]*\)/i,Ob=/opacity\s*=\s*([^)]*)/,Pb=/^(none|table(?!-c[ea]).+)/,Qb=new RegExp("^("+T+")(.*)$","i"),Rb=new RegExp("^([+-])=("+T+")","i"),Sb={position:"absolute",visibility:"hidden",display:"block"},Tb={letterSpacing:0,fontWeight:400},Ub=["Webkit","O","Moz","ms"];function Vb(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=Ub.length;while(e--)if(b=Ub[e]+c,b in a)return b;return d}function Wb(a,b){for(var c,d,e,f=[],g=0,h=a.length;h>g;g++)d=a[g],d.style&&(f[g]=n._data(d,"olddisplay"),c=d.style.display,b?(f[g]||"none"!==c||(d.style.display=""),""===d.style.display&&V(d)&&(f[g]=n._data(d,"olddisplay",Gb(d.nodeName)))):f[g]||(e=V(d),(c&&"none"!==c||!e)&&n._data(d,"olddisplay",e?c:n.css(d,"display"))));for(g=0;h>g;g++)d=a[g],d.style&&(b&&"none"!==d.style.display&&""!==d.style.display||(d.style.display=b?f[g]||"":"none"));return a}function Xb(a,b,c){var d=Qb.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function Yb(a,b,c,d,e){for(var f=c===(d?"border":"content")?4:"width"===b?1:0,g=0;4>f;f+=2)"margin"===c&&(g+=n.css(a,c+U[f],!0,e)),d?("content"===c&&(g-=n.css(a,"padding"+U[f],!0,e)),"margin"!==c&&(g-=n.css(a,"border"+U[f]+"Width",!0,e))):(g+=n.css(a,"padding"+U[f],!0,e),"padding"!==c&&(g+=n.css(a,"border"+U[f]+"Width",!0,e)));return g}function Zb(a,b,c){var d=!0,e="width"===b?a.offsetWidth:a.offsetHeight,f=Jb(a),g=l.boxSizing()&&"border-box"===n.css(a,"boxSizing",!1,f);if(0>=e||null==e){if(e=Kb(a,b,f),(0>e||null==e)&&(e=a.style[b]),Ib.test(e))return e;d=g&&(l.boxSizingReliable()||e===a.style[b]),e=parseFloat(e)||0}return e+Yb(a,b,c||(g?"border":"content"),d,f)+"px"}n.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=Kb(a,"opacity");return""===c?"1":c}}}},cssNumber:{columnCount:!0,fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,order:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":l.cssFloat?"cssFloat":"styleFloat"},style:function(a,b,c,d){if(a&&3!==a.nodeType&&8!==a.nodeType&&a.style){var e,f,g,h=n.camelCase(b),i=a.style;if(b=n.cssProps[h]||(n.cssProps[h]=Vb(i,h)),g=n.cssHooks[b]||n.cssHooks[h],void 0===c)return g&&"get"in g&&void 0!==(e=g.get(a,!1,d))?e:i[b];if(f=typeof c,"string"===f&&(e=Rb.exec(c))&&(c=(e[1]+1)*e[2]+parseFloat(n.css(a,b)),f="number"),null!=c&&c===c&&("number"!==f||n.cssNumber[h]||(c+="px"),l.clearCloneStyle||""!==c||0!==b.indexOf("background")||(i[b]="inherit"),!(g&&"set"in g&&void 0===(c=g.set(a,c,d)))))try{i[b]="",i[b]=c}catch(j){}}},css:function(a,b,c,d){var e,f,g,h=n.camelCase(b);return b=n.cssProps[h]||(n.cssProps[h]=Vb(a.style,h)),g=n.cssHooks[b]||n.cssHooks[h],g&&"get"in g&&(f=g.get(a,!0,c)),void 0===f&&(f=Kb(a,b,d)),"normal"===f&&b in Tb&&(f=Tb[b]),""===c||c?(e=parseFloat(f),c===!0||n.isNumeric(e)?e||0:f):f}}),n.each(["height","width"],function(a,b){n.cssHooks[b]={get:function(a,c,d){return c?0===a.offsetWidth&&Pb.test(n.css(a,"display"))?n.swap(a,Sb,function(){return Zb(a,b,d)}):Zb(a,b,d):void 0},set:function(a,c,d){var e=d&&Jb(a);return Xb(a,c,d?Yb(a,b,d,l.boxSizing()&&"border-box"===n.css(a,"boxSizing",!1,e),e):0)}}}),l.opacity||(n.cssHooks.opacity={get:function(a,b){return Ob.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?.01*parseFloat(RegExp.$1)+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=n.isNumeric(b)?"alpha(opacity="+100*b+")":"",f=d&&d.filter||c.filter||"";c.zoom=1,(b>=1||""===b)&&""===n.trim(f.replace(Nb,""))&&c.removeAttribute&&(c.removeAttribute("filter"),""===b||d&&!d.filter)||(c.filter=Nb.test(f)?f.replace(Nb,e):f+" "+e)}}),n.cssHooks.marginRight=Mb(l.reliableMarginRight,function(a,b){return b?n.swap(a,{display:"inline-block"},Kb,[a,"marginRight"]):void 0}),n.each({margin:"",padding:"",border:"Width"},function(a,b){n.cssHooks[a+b]={expand:function(c){for(var d=0,e={},f="string"==typeof c?c.split(" "):[c];4>d;d++)e[a+U[d]+b]=f[d]||f[d-2]||f[0];return e}},Hb.test(a)||(n.cssHooks[a+b].set=Xb)}),n.fn.extend({css:function(a,b){return W(this,function(a,b,c){var d,e,f={},g=0;if(n.isArray(b)){for(d=Jb(a),e=b.length;e>g;g++)f[b[g]]=n.css(a,b[g],!1,d);return f}return void 0!==c?n.style(a,b,c):n.css(a,b)
},a,b,arguments.length>1)},show:function(){return Wb(this,!0)},hide:function(){return Wb(this)},toggle:function(a){return"boolean"==typeof a?a?this.show():this.hide():this.each(function(){V(this)?n(this).show():n(this).hide()})}});function $b(a,b,c,d,e){return new $b.prototype.init(a,b,c,d,e)}n.Tween=$b,$b.prototype={constructor:$b,init:function(a,b,c,d,e,f){this.elem=a,this.prop=c,this.easing=e||"swing",this.options=b,this.start=this.now=this.cur(),this.end=d,this.unit=f||(n.cssNumber[c]?"":"px")},cur:function(){var a=$b.propHooks[this.prop];return a&&a.get?a.get(this):$b.propHooks._default.get(this)},run:function(a){var b,c=$b.propHooks[this.prop];return this.pos=b=this.options.duration?n.easing[this.easing](a,this.options.duration*a,0,1,this.options.duration):a,this.now=(this.end-this.start)*b+this.start,this.options.step&&this.options.step.call(this.elem,this.now,this),c&&c.set?c.set(this):$b.propHooks._default.set(this),this}},$b.prototype.init.prototype=$b.prototype,$b.propHooks={_default:{get:function(a){var b;return null==a.elem[a.prop]||a.elem.style&&null!=a.elem.style[a.prop]?(b=n.css(a.elem,a.prop,""),b&&"auto"!==b?b:0):a.elem[a.prop]},set:function(a){n.fx.step[a.prop]?n.fx.step[a.prop](a):a.elem.style&&(null!=a.elem.style[n.cssProps[a.prop]]||n.cssHooks[a.prop])?n.style(a.elem,a.prop,a.now+a.unit):a.elem[a.prop]=a.now}}},$b.propHooks.scrollTop=$b.propHooks.scrollLeft={set:function(a){a.elem.nodeType&&a.elem.parentNode&&(a.elem[a.prop]=a.now)}},n.easing={linear:function(a){return a},swing:function(a){return.5-Math.cos(a*Math.PI)/2}},n.fx=$b.prototype.init,n.fx.step={};var _b,ac,bc=/^(?:toggle|show|hide)$/,cc=new RegExp("^(?:([+-])=|)("+T+")([a-z%]*)$","i"),dc=/queueHooks$/,ec=[jc],fc={"*":[function(a,b){var c=this.createTween(a,b),d=c.cur(),e=cc.exec(b),f=e&&e[3]||(n.cssNumber[a]?"":"px"),g=(n.cssNumber[a]||"px"!==f&&+d)&&cc.exec(n.css(c.elem,a)),h=1,i=20;if(g&&g[3]!==f){f=f||g[3],e=e||[],g=+d||1;do h=h||".5",g/=h,n.style(c.elem,a,g+f);while(h!==(h=c.cur()/d)&&1!==h&&--i)}return e&&(g=c.start=+g||+d||0,c.unit=f,c.end=e[1]?g+(e[1]+1)*e[2]:+e[2]),c}]};function gc(){return setTimeout(function(){_b=void 0}),_b=n.now()}function hc(a,b){var c,d={height:a},e=0;for(b=b?1:0;4>e;e+=2-b)c=U[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function ic(a,b,c){for(var d,e=(fc[b]||[]).concat(fc["*"]),f=0,g=e.length;g>f;f++)if(d=e[f].call(c,b,a))return d}function jc(a,b,c){var d,e,f,g,h,i,j,k,m=this,o={},p=a.style,q=a.nodeType&&V(a),r=n._data(a,"fxshow");c.queue||(h=n._queueHooks(a,"fx"),null==h.unqueued&&(h.unqueued=0,i=h.empty.fire,h.empty.fire=function(){h.unqueued||i()}),h.unqueued++,m.always(function(){m.always(function(){h.unqueued--,n.queue(a,"fx").length||h.empty.fire()})})),1===a.nodeType&&("height"in b||"width"in b)&&(c.overflow=[p.overflow,p.overflowX,p.overflowY],j=n.css(a,"display"),k=Gb(a.nodeName),"none"===j&&(j=k),"inline"===j&&"none"===n.css(a,"float")&&(l.inlineBlockNeedsLayout&&"inline"!==k?p.zoom=1:p.display="inline-block")),c.overflow&&(p.overflow="hidden",l.shrinkWrapBlocks()||m.always(function(){p.overflow=c.overflow[0],p.overflowX=c.overflow[1],p.overflowY=c.overflow[2]}));for(d in b)if(e=b[d],bc.exec(e)){if(delete b[d],f=f||"toggle"===e,e===(q?"hide":"show")){if("show"!==e||!r||void 0===r[d])continue;q=!0}o[d]=r&&r[d]||n.style(a,d)}if(!n.isEmptyObject(o)){r?"hidden"in r&&(q=r.hidden):r=n._data(a,"fxshow",{}),f&&(r.hidden=!q),q?n(a).show():m.done(function(){n(a).hide()}),m.done(function(){var b;n._removeData(a,"fxshow");for(b in o)n.style(a,b,o[b])});for(d in o)g=ic(q?r[d]:0,d,m),d in r||(r[d]=g.start,q&&(g.end=g.start,g.start="width"===d||"height"===d?1:0))}}function kc(a,b){var c,d,e,f,g;for(c in a)if(d=n.camelCase(c),e=b[d],f=a[c],n.isArray(f)&&(e=f[1],f=a[c]=f[0]),c!==d&&(a[d]=f,delete a[c]),g=n.cssHooks[d],g&&"expand"in g){f=g.expand(f),delete a[d];for(c in f)c in a||(a[c]=f[c],b[c]=e)}else b[d]=e}function lc(a,b,c){var d,e,f=0,g=ec.length,h=n.Deferred().always(function(){delete i.elem}),i=function(){if(e)return!1;for(var b=_b||gc(),c=Math.max(0,j.startTime+j.duration-b),d=c/j.duration||0,f=1-d,g=0,i=j.tweens.length;i>g;g++)j.tweens[g].run(f);return h.notifyWith(a,[j,f,c]),1>f&&i?c:(h.resolveWith(a,[j]),!1)},j=h.promise({elem:a,props:n.extend({},b),opts:n.extend(!0,{specialEasing:{}},c),originalProperties:b,originalOptions:c,startTime:_b||gc(),duration:c.duration,tweens:[],createTween:function(b,c){var d=n.Tween(a,j.opts,b,c,j.opts.specialEasing[b]||j.opts.easing);return j.tweens.push(d),d},stop:function(b){var c=0,d=b?j.tweens.length:0;if(e)return this;for(e=!0;d>c;c++)j.tweens[c].run(1);return b?h.resolveWith(a,[j,b]):h.rejectWith(a,[j,b]),this}}),k=j.props;for(kc(k,j.opts.specialEasing);g>f;f++)if(d=ec[f].call(j,a,k,j.opts))return d;return n.map(k,ic,j),n.isFunction(j.opts.start)&&j.opts.start.call(a,j),n.fx.timer(n.extend(i,{elem:a,anim:j,queue:j.opts.queue})),j.progress(j.opts.progress).done(j.opts.done,j.opts.complete).fail(j.opts.fail).always(j.opts.always)}n.Animation=n.extend(lc,{tweener:function(a,b){n.isFunction(a)?(b=a,a=["*"]):a=a.split(" ");for(var c,d=0,e=a.length;e>d;d++)c=a[d],fc[c]=fc[c]||[],fc[c].unshift(b)},prefilter:function(a,b){b?ec.unshift(a):ec.push(a)}}),n.speed=function(a,b,c){var d=a&&"object"==typeof a?n.extend({},a):{complete:c||!c&&b||n.isFunction(a)&&a,duration:a,easing:c&&b||b&&!n.isFunction(b)&&b};return d.duration=n.fx.off?0:"number"==typeof d.duration?d.duration:d.duration in n.fx.speeds?n.fx.speeds[d.duration]:n.fx.speeds._default,(null==d.queue||d.queue===!0)&&(d.queue="fx"),d.old=d.complete,d.complete=function(){n.isFunction(d.old)&&d.old.call(this),d.queue&&n.dequeue(this,d.queue)},d},n.fn.extend({fadeTo:function(a,b,c,d){return this.filter(V).css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){var e=n.isEmptyObject(a),f=n.speed(b,c,d),g=function(){var b=lc(this,n.extend({},a),f);(e||n._data(this,"finish"))&&b.stop(!0)};return g.finish=g,e||f.queue===!1?this.each(g):this.queue(f.queue,g)},stop:function(a,b,c){var d=function(a){var b=a.stop;delete a.stop,b(c)};return"string"!=typeof a&&(c=b,b=a,a=void 0),b&&a!==!1&&this.queue(a||"fx",[]),this.each(function(){var b=!0,e=null!=a&&a+"queueHooks",f=n.timers,g=n._data(this);if(e)g[e]&&g[e].stop&&d(g[e]);else for(e in g)g[e]&&g[e].stop&&dc.test(e)&&d(g[e]);for(e=f.length;e--;)f[e].elem!==this||null!=a&&f[e].queue!==a||(f[e].anim.stop(c),b=!1,f.splice(e,1));(b||!c)&&n.dequeue(this,a)})},finish:function(a){return a!==!1&&(a=a||"fx"),this.each(function(){var b,c=n._data(this),d=c[a+"queue"],e=c[a+"queueHooks"],f=n.timers,g=d?d.length:0;for(c.finish=!0,n.queue(this,a,[]),e&&e.stop&&e.stop.call(this,!0),b=f.length;b--;)f[b].elem===this&&f[b].queue===a&&(f[b].anim.stop(!0),f.splice(b,1));for(b=0;g>b;b++)d[b]&&d[b].finish&&d[b].finish.call(this);delete c.finish})}}),n.each(["toggle","show","hide"],function(a,b){var c=n.fn[b];n.fn[b]=function(a,d,e){return null==a||"boolean"==typeof a?c.apply(this,arguments):this.animate(hc(b,!0),a,d,e)}}),n.each({slideDown:hc("show"),slideUp:hc("hide"),slideToggle:hc("toggle"),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){n.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),n.timers=[],n.fx.tick=function(){var a,b=n.timers,c=0;for(_b=n.now();c<b.length;c++)a=b[c],a()||b[c]!==a||b.splice(c--,1);b.length||n.fx.stop(),_b=void 0},n.fx.timer=function(a){n.timers.push(a),a()?n.fx.start():n.timers.pop()},n.fx.interval=13,n.fx.start=function(){ac||(ac=setInterval(n.fx.tick,n.fx.interval))},n.fx.stop=function(){clearInterval(ac),ac=null},n.fx.speeds={slow:600,fast:200,_default:400},n.fn.delay=function(a,b){return a=n.fx?n.fx.speeds[a]||a:a,b=b||"fx",this.queue(b,function(b,c){var d=setTimeout(b,a);c.stop=function(){clearTimeout(d)}})},function(){var a,b,c,d,e=z.createElement("div");e.setAttribute("className","t"),e.innerHTML=" <link/><table></table><a href='/a'>a</a><input type='checkbox'/>",a=e.getElementsByTagName("a")[0],c=z.createElement("select"),d=c.appendChild(z.createElement("option")),b=e.getElementsByTagName("input")[0],a.style.cssText="top:1px",l.getSetAttribute="t"!==e.className,l.style=/top/.test(a.getAttribute("style")),l.hrefNormalized="/a"===a.getAttribute("href"),l.checkOn=!!b.value,l.optSelected=d.selected,l.enctype=!!z.createElement("form").enctype,c.disabled=!0,l.optDisabled=!d.disabled,b=z.createElement("input"),b.setAttribute("value",""),l.input=""===b.getAttribute("value"),b.value="t",b.setAttribute("type","radio"),l.radioValue="t"===b.value,a=b=c=d=e=null}();var mc=/\r/g;n.fn.extend({val:function(a){var b,c,d,e=this[0];{if(arguments.length)return d=n.isFunction(a),this.each(function(c){var e;1===this.nodeType&&(e=d?a.call(this,c,n(this).val()):a,null==e?e="":"number"==typeof e?e+="":n.isArray(e)&&(e=n.map(e,function(a){return null==a?"":a+""})),b=n.valHooks[this.type]||n.valHooks[this.nodeName.toLowerCase()],b&&"set"in b&&void 0!==b.set(this,e,"value")||(this.value=e))});if(e)return b=n.valHooks[e.type]||n.valHooks[e.nodeName.toLowerCase()],b&&"get"in b&&void 0!==(c=b.get(e,"value"))?c:(c=e.value,"string"==typeof c?c.replace(mc,""):null==c?"":c)}}}),n.extend({valHooks:{option:{get:function(a){var b=n.find.attr(a,"value");return null!=b?b:n.text(a)}},select:{get:function(a){for(var b,c,d=a.options,e=a.selectedIndex,f="select-one"===a.type||0>e,g=f?null:[],h=f?e+1:d.length,i=0>e?h:f?e:0;h>i;i++)if(c=d[i],!(!c.selected&&i!==e||(l.optDisabled?c.disabled:null!==c.getAttribute("disabled"))||c.parentNode.disabled&&n.nodeName(c.parentNode,"optgroup"))){if(b=n(c).val(),f)return b;g.push(b)}return g},set:function(a,b){var c,d,e=a.options,f=n.makeArray(b),g=e.length;while(g--)if(d=e[g],n.inArray(n.valHooks.option.get(d),f)>=0)try{d.selected=c=!0}catch(h){d.scrollHeight}else d.selected=!1;return c||(a.selectedIndex=-1),e}}}}),n.each(["radio","checkbox"],function(){n.valHooks[this]={set:function(a,b){return n.isArray(b)?a.checked=n.inArray(n(a).val(),b)>=0:void 0}},l.checkOn||(n.valHooks[this].get=function(a){return null===a.getAttribute("value")?"on":a.value})});var nc,oc,pc=n.expr.attrHandle,qc=/^(?:checked|selected)$/i,rc=l.getSetAttribute,sc=l.input;n.fn.extend({attr:function(a,b){return W(this,n.attr,a,b,arguments.length>1)},removeAttr:function(a){return this.each(function(){n.removeAttr(this,a)})}}),n.extend({attr:function(a,b,c){var d,e,f=a.nodeType;if(a&&3!==f&&8!==f&&2!==f)return typeof a.getAttribute===L?n.prop(a,b,c):(1===f&&n.isXMLDoc(a)||(b=b.toLowerCase(),d=n.attrHooks[b]||(n.expr.match.bool.test(b)?oc:nc)),void 0===c?d&&"get"in d&&null!==(e=d.get(a,b))?e:(e=n.find.attr(a,b),null==e?void 0:e):null!==c?d&&"set"in d&&void 0!==(e=d.set(a,c,b))?e:(a.setAttribute(b,c+""),c):void n.removeAttr(a,b))},removeAttr:function(a,b){var c,d,e=0,f=b&&b.match(F);if(f&&1===a.nodeType)while(c=f[e++])d=n.propFix[c]||c,n.expr.match.bool.test(c)?sc&&rc||!qc.test(c)?a[d]=!1:a[n.camelCase("default-"+c)]=a[d]=!1:n.attr(a,c,""),a.removeAttribute(rc?c:d)},attrHooks:{type:{set:function(a,b){if(!l.radioValue&&"radio"===b&&n.nodeName(a,"input")){var c=a.value;return a.setAttribute("type",b),c&&(a.value=c),b}}}}}),oc={set:function(a,b,c){return b===!1?n.removeAttr(a,c):sc&&rc||!qc.test(c)?a.setAttribute(!rc&&n.propFix[c]||c,c):a[n.camelCase("default-"+c)]=a[c]=!0,c}},n.each(n.expr.match.bool.source.match(/\w+/g),function(a,b){var c=pc[b]||n.find.attr;pc[b]=sc&&rc||!qc.test(b)?function(a,b,d){var e,f;return d||(f=pc[b],pc[b]=e,e=null!=c(a,b,d)?b.toLowerCase():null,pc[b]=f),e}:function(a,b,c){return c?void 0:a[n.camelCase("default-"+b)]?b.toLowerCase():null}}),sc&&rc||(n.attrHooks.value={set:function(a,b,c){return n.nodeName(a,"input")?void(a.defaultValue=b):nc&&nc.set(a,b,c)}}),rc||(nc={set:function(a,b,c){var d=a.getAttributeNode(c);return d||a.setAttributeNode(d=a.ownerDocument.createAttribute(c)),d.value=b+="","value"===c||b===a.getAttribute(c)?b:void 0}},pc.id=pc.name=pc.coords=function(a,b,c){var d;return c?void 0:(d=a.getAttributeNode(b))&&""!==d.value?d.value:null},n.valHooks.button={get:function(a,b){var c=a.getAttributeNode(b);return c&&c.specified?c.value:void 0},set:nc.set},n.attrHooks.contenteditable={set:function(a,b,c){nc.set(a,""===b?!1:b,c)}},n.each(["width","height"],function(a,b){n.attrHooks[b]={set:function(a,c){return""===c?(a.setAttribute(b,"auto"),c):void 0}}})),l.style||(n.attrHooks.style={get:function(a){return a.style.cssText||void 0},set:function(a,b){return a.style.cssText=b+""}});var tc=/^(?:input|select|textarea|button|object)$/i,uc=/^(?:a|area)$/i;n.fn.extend({prop:function(a,b){return W(this,n.prop,a,b,arguments.length>1)},removeProp:function(a){return a=n.propFix[a]||a,this.each(function(){try{this[a]=void 0,delete this[a]}catch(b){}})}}),n.extend({propFix:{"for":"htmlFor","class":"className"},prop:function(a,b,c){var d,e,f,g=a.nodeType;if(a&&3!==g&&8!==g&&2!==g)return f=1!==g||!n.isXMLDoc(a),f&&(b=n.propFix[b]||b,e=n.propHooks[b]),void 0!==c?e&&"set"in e&&void 0!==(d=e.set(a,c,b))?d:a[b]=c:e&&"get"in e&&null!==(d=e.get(a,b))?d:a[b]},propHooks:{tabIndex:{get:function(a){var b=n.find.attr(a,"tabindex");return b?parseInt(b,10):tc.test(a.nodeName)||uc.test(a.nodeName)&&a.href?0:-1}}}}),l.hrefNormalized||n.each(["href","src"],function(a,b){n.propHooks[b]={get:function(a){return a.getAttribute(b,4)}}}),l.optSelected||(n.propHooks.selected={get:function(a){var b=a.parentNode;return b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex),null}}),n.each(["tabIndex","readOnly","maxLength","cellSpacing","cellPadding","rowSpan","colSpan","useMap","frameBorder","contentEditable"],function(){n.propFix[this.toLowerCase()]=this}),l.enctype||(n.propFix.enctype="encoding");var vc=/[\t\r\n\f]/g;n.fn.extend({addClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j="string"==typeof a&&a;if(n.isFunction(a))return this.each(function(b){n(this).addClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(F)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(vc," "):" ")){f=0;while(e=b[f++])d.indexOf(" "+e+" ")<0&&(d+=e+" ");g=n.trim(d),c.className!==g&&(c.className=g)}return this},removeClass:function(a){var b,c,d,e,f,g,h=0,i=this.length,j=0===arguments.length||"string"==typeof a&&a;if(n.isFunction(a))return this.each(function(b){n(this).removeClass(a.call(this,b,this.className))});if(j)for(b=(a||"").match(F)||[];i>h;h++)if(c=this[h],d=1===c.nodeType&&(c.className?(" "+c.className+" ").replace(vc," "):"")){f=0;while(e=b[f++])while(d.indexOf(" "+e+" ")>=0)d=d.replace(" "+e+" "," ");g=a?n.trim(d):"",c.className!==g&&(c.className=g)}return this},toggleClass:function(a,b){var c=typeof a;return"boolean"==typeof b&&"string"===c?b?this.addClass(a):this.removeClass(a):this.each(n.isFunction(a)?function(c){n(this).toggleClass(a.call(this,c,this.className,b),b)}:function(){if("string"===c){var b,d=0,e=n(this),f=a.match(F)||[];while(b=f[d++])e.hasClass(b)?e.removeClass(b):e.addClass(b)}else(c===L||"boolean"===c)&&(this.className&&n._data(this,"__className__",this.className),this.className=this.className||a===!1?"":n._data(this,"__className__")||"")})},hasClass:function(a){for(var b=" "+a+" ",c=0,d=this.length;d>c;c++)if(1===this[c].nodeType&&(" "+this[c].className+" ").replace(vc," ").indexOf(b)>=0)return!0;return!1}}),n.each("blur focus focusin focusout load resize scroll unload click dblclick mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave change select submit keydown keypress keyup error contextmenu".split(" "),function(a,b){n.fn[b]=function(a,c){return arguments.length>0?this.on(b,null,a,c):this.trigger(b)}}),n.fn.extend({hover:function(a,b){return this.mouseenter(a).mouseleave(b||a)},bind:function(a,b,c){return this.on(a,null,b,c)},unbind:function(a,b){return this.off(a,null,b)},delegate:function(a,b,c,d){return this.on(b,a,c,d)},undelegate:function(a,b,c){return 1===arguments.length?this.off(a,"**"):this.off(b,a||"**",c)}});var wc=n.now(),xc=/\?/,yc=/(,)|(\[|{)|(}|])|"(?:[^"\\\r\n]|\\["\\\/bfnrt]|\\u[\da-fA-F]{4})*"\s*:?|true|false|null|-?(?!0\d)\d+(?:\.\d+|)(?:[eE][+-]?\d+|)/g;n.parseJSON=function(b){if(a.JSON&&a.JSON.parse)return a.JSON.parse(b+"");var c,d=null,e=n.trim(b+"");return e&&!n.trim(e.replace(yc,function(a,b,e,f){return c&&b&&(d=0),0===d?a:(c=e||b,d+=!f-!e,"")}))?Function("return "+e)():n.error("Invalid JSON: "+b)},n.parseXML=function(b){var c,d;if(!b||"string"!=typeof b)return null;try{a.DOMParser?(d=new DOMParser,c=d.parseFromString(b,"text/xml")):(c=new ActiveXObject("Microsoft.XMLDOM"),c.async="false",c.loadXML(b))}catch(e){c=void 0}return c&&c.documentElement&&!c.getElementsByTagName("parsererror").length||n.error("Invalid XML: "+b),c};var zc,Ac,Bc=/#.*$/,Cc=/([?&])_=[^&]*/,Dc=/^(.*?):[ \t]*([^\r\n]*)\r?$/gm,Ec=/^(?:about|app|app-storage|.+-extension|file|res|widget):$/,Fc=/^(?:GET|HEAD)$/,Gc=/^\/\//,Hc=/^([\w.+-]+:)(?:\/\/(?:[^\/?#]*@|)([^\/?#:]*)(?::(\d+)|)|)/,Ic={},Jc={},Kc="*/".concat("*");try{Ac=location.href}catch(Lc){Ac=z.createElement("a"),Ac.href="",Ac=Ac.href}zc=Hc.exec(Ac.toLowerCase())||[];function Mc(a){return function(b,c){"string"!=typeof b&&(c=b,b="*");var d,e=0,f=b.toLowerCase().match(F)||[];if(n.isFunction(c))while(d=f[e++])"+"===d.charAt(0)?(d=d.slice(1)||"*",(a[d]=a[d]||[]).unshift(c)):(a[d]=a[d]||[]).push(c)}}function Nc(a,b,c,d){var e={},f=a===Jc;function g(h){var i;return e[h]=!0,n.each(a[h]||[],function(a,h){var j=h(b,c,d);return"string"!=typeof j||f||e[j]?f?!(i=j):void 0:(b.dataTypes.unshift(j),g(j),!1)}),i}return g(b.dataTypes[0])||!e["*"]&&g("*")}function Oc(a,b){var c,d,e=n.ajaxSettings.flatOptions||{};for(d in b)void 0!==b[d]&&((e[d]?a:c||(c={}))[d]=b[d]);return c&&n.extend(!0,a,c),a}function Pc(a,b,c){var d,e,f,g,h=a.contents,i=a.dataTypes;while("*"===i[0])i.shift(),void 0===e&&(e=a.mimeType||b.getResponseHeader("Content-Type"));if(e)for(g in h)if(h[g]&&h[g].test(e)){i.unshift(g);break}if(i[0]in c)f=i[0];else{for(g in c){if(!i[0]||a.converters[g+" "+i[0]]){f=g;break}d||(d=g)}f=f||d}return f?(f!==i[0]&&i.unshift(f),c[f]):void 0}function Qc(a,b,c,d){var e,f,g,h,i,j={},k=a.dataTypes.slice();if(k[1])for(g in a.converters)j[g.toLowerCase()]=a.converters[g];f=k.shift();while(f)if(a.responseFields[f]&&(c[a.responseFields[f]]=b),!i&&d&&a.dataFilter&&(b=a.dataFilter(b,a.dataType)),i=f,f=k.shift())if("*"===f)f=i;else if("*"!==i&&i!==f){if(g=j[i+" "+f]||j["* "+f],!g)for(e in j)if(h=e.split(" "),h[1]===f&&(g=j[i+" "+h[0]]||j["* "+h[0]])){g===!0?g=j[e]:j[e]!==!0&&(f=h[0],k.unshift(h[1]));break}if(g!==!0)if(g&&a["throws"])b=g(b);else try{b=g(b)}catch(l){return{state:"parsererror",error:g?l:"No conversion from "+i+" to "+f}}}return{state:"success",data:b}}n.extend({active:0,lastModified:{},etag:{},ajaxSettings:{url:Ac,type:"GET",isLocal:Ec.test(zc[1]),global:!0,processData:!0,async:!0,contentType:"application/x-www-form-urlencoded; charset=UTF-8",accepts:{"*":Kc,text:"text/plain",html:"text/html",xml:"application/xml, text/xml",json:"application/json, text/javascript"},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText",json:"responseJSON"},converters:{"* text":String,"text html":!0,"text json":n.parseJSON,"text xml":n.parseXML},flatOptions:{url:!0,context:!0}},ajaxSetup:function(a,b){return b?Oc(Oc(a,n.ajaxSettings),b):Oc(n.ajaxSettings,a)},ajaxPrefilter:Mc(Ic),ajaxTransport:Mc(Jc),ajax:function(a,b){"object"==typeof a&&(b=a,a=void 0),b=b||{};var c,d,e,f,g,h,i,j,k=n.ajaxSetup({},b),l=k.context||k,m=k.context&&(l.nodeType||l.jquery)?n(l):n.event,o=n.Deferred(),p=n.Callbacks("once memory"),q=k.statusCode||{},r={},s={},t=0,u="canceled",v={readyState:0,getResponseHeader:function(a){var b;if(2===t){if(!j){j={};while(b=Dc.exec(f))j[b[1].toLowerCase()]=b[2]}b=j[a.toLowerCase()]}return null==b?null:b},getAllResponseHeaders:function(){return 2===t?f:null},setRequestHeader:function(a,b){var c=a.toLowerCase();return t||(a=s[c]=s[c]||a,r[a]=b),this},overrideMimeType:function(a){return t||(k.mimeType=a),this},statusCode:function(a){var b;if(a)if(2>t)for(b in a)q[b]=[q[b],a[b]];else v.always(a[v.status]);return this},abort:function(a){var b=a||u;return i&&i.abort(b),x(0,b),this}};if(o.promise(v).complete=p.add,v.success=v.done,v.error=v.fail,k.url=((a||k.url||Ac)+"").replace(Bc,"").replace(Gc,zc[1]+"//"),k.type=b.method||b.type||k.method||k.type,k.dataTypes=n.trim(k.dataType||"*").toLowerCase().match(F)||[""],null==k.crossDomain&&(c=Hc.exec(k.url.toLowerCase()),k.crossDomain=!(!c||c[1]===zc[1]&&c[2]===zc[2]&&(c[3]||("http:"===c[1]?"80":"443"))===(zc[3]||("http:"===zc[1]?"80":"443")))),k.data&&k.processData&&"string"!=typeof k.data&&(k.data=n.param(k.data,k.traditional)),Nc(Ic,k,b,v),2===t)return v;h=k.global,h&&0===n.active++&&n.event.trigger("ajaxStart"),k.type=k.type.toUpperCase(),k.hasContent=!Fc.test(k.type),e=k.url,k.hasContent||(k.data&&(e=k.url+=(xc.test(e)?"&":"?")+k.data,delete k.data),k.cache===!1&&(k.url=Cc.test(e)?e.replace(Cc,"$1_="+wc++):e+(xc.test(e)?"&":"?")+"_="+wc++)),k.ifModified&&(n.lastModified[e]&&v.setRequestHeader("If-Modified-Since",n.lastModified[e]),n.etag[e]&&v.setRequestHeader("If-None-Match",n.etag[e])),(k.data&&k.hasContent&&k.contentType!==!1||b.contentType)&&v.setRequestHeader("Content-Type",k.contentType),v.setRequestHeader("Accept",k.dataTypes[0]&&k.accepts[k.dataTypes[0]]?k.accepts[k.dataTypes[0]]+("*"!==k.dataTypes[0]?", "+Kc+"; q=0.01":""):k.accepts["*"]);for(d in k.headers)v.setRequestHeader(d,k.headers[d]);if(k.beforeSend&&(k.beforeSend.call(l,v,k)===!1||2===t))return v.abort();u="abort";for(d in{success:1,error:1,complete:1})v[d](k[d]);if(i=Nc(Jc,k,b,v)){v.readyState=1,h&&m.trigger("ajaxSend",[v,k]),k.async&&k.timeout>0&&(g=setTimeout(function(){v.abort("timeout")},k.timeout));try{t=1,i.send(r,x)}catch(w){if(!(2>t))throw w;x(-1,w)}}else x(-1,"No Transport");function x(a,b,c,d){var j,r,s,u,w,x=b;2!==t&&(t=2,g&&clearTimeout(g),i=void 0,f=d||"",v.readyState=a>0?4:0,j=a>=200&&300>a||304===a,c&&(u=Pc(k,v,c)),u=Qc(k,u,v,j),j?(k.ifModified&&(w=v.getResponseHeader("Last-Modified"),w&&(n.lastModified[e]=w),w=v.getResponseHeader("etag"),w&&(n.etag[e]=w)),204===a||"HEAD"===k.type?x="nocontent":304===a?x="notmodified":(x=u.state,r=u.data,s=u.error,j=!s)):(s=x,(a||!x)&&(x="error",0>a&&(a=0))),v.status=a,v.statusText=(b||x)+"",j?o.resolveWith(l,[r,x,v]):o.rejectWith(l,[v,x,s]),v.statusCode(q),q=void 0,h&&m.trigger(j?"ajaxSuccess":"ajaxError",[v,k,j?r:s]),p.fireWith(l,[v,x]),h&&(m.trigger("ajaxComplete",[v,k]),--n.active||n.event.trigger("ajaxStop")))}return v},getJSON:function(a,b,c){return n.get(a,b,c,"json")},getScript:function(a,b){return n.get(a,void 0,b,"script")}}),n.each(["get","post"],function(a,b){n[b]=function(a,c,d,e){return n.isFunction(c)&&(e=e||d,d=c,c=void 0),n.ajax({url:a,type:b,dataType:e,data:c,success:d})}}),n.each(["ajaxStart","ajaxStop","ajaxComplete","ajaxError","ajaxSuccess","ajaxSend"],function(a,b){n.fn[b]=function(a){return this.on(b,a)}}),n._evalUrl=function(a){return n.ajax({url:a,type:"GET",dataType:"script",async:!1,global:!1,"throws":!0})},n.fn.extend({wrapAll:function(a){if(n.isFunction(a))return this.each(function(b){n(this).wrapAll(a.call(this,b))});if(this[0]){var b=n(a,this[0].ownerDocument).eq(0).clone(!0);this[0].parentNode&&b.insertBefore(this[0]),b.map(function(){var a=this;while(a.firstChild&&1===a.firstChild.nodeType)a=a.firstChild;return a}).append(this)}return this},wrapInner:function(a){return this.each(n.isFunction(a)?function(b){n(this).wrapInner(a.call(this,b))}:function(){var b=n(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){var b=n.isFunction(a);return this.each(function(c){n(this).wrapAll(b?a.call(this,c):a)})},unwrap:function(){return this.parent().each(function(){n.nodeName(this,"body")||n(this).replaceWith(this.childNodes)}).end()}}),n.expr.filters.hidden=function(a){return a.offsetWidth<=0&&a.offsetHeight<=0||!l.reliableHiddenOffsets()&&"none"===(a.style&&a.style.display||n.css(a,"display"))},n.expr.filters.visible=function(a){return!n.expr.filters.hidden(a)};var Rc=/%20/g,Sc=/\[\]$/,Tc=/\r?\n/g,Uc=/^(?:submit|button|image|reset|file)$/i,Vc=/^(?:input|select|textarea|keygen)/i;function Wc(a,b,c,d){var e;if(n.isArray(b))n.each(b,function(b,e){c||Sc.test(a)?d(a,e):Wc(a+"["+("object"==typeof e?b:"")+"]",e,c,d)});else if(c||"object"!==n.type(b))d(a,b);else for(e in b)Wc(a+"["+e+"]",b[e],c,d)}n.param=function(a,b){var c,d=[],e=function(a,b){b=n.isFunction(b)?b():null==b?"":b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};if(void 0===b&&(b=n.ajaxSettings&&n.ajaxSettings.traditional),n.isArray(a)||a.jquery&&!n.isPlainObject(a))n.each(a,function(){e(this.name,this.value)});else for(c in a)Wc(c,a[c],b,e);return d.join("&").replace(Rc,"+")},n.fn.extend({serialize:function(){return n.param(this.serializeArray())},serializeArray:function(){return this.map(function(){var a=n.prop(this,"elements");return a?n.makeArray(a):this}).filter(function(){var a=this.type;return this.name&&!n(this).is(":disabled")&&Vc.test(this.nodeName)&&!Uc.test(a)&&(this.checked||!X.test(a))}).map(function(a,b){var c=n(this).val();return null==c?null:n.isArray(c)?n.map(c,function(a){return{name:b.name,value:a.replace(Tc,"\r\n")}}):{name:b.name,value:c.replace(Tc,"\r\n")}}).get()}}),n.ajaxSettings.xhr=void 0!==a.ActiveXObject?function(){return!this.isLocal&&/^(get|post|head|put|delete|options)$/i.test(this.type)&&$c()||_c()}:$c;var Xc=0,Yc={},Zc=n.ajaxSettings.xhr();a.ActiveXObject&&n(a).on("unload",function(){for(var a in Yc)Yc[a](void 0,!0)}),l.cors=!!Zc&&"withCredentials"in Zc,Zc=l.ajax=!!Zc,Zc&&n.ajaxTransport(function(a){if(!a.crossDomain||l.cors){var b;return{send:function(c,d){var e,f=a.xhr(),g=++Xc;if(f.open(a.type,a.url,a.async,a.username,a.password),a.xhrFields)for(e in a.xhrFields)f[e]=a.xhrFields[e];a.mimeType&&f.overrideMimeType&&f.overrideMimeType(a.mimeType),a.crossDomain||c["X-Requested-With"]||(c["X-Requested-With"]="XMLHttpRequest");for(e in c)void 0!==c[e]&&f.setRequestHeader(e,c[e]+"");f.send(a.hasContent&&a.data||null),b=function(c,e){var h,i,j;if(b&&(e||4===f.readyState))if(delete Yc[g],b=void 0,f.onreadystatechange=n.noop,e)4!==f.readyState&&f.abort();else{j={},h=f.status,"string"==typeof f.responseText&&(j.text=f.responseText);try{i=f.statusText}catch(k){i=""}h||!a.isLocal||a.crossDomain?1223===h&&(h=204):h=j.text?200:404}j&&d(h,i,j,f.getAllResponseHeaders())},a.async?4===f.readyState?setTimeout(b):f.onreadystatechange=Yc[g]=b:b()},abort:function(){b&&b(void 0,!0)}}}});function $c(){try{return new a.XMLHttpRequest}catch(b){}}function _c(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}n.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/(?:java|ecma)script/},converters:{"text script":function(a){return n.globalEval(a),a}}}),n.ajaxPrefilter("script",function(a){void 0===a.cache&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),n.ajaxTransport("script",function(a){if(a.crossDomain){var b,c=z.head||n("head")[0]||z.documentElement;return{send:function(d,e){b=z.createElement("script"),b.async=!0,a.scriptCharset&&(b.charset=a.scriptCharset),b.src=a.url,b.onload=b.onreadystatechange=function(a,c){(c||!b.readyState||/loaded|complete/.test(b.readyState))&&(b.onload=b.onreadystatechange=null,b.parentNode&&b.parentNode.removeChild(b),b=null,c||e(200,"success"))},c.insertBefore(b,c.firstChild)},abort:function(){b&&b.onload(void 0,!0)}}}});var ad=[],bd=/(=)\?(?=&|$)|\?\?/;n.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=ad.pop()||n.expando+"_"+wc++;return this[a]=!0,a}}),n.ajaxPrefilter("json jsonp",function(b,c,d){var e,f,g,h=b.jsonp!==!1&&(bd.test(b.url)?"url":"string"==typeof b.data&&!(b.contentType||"").indexOf("application/x-www-form-urlencoded")&&bd.test(b.data)&&"data");return h||"jsonp"===b.dataTypes[0]?(e=b.jsonpCallback=n.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,h?b[h]=b[h].replace(bd,"$1"+e):b.jsonp!==!1&&(b.url+=(xc.test(b.url)?"&":"?")+b.jsonp+"="+e),b.converters["script json"]=function(){return g||n.error(e+" was not called"),g[0]},b.dataTypes[0]="json",f=a[e],a[e]=function(){g=arguments},d.always(function(){a[e]=f,b[e]&&(b.jsonpCallback=c.jsonpCallback,ad.push(e)),g&&n.isFunction(f)&&f(g[0]),g=f=void 0}),"script"):void 0}),n.parseHTML=function(a,b,c){if(!a||"string"!=typeof a)return null;"boolean"==typeof b&&(c=b,b=!1),b=b||z;var d=v.exec(a),e=!c&&[];return d?[b.createElement(d[1])]:(d=n.buildFragment([a],b,e),e&&e.length&&n(e).remove(),n.merge([],d.childNodes))};var cd=n.fn.load;n.fn.load=function(a,b,c){if("string"!=typeof a&&cd)return cd.apply(this,arguments);var d,e,f,g=this,h=a.indexOf(" ");return h>=0&&(d=a.slice(h,a.length),a=a.slice(0,h)),n.isFunction(b)?(c=b,b=void 0):b&&"object"==typeof b&&(f="POST"),g.length>0&&n.ajax({url:a,type:f,dataType:"html",data:b}).done(function(a){e=arguments,g.html(d?n("<div>").append(n.parseHTML(a)).find(d):a)}).complete(c&&function(a,b){g.each(c,e||[a.responseText,b,a])}),this},n.expr.filters.animated=function(a){return n.grep(n.timers,function(b){return a===b.elem}).length};var dd=a.document.documentElement;function ed(a){return n.isWindow(a)?a:9===a.nodeType?a.defaultView||a.parentWindow:!1}n.offset={setOffset:function(a,b,c){var d,e,f,g,h,i,j,k=n.css(a,"position"),l=n(a),m={};"static"===k&&(a.style.position="relative"),h=l.offset(),f=n.css(a,"top"),i=n.css(a,"left"),j=("absolute"===k||"fixed"===k)&&n.inArray("auto",[f,i])>-1,j?(d=l.position(),g=d.top,e=d.left):(g=parseFloat(f)||0,e=parseFloat(i)||0),n.isFunction(b)&&(b=b.call(a,c,h)),null!=b.top&&(m.top=b.top-h.top+g),null!=b.left&&(m.left=b.left-h.left+e),"using"in b?b.using.call(a,m):l.css(m)}},n.fn.extend({offset:function(a){if(arguments.length)return void 0===a?this:this.each(function(b){n.offset.setOffset(this,a,b)});var b,c,d={top:0,left:0},e=this[0],f=e&&e.ownerDocument;if(f)return b=f.documentElement,n.contains(b,e)?(typeof e.getBoundingClientRect!==L&&(d=e.getBoundingClientRect()),c=ed(f),{top:d.top+(c.pageYOffset||b.scrollTop)-(b.clientTop||0),left:d.left+(c.pageXOffset||b.scrollLeft)-(b.clientLeft||0)}):d},position:function(){if(this[0]){var a,b,c={top:0,left:0},d=this[0];return"fixed"===n.css(d,"position")?b=d.getBoundingClientRect():(a=this.offsetParent(),b=this.offset(),n.nodeName(a[0],"html")||(c=a.offset()),c.top+=n.css(a[0],"borderTopWidth",!0),c.left+=n.css(a[0],"borderLeftWidth",!0)),{top:b.top-c.top-n.css(d,"marginTop",!0),left:b.left-c.left-n.css(d,"marginLeft",!0)}}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||dd;while(a&&!n.nodeName(a,"html")&&"static"===n.css(a,"position"))a=a.offsetParent;return a||dd})}}),n.each({scrollLeft:"pageXOffset",scrollTop:"pageYOffset"},function(a,b){var c=/Y/.test(b);n.fn[a]=function(d){return W(this,function(a,d,e){var f=ed(a);return void 0===e?f?b in f?f[b]:f.document.documentElement[d]:a[d]:void(f?f.scrollTo(c?n(f).scrollLeft():e,c?e:n(f).scrollTop()):a[d]=e)},a,d,arguments.length,null)}}),n.each(["top","left"],function(a,b){n.cssHooks[b]=Mb(l.pixelPosition,function(a,c){return c?(c=Kb(a,b),Ib.test(c)?n(a).position()[b]+"px":c):void 0})}),n.each({Height:"height",Width:"width"},function(a,b){n.each({padding:"inner"+a,content:b,"":"outer"+a},function(c,d){n.fn[d]=function(d,e){var f=arguments.length&&(c||"boolean"!=typeof d),g=c||(d===!0||e===!0?"margin":"border");return W(this,function(b,c,d){var e;return n.isWindow(b)?b.document.documentElement["client"+a]:9===b.nodeType?(e=b.documentElement,Math.max(b.body["scroll"+a],e["scroll"+a],b.body["offset"+a],e["offset"+a],e["client"+a])):void 0===d?n.css(b,c,g):n.style(b,c,d,g)},b,f?d:void 0,f,null)}})}),n.fn.size=function(){return this.length},n.fn.andSelf=n.fn.addBack,"function"==typeof define&&define.amd&&define("jquery",[],function(){return n});var fd=a.jQuery,gd=a.$;return n.noConflict=function(b){return a.$===n&&(a.$=gd),b&&a.jQuery===n&&(a.jQuery=fd),n},typeof b===L&&(a.jQuery=a.$=n),n}); |
sites/all/libraries/syntaxhighlighter_3.0.83/tests/js/jquery-1.4.2.js | zilverdistel/zdbe | /*!
* jQuery JavaScript Library v1.4.2
* http://jquery.com/
*
* Copyright 2010, John Resig
* Dual licensed under the MIT or GPL Version 2 licenses.
* http://jquery.org/license
*
* Includes Sizzle.js
* http://sizzlejs.com/
* Copyright 2010, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
*
* Date: Sat Feb 13 22:33:48 2010 -0500
*/
(function( window, undefined ) {
// Define a local copy of jQuery
var jQuery = function( selector, context ) {
// The jQuery object is actually just the init constructor 'enhanced'
return new jQuery.fn.init( selector, context );
},
// Map over jQuery in case of overwrite
_jQuery = window.jQuery,
// Map over the $ in case of overwrite
_$ = window.$,
// Use the correct document accordingly with window argument (sandbox)
document = window.document,
// A central reference to the root jQuery(document)
rootjQuery,
// A simple way to check for HTML strings or ID strings
// (both of which we optimize for)
quickExpr = /^[^<]*(<[\w\W]+>)[^>]*$|^#([\w-]+)$/,
// Is it a simple selector
isSimple = /^.[^:#\[\.,]*$/,
// Check if a string has a non-whitespace character in it
rnotwhite = /\S/,
// Used for trimming whitespace
rtrim = /^(\s|\u00A0)+|(\s|\u00A0)+$/g,
// Match a standalone tag
rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>)?$/,
// Keep a UserAgent string for use with jQuery.browser
userAgent = navigator.userAgent,
// For matching the engine and version of the browser
browserMatch,
// Has the ready events already been bound?
readyBound = false,
// The functions to execute on DOM ready
readyList = [],
// The ready event handler
DOMContentLoaded,
// Save a reference to some core methods
toString = Object.prototype.toString,
hasOwnProperty = Object.prototype.hasOwnProperty,
push = Array.prototype.push,
slice = Array.prototype.slice,
indexOf = Array.prototype.indexOf;
jQuery.fn = jQuery.prototype = {
init: function( selector, context ) {
var match, elem, ret, doc;
// Handle $(""), $(null), or $(undefined)
if ( !selector ) {
return this;
}
// Handle $(DOMElement)
if ( selector.nodeType ) {
this.context = this[0] = selector;
this.length = 1;
return this;
}
// The body element only exists once, optimize finding it
if ( selector === "body" && !context ) {
this.context = document;
this[0] = document.body;
this.selector = "body";
this.length = 1;
return this;
}
// Handle HTML strings
if ( typeof selector === "string" ) {
// Are we dealing with HTML string or an ID?
match = quickExpr.exec( selector );
// Verify a match, and that no context was specified for #id
if ( match && (match[1] || !context) ) {
// HANDLE: $(html) -> $(array)
if ( match[1] ) {
doc = (context ? context.ownerDocument || context : document);
// If a single string is passed in and it's a single tag
// just do a createElement and skip the rest
ret = rsingleTag.exec( selector );
if ( ret ) {
if ( jQuery.isPlainObject( context ) ) {
selector = [ document.createElement( ret[1] ) ];
jQuery.fn.attr.call( selector, context, true );
} else {
selector = [ doc.createElement( ret[1] ) ];
}
} else {
ret = buildFragment( [ match[1] ], [ doc ] );
selector = (ret.cacheable ? ret.fragment.cloneNode(true) : ret.fragment).childNodes;
}
return jQuery.merge( this, selector );
// HANDLE: $("#id")
} else {
elem = document.getElementById( match[2] );
if ( elem ) {
// Handle the case where IE and Opera return items
// by name instead of ID
if ( elem.id !== match[2] ) {
return rootjQuery.find( selector );
}
// Otherwise, we inject the element directly into the jQuery object
this.length = 1;
this[0] = elem;
}
this.context = document;
this.selector = selector;
return this;
}
// HANDLE: $("TAG")
} else if ( !context && /^\w+$/.test( selector ) ) {
this.selector = selector;
this.context = document;
selector = document.getElementsByTagName( selector );
return jQuery.merge( this, selector );
// HANDLE: $(expr, $(...))
} else if ( !context || context.jquery ) {
return (context || rootjQuery).find( selector );
// HANDLE: $(expr, context)
// (which is just equivalent to: $(context).find(expr)
} else {
return jQuery( context ).find( selector );
}
// HANDLE: $(function)
// Shortcut for document ready
} else if ( jQuery.isFunction( selector ) ) {
return rootjQuery.ready( selector );
}
if (selector.selector !== undefined) {
this.selector = selector.selector;
this.context = selector.context;
}
return jQuery.makeArray( selector, this );
},
// Start with an empty selector
selector: "",
// The current version of jQuery being used
jquery: "1.4.2",
// The default length of a jQuery object is 0
length: 0,
// The number of elements contained in the matched element set
size: function() {
return this.length;
},
toArray: function() {
return slice.call( this, 0 );
},
// Get the Nth element in the matched element set OR
// Get the whole matched element set as a clean array
get: function( num ) {
return num == null ?
// Return a 'clean' array
this.toArray() :
// Return just the object
( num < 0 ? this.slice(num)[ 0 ] : this[ num ] );
},
// Take an array of elements and push it onto the stack
// (returning the new matched element set)
pushStack: function( elems, name, selector ) {
// Build a new jQuery matched element set
var ret = jQuery();
if ( jQuery.isArray( elems ) ) {
push.apply( ret, elems );
} else {
jQuery.merge( ret, elems );
}
// Add the old object onto the stack (as a reference)
ret.prevObject = this;
ret.context = this.context;
if ( name === "find" ) {
ret.selector = this.selector + (this.selector ? " " : "") + selector;
} else if ( name ) {
ret.selector = this.selector + "." + name + "(" + selector + ")";
}
// Return the newly-formed element set
return ret;
},
// Execute a callback for every element in the matched set.
// (You can seed the arguments with an array of args, but this is
// only used internally.)
each: function( callback, args ) {
return jQuery.each( this, callback, args );
},
ready: function( fn ) {
// Attach the listeners
jQuery.bindReady();
// If the DOM is already ready
if ( jQuery.isReady ) {
// Execute the function immediately
fn.call( document, jQuery );
// Otherwise, remember the function for later
} else if ( readyList ) {
// Add the function to the wait list
readyList.push( fn );
}
return this;
},
eq: function( i ) {
return i === -1 ?
this.slice( i ) :
this.slice( i, +i + 1 );
},
first: function() {
return this.eq( 0 );
},
last: function() {
return this.eq( -1 );
},
slice: function() {
return this.pushStack( slice.apply( this, arguments ),
"slice", slice.call(arguments).join(",") );
},
map: function( callback ) {
return this.pushStack( jQuery.map(this, function( elem, i ) {
return callback.call( elem, i, elem );
}));
},
end: function() {
return this.prevObject || jQuery(null);
},
// For internal use only.
// Behaves like an Array's method, not like a jQuery method.
push: push,
sort: [].sort,
splice: [].splice
};
// Give the init function the jQuery prototype for later instantiation
jQuery.fn.init.prototype = jQuery.fn;
jQuery.extend = jQuery.fn.extend = function() {
// copy reference to target object
var target = arguments[0] || {}, i = 1, length = arguments.length, deep = false, options, name, src, copy;
// 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 object literal values or arrays
if ( deep && copy && ( jQuery.isPlainObject(copy) || jQuery.isArray(copy) ) ) {
var clone = src && ( jQuery.isPlainObject(src) || jQuery.isArray(src) ) ? src
: jQuery.isArray(copy) ? [] : {};
// 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,
// Handle when the DOM is ready
ready: function() {
// Make sure that the DOM is not already loaded
if ( !jQuery.isReady ) {
// Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443).
if ( !document.body ) {
return setTimeout( jQuery.ready, 13 );
}
// Remember that the DOM is ready
jQuery.isReady = true;
// If there are functions bound, to execute
if ( readyList ) {
// Execute all of them
var fn, i = 0;
while ( (fn = readyList[ i++ ]) ) {
fn.call( document, jQuery );
}
// Reset the list of functions
readyList = null;
}
// Trigger any bound ready events
if ( jQuery.fn.triggerHandler ) {
jQuery( document ).triggerHandler( "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" ) {
return jQuery.ready();
}
// 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 toString.call(obj) === "[object Function]";
},
isArray: function( obj ) {
return toString.call(obj) === "[object Array]";
},
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 || toString.call(obj) !== "[object Object]" || obj.nodeType || obj.setInterval ) {
return false;
}
// Not own constructor property must be Object
if ( obj.constructor
&& !hasOwnProperty.call(obj, "constructor")
&& !hasOwnProperty.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 || hasOwnProperty.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 ( /^[\],:{}\s]*$/.test(data.replace(/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g, "@")
.replace(/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g, "]")
.replace(/(?:^|:|,)(?:\s*\[)+/g, "")) ) {
// Try to use the native JSON parser first
return window.JSON && window.JSON.parse ?
window.JSON.parse( data ) :
(new Function("return " + data))();
} else {
jQuery.error( "Invalid JSON: " + data );
}
},
noop: function() {},
// Evalulates a script in a global context
globalEval: function( data ) {
if ( data && rnotwhite.test(data) ) {
// Inspired by code by Andrea Giammarchi
// http://webreflection.blogspot.com/2007/08/global-scope-evaluation-and-dom.html
var head = document.getElementsByTagName("head")[0] || document.documentElement,
script = document.createElement("script");
script.type = "text/javascript";
if ( jQuery.support.scriptEval ) {
script.appendChild( document.createTextNode( data ) );
} else {
script.text = data;
}
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
// This arises when a base node is used (#2709).
head.insertBefore( script, head.firstChild );
head.removeChild( script );
}
},
nodeName: function( elem, name ) {
return elem.nodeName && elem.nodeName.toUpperCase() === name.toUpperCase();
},
// args is for internal usage only
each: function( object, callback, args ) {
var name, i = 0,
length = object.length,
isObj = length === undefined || jQuery.isFunction(object);
if ( args ) {
if ( isObj ) {
for ( name in object ) {
if ( callback.apply( object[ name ], args ) === false ) {
break;
}
}
} else {
for ( ; i < length; ) {
if ( callback.apply( object[ i++ ], args ) === false ) {
break;
}
}
}
// A special, fast, case for the most common use of each
} else {
if ( isObj ) {
for ( name in object ) {
if ( callback.call( object[ name ], name, object[ name ] ) === false ) {
break;
}
}
} else {
for ( var value = object[0];
i < length && callback.call( value, i, value ) !== false; value = object[++i] ) {}
}
}
return object;
},
trim: function( text ) {
return (text || "").replace( rtrim, "" );
},
// 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)
if ( array.length == null || typeof array === "string" || jQuery.isFunction(array) || (typeof array !== "function" && array.setInterval) ) {
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 = [];
// Go through the array, only saving the items
// that pass the validator function
for ( var i = 0, length = elems.length; i < length; i++ ) {
if ( !inv !== !callback( elems[ i ], i ) ) {
ret.push( elems[ i ] );
}
}
return ret;
},
// arg is for internal usage only
map: function( elems, callback, arg ) {
var ret = [], value;
// Go through the array, translating each of the items to their
// new value (or values).
for ( var i = 0, length = elems.length; i < length; i++ ) {
value = callback( elems[ i ], i, arg );
if ( value != null ) {
ret[ ret.length ] = value;
}
}
return ret.concat.apply( [], ret );
},
// A global GUID counter for objects
guid: 1,
proxy: function( fn, proxy, thisObject ) {
if ( arguments.length === 2 ) {
if ( typeof proxy === "string" ) {
thisObject = fn;
fn = thisObject[ proxy ];
proxy = undefined;
} else if ( proxy && !jQuery.isFunction( proxy ) ) {
thisObject = proxy;
proxy = undefined;
}
}
if ( !proxy && fn ) {
proxy = function() {
return fn.apply( thisObject || this, arguments );
};
}
// Set the guid of unique handler to the same of original handler, so it can be removed
if ( fn ) {
proxy.guid = fn.guid = fn.guid || proxy.guid || jQuery.guid++;
}
// So proxy can be declared as an argument
return proxy;
},
// Use of jQuery.browser is frowned upon.
// More details: http://docs.jquery.com/Utilities/jQuery.browser
uaMatch: function( ua ) {
ua = ua.toLowerCase();
var match = /(webkit)[ \/]([\w.]+)/.exec( ua ) ||
/(opera)(?:.*version)?[ \/]([\w.]+)/.exec( ua ) ||
/(msie) ([\w.]+)/.exec( ua ) ||
!/compatible/.test( ua ) && /(mozilla)(?:.*? rv:([\w.]+))?/.exec( ua ) ||
[];
return { browser: match[1] || "", version: match[2] || "0" };
},
browser: {}
});
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 );
};
}
// 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( error ) {
setTimeout( doScrollCheck, 1 );
return;
}
// and execute any waiting functions
jQuery.ready();
}
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 );
}
}
// Mutifunctional method to get and set values to a collection
// The value/s can be optionally by executed if its a function
function access( elems, key, value, exec, fn, pass ) {
var length = elems.length;
// Setting many attributes
if ( typeof key === "object" ) {
for ( var k in key ) {
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;
}
function now() {
return (new Date).getTime();
}
(function() {
jQuery.support = {};
var root = document.documentElement,
script = document.createElement("script"),
div = document.createElement("div"),
id = "script" + now();
div.style.display = "none";
div.innerHTML = " <link/><table></table><a href='/a' style='color:red;float:left;opacity:.55;'>a</a><input type='checkbox'/>";
var all = div.getElementsByTagName("*"),
a = div.getElementsByTagName("a")[0];
// 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: document.createElement("select").appendChild( document.createElement("option") ).selected,
parentNode: div.removeChild( div.appendChild( document.createElement("div") ) ).parentNode === null,
// Will be defined later
deleteExpando: true,
checkClone: false,
scriptEval: false,
noCloneEvent: true,
boxModel: null
};
script.type = "text/javascript";
try {
script.appendChild( document.createTextNode( "window." + id + "=1;" ) );
} catch(e) {}
root.insertBefore( script, root.firstChild );
// Make sure that the execution of code works by injecting a script
// tag with appendChild/createTextNode
// (IE doesn't support this, fails, and uses .text instead)
if ( window[ id ] ) {
jQuery.support.scriptEval = true;
delete window[ id ];
}
// Test to see if it's possible to delete an expando from an element
// Fails in Internet Explorer
try {
delete script.test;
} catch(e) {
jQuery.support.deleteExpando = false;
}
root.removeChild( script );
if ( div.attachEvent && div.fireEvent ) {
div.attachEvent("onclick", function click() {
// Cloning a node shouldn't copy over any
// bound event handlers (IE does this)
jQuery.support.noCloneEvent = false;
div.detachEvent("onclick", click);
});
div.cloneNode(true).fireEvent("onclick");
}
div = document.createElement("div");
div.innerHTML = "<input type='radio' name='radiotest' checked='checked'/>";
var fragment = document.createDocumentFragment();
fragment.appendChild( div.firstChild );
// WebKit doesn't clone checked state correctly in fragments
jQuery.support.checkClone = fragment.cloneNode(true).cloneNode(true).lastChild.checked;
// Figure out if the W3C box model works as expected
// document.body must exist before we can do this
jQuery(function() {
var div = document.createElement("div");
div.style.width = div.style.paddingLeft = "1px";
document.body.appendChild( div );
jQuery.boxModel = jQuery.support.boxModel = div.offsetWidth === 2;
document.body.removeChild( div ).style.display = 'none';
div = null;
});
// Technique from Juriy Zaytsev
// http://thinkweb2.com/projects/prototype/detecting-event-support-without-browser-sniffing/
var eventSupported = function( eventName ) {
var el = document.createElement("div");
eventName = "on" + eventName;
var isSupported = (eventName in el);
if ( !isSupported ) {
el.setAttribute(eventName, "return;");
isSupported = typeof el[eventName] === "function";
}
el = null;
return isSupported;
};
jQuery.support.submitBubbles = eventSupported("submit");
jQuery.support.changeBubbles = eventSupported("change");
// release memory in IE
root = script = div = all = a = null;
})();
jQuery.props = {
"for": "htmlFor",
"class": "className",
readonly: "readOnly",
maxlength: "maxLength",
cellspacing: "cellSpacing",
rowspan: "rowSpan",
colspan: "colSpan",
tabindex: "tabIndex",
usemap: "useMap",
frameborder: "frameBorder"
};
var expando = "jQuery" + now(), uuid = 0, windowData = {};
jQuery.extend({
cache: {},
expando:expando,
// The following elements throw uncatchable exceptions if you
// attempt to add expando properties to them.
noData: {
"embed": true,
"object": true,
"applet": true
},
data: function( elem, name, data ) {
if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) {
return;
}
elem = elem == window ?
windowData :
elem;
var id = elem[ expando ], cache = jQuery.cache, thisCache;
if ( !id && typeof name === "string" && data === undefined ) {
return null;
}
// Compute a unique ID for the element
if ( !id ) {
id = ++uuid;
}
// Avoid generating a new cache unless none exists and we
// want to manipulate it.
if ( typeof name === "object" ) {
elem[ expando ] = id;
thisCache = cache[ id ] = jQuery.extend(true, {}, name);
} else if ( !cache[ id ] ) {
elem[ expando ] = id;
cache[ id ] = {};
}
thisCache = cache[ id ];
// Prevent overriding the named cache with undefined values
if ( data !== undefined ) {
thisCache[ name ] = data;
}
return typeof name === "string" ? thisCache[ name ] : thisCache;
},
removeData: function( elem, name ) {
if ( elem.nodeName && jQuery.noData[elem.nodeName.toLowerCase()] ) {
return;
}
elem = elem == window ?
windowData :
elem;
var id = elem[ expando ], cache = jQuery.cache, thisCache = cache[ id ];
// If we want to remove a specific section of the element's data
if ( name ) {
if ( thisCache ) {
// Remove the section of cache data
delete thisCache[ name ];
// If we've removed all the data, remove the element's cache
if ( jQuery.isEmptyObject(thisCache) ) {
jQuery.removeData( elem );
}
}
// Otherwise, we want to remove all of the element's data
} else {
if ( jQuery.support.deleteExpando ) {
delete elem[ jQuery.expando ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( jQuery.expando );
}
// Completely remove the data cache
delete cache[ id ];
}
}
});
jQuery.fn.extend({
data: function( key, value ) {
if ( typeof key === "undefined" && this.length ) {
return jQuery.data( this[0] );
} 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 ) {
var data = this.triggerHandler("getData" + parts[1] + "!", [parts[0]]);
if ( data === undefined && this.length ) {
data = jQuery.data( this[0], key );
}
return data === undefined && parts[1] ?
this.data( parts[0] ) :
data;
} else {
return this.trigger("setData" + parts[1] + "!", [parts[0], value]).each(function() {
jQuery.data( this, key, value );
});
}
},
removeData: function( key ) {
return this.each(function() {
jQuery.removeData( this, key );
});
}
});
jQuery.extend({
queue: function( elem, type, data ) {
if ( !elem ) {
return;
}
type = (type || "fx") + "queue";
var q = jQuery.data( elem, type );
// Speed up dequeue by getting out quickly if this is just a lookup
if ( !data ) {
return q || [];
}
if ( !q || jQuery.isArray(data) ) {
q = jQuery.data( elem, type, jQuery.makeArray(data) );
} else {
q.push( data );
}
return q;
},
dequeue: function( elem, type ) {
type = type || "fx";
var queue = jQuery.queue( elem, type ), fn = queue.shift();
// If the fx queue is dequeued, always remove the progress sentinel
if ( fn === "inprogress" ) {
fn = queue.shift();
}
if ( fn ) {
// Add a progress sentinel to prevent the fx queue from being
// automatically dequeued
if ( type === "fx" ) {
queue.unshift("inprogress");
}
fn.call(elem, function() {
jQuery.dequeue(elem, type);
});
}
}
});
jQuery.fn.extend({
queue: function( type, data ) {
if ( typeof type !== "string" ) {
data = type;
type = "fx";
}
if ( data === undefined ) {
return jQuery.queue( this[0], type );
}
return this.each(function( i, elem ) {
var queue = jQuery.queue( this, type, data );
if ( type === "fx" && queue[0] !== "inprogress" ) {
jQuery.dequeue( this, type );
}
});
},
dequeue: function( type ) {
return this.each(function() {
jQuery.dequeue( this, type );
});
},
// Based off of the plugin by Clint Helfers, with permission.
// http://blindsignals.com/index.php/2009/07/jquery-delay/
delay: function( time, type ) {
time = jQuery.fx ? jQuery.fx.speeds[time] || time : time;
type = type || "fx";
return this.queue( type, function() {
var elem = this;
setTimeout(function() {
jQuery.dequeue( elem, type );
}, time );
});
},
clearQueue: function( type ) {
return this.queue( type || "fx", [] );
}
});
var rclass = /[\n\t]/g,
rspace = /\s+/,
rreturn = /\r/g,
rspecialurl = /href|src|style/,
rtype = /(button|input)/i,
rfocusable = /(button|input|object|select|textarea)/i,
rclickable = /^(a|area)$/i,
rradiocheck = /radio|checkbox/;
jQuery.fn.extend({
attr: function( name, value ) {
return 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( rspace );
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(rspace);
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( rspace );
while ( (className = classNames[ i++ ]) ) {
// check each className given, space seperated list
state = isBool ? state : !self.hasClass( className );
self[ state ? "addClass" : "removeClass" ]( className );
}
} else if ( type === "undefined" || type === "boolean" ) {
if ( this.className ) {
// store className if set
jQuery.data( this, "__className__", this.className );
}
// toggle whole className
this.className = this.className || value === false ? "" : jQuery.data( this, "__className__" ) || "";
}
});
},
hasClass: function( selector ) {
var className = " " + selector + " ";
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 ( value === undefined ) {
var elem = this[0];
if ( elem ) {
if ( jQuery.nodeName( elem, "option" ) ) {
return (elem.attributes.value || {}).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 ];
if ( option.selected ) {
// Get the specifc value for the option
value = jQuery(option).val();
// We don't need an array for one selects
if ( one ) {
return value;
}
// Multi-Selects return an array
values.push( value );
}
}
return values;
}
// Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified
if ( rradiocheck.test( elem.type ) && !jQuery.support.checkOn ) {
return elem.getAttribute("value") === null ? "on" : elem.value;
}
// Everything else, we just grab the value
return (elem.value || "").replace(rreturn, "");
}
return undefined;
}
var isFunction = jQuery.isFunction(value);
return this.each(function(i) {
var self = jQuery(this), val = value;
if ( this.nodeType !== 1 ) {
return;
}
if ( isFunction ) {
val = value.call(this, i, self.val());
}
// Typecast each time if the value is a Function and the appended
// value is therefore different each time.
if ( typeof val === "number" ) {
val += "";
}
if ( jQuery.isArray(val) && rradiocheck.test( this.type ) ) {
this.checked = jQuery.inArray( self.val(), val ) >= 0;
} else if ( jQuery.nodeName( this, "select" ) ) {
var values = jQuery.makeArray(val);
jQuery( "option", this ).each(function() {
this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0;
});
if ( !values.length ) {
this.selectedIndex = -1;
}
} else {
this.value = val;
}
});
}
});
jQuery.extend({
attrFn: {
val: true,
css: true,
html: true,
text: true,
data: true,
width: true,
height: true,
offset: true
},
attr: function( elem, name, value, pass ) {
// don't set attributes on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) {
return undefined;
}
if ( pass && name in jQuery.attrFn ) {
return jQuery(elem)[name](value);
}
var notxml = elem.nodeType !== 1 || !jQuery.isXMLDoc( elem ),
// Whether we are setting (or getting)
set = value !== undefined;
// Try to normalize/fix the name
name = notxml && jQuery.props[ name ] || name;
// 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
if ( name in elem && 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" );
}
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 );
}
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;
}
// elem is actually elem.style ... set the style
// Using attr for specific style information is now deprecated. Use style instead.
return jQuery.style( elem, name, value );
}
});
var rnamespaces = /\.(.*)$/,
fcleanup = function( nm ) {
return nm.replace(/[^\w\s\.\|`]/g, function( ch ) {
return "\\" + ch;
});
};
/*
* A number of helper functions used for managing events.
* Many of the ideas behind this code originated from
* Dean Edwards' addEvent library.
*/
jQuery.event = {
// Bind an event to an element
// Original by Dean Edwards
add: function( elem, types, handler, data ) {
if ( elem.nodeType === 3 || elem.nodeType === 8 ) {
return;
}
// For whatever reason, IE has trouble passing the window object
// around, causing it to be cloned in the process
if ( elem.setInterval && ( elem !== window && !elem.frameElement ) ) {
elem = window;
}
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 = elemData.events || {},
eventHandle = elemData.handle, eventHandle;
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;
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;
}
var ret, type, fn, i = 0, all, namespaces, namespace, special, eventType, handleObj, origType,
elemData = 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 ( var 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 ( var 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 ) {
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 );
}
}
},
// 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[expando] ? event :
// Object literal
jQuery.extend( jQuery.Event(type), event ) :
// Just the event type (string)
jQuery.Event(type);
if ( type.indexOf("!") >= 0 ) {
event.type = type = type.slice(0, -1);
event.exclusive = true;
}
// Handle a global trigger
if ( !elem ) {
// Don't bubble custom events when global (to avoid too much overhead)
event.stopPropagation();
// Only trigger if we've ever bound an event for it
if ( jQuery.event.global[ type ] ) {
jQuery.each( jQuery.cache, function() {
if ( this.events && this.events[type] ) {
jQuery.event.trigger( event, data, this.handle.elem );
}
});
}
}
// Handle triggering a single element
// don't do events on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) {
return undefined;
}
// Clean up in case it is reused
event.result = undefined;
event.target = elem;
// Clone the incoming data, if any
data = jQuery.makeArray( data );
data.unshift( event );
}
event.currentTarget = elem;
// Trigger the event, it is assumed that "handle" is a function
var handle = 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;
}
}
// prevent IE from throwing an error for some elements with some event types, see #3533
} catch (e) {}
if ( !event.isPropagationStopped() && parent ) {
jQuery.event.trigger( event, data, parent, true );
} else if ( !event.isDefaultPrevented() ) {
var target = event.target, old,
isClick = jQuery.nodeName(target, "a") && type === "click",
special = jQuery.event.special[ type ] || {};
if ( (!special._default || special._default.call( elem, event ) === false) &&
!isClick && !(target && target.nodeName && jQuery.noData[target.nodeName.toLowerCase()]) ) {
try {
if ( target[ type ] ) {
// Make sure that we don't accidentally re-trigger the onFOO events
old = target[ "on" + type ];
if ( old ) {
target[ "on" + type ] = null;
}
jQuery.event.triggered = true;
target[ type ]();
}
// prevent IE from throwing an error for some elements with some event types, see #3533
} catch (e) {}
if ( old ) {
target[ "on" + type ] = old;
}
jQuery.event.triggered = false;
}
}
},
handle: function( event ) {
var all, handlers, namespaces, namespace, events;
event = arguments[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 = new RegExp("(^|\\.)" + namespaces.slice(0).sort().join("\\.(?:.*\\.)?") + "(\\.|$)");
}
var 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.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, arguments );
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 originalTarget pageX pageY prevValue relatedNode relatedTarget screenX screenY shiftKey srcElement target toElement view wheelDelta which".split(" "),
fix: function( event ) {
if ( event[ 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 ) {
event.target = event.srcElement || document; // Fixes #1925 where srcElement might not be defined either
}
// 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 && ((event.charCode || event.charCode === 0) ? event.charCode : event.keyCode) ) {
event.which = 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, handleObj.origType, jQuery.extend({}, handleObj, {handler: liveHandler}) );
},
remove: function( handleObj ) {
var remove = true,
type = handleObj.origType.replace(rnamespaces, "");
jQuery.each( jQuery.data(this, "events").live || [], function() {
if ( type === this.origType.replace(rnamespaces, "") ) {
remove = false;
return false;
}
});
if ( remove ) {
jQuery.event.remove( this, handleObj.origType, liveHandler );
}
}
},
beforeunload: {
setup: function( data, namespaces, eventHandle ) {
// We only want to do this special case on windows
if ( this.setInterval ) {
this.onbeforeunload = eventHandle;
}
return false;
},
teardown: function( namespaces, eventHandle ) {
if ( this.onbeforeunload === eventHandle ) {
this.onbeforeunload = null;
}
}
}
}
};
var removeEvent = document.removeEventListener ?
function( elem, type, handle ) {
elem.removeEventListener( type, handle, false );
} :
function( elem, type, handle ) {
elem.detachEvent( "on" + type, handle );
};
jQuery.Event = function( src ) {
// Allow instantiation without the 'new' keyword
if ( !this.preventDefault ) {
return new jQuery.Event( src );
}
// Event object
if ( src && src.type ) {
this.originalEvent = src;
this.type = src.type;
// Event type
} else {
this.type = src;
}
// timeStamp is buggy for some events on Firefox(#3843)
// So we won't rely on the native value
this.timeStamp = now();
// Mark it as fixed
this[ 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)
e.returnValue = false;
},
stopPropagation: function() {
this.isPropagationStopped = returnTrue;
var e = this.originalEvent;
if ( !e ) {
return;
}
// if stopPropagation exists run it on the original event
if ( e.stopPropagation ) {
e.stopPropagation();
}
// otherwise set the cancelBubble property of the original event to true (IE)
e.cancelBubble = true;
},
stopImmediatePropagation: function() {
this.isImmediatePropagationStopped = returnTrue;
this.stopPropagation();
},
isDefaultPrevented: returnFalse,
isPropagationStopped: returnFalse,
isImmediatePropagationStopped: returnFalse
};
// Checks if an event happened on an element within another element
// Used in jQuery.event.special.mouseenter and mouseleave handlers
var withinElement = function( event ) {
// Check if mouse(over|out) are still within the same parent element
var parent = event.relatedTarget;
// Firefox sometimes assigns relatedTarget a XUL element
// which we cannot access the parentNode property of
try {
// Traverse up the tree
while ( parent && parent !== this ) {
parent = parent.parentNode;
}
if ( parent !== this ) {
// set the correct event type
event.type = event.data;
// handle event if we actually just moused on to a non sub-element
jQuery.event.handle.apply( this, arguments );
}
// assuming we've left the element since we most likely mousedover a xul element
} catch(e) { }
},
// In case of event delegation, we only need to rename the event.type,
// liveHandler will take care of the rest.
delegate = function( event ) {
event.type = event.data;
jQuery.event.handle.apply( this, arguments );
};
// Create mouseenter and mouseleave events
jQuery.each({
mouseenter: "mouseover",
mouseleave: "mouseout"
}, function( orig, fix ) {
jQuery.event.special[ orig ] = {
setup: function( data ) {
jQuery.event.add( this, fix, data && data.selector ? delegate : withinElement, orig );
},
teardown: function( data ) {
jQuery.event.remove( this, fix, data && data.selector ? delegate : withinElement );
}
};
});
// submit delegation
if ( !jQuery.support.submitBubbles ) {
jQuery.event.special.submit = {
setup: function( data, namespaces ) {
if ( this.nodeName.toLowerCase() !== "form" ) {
jQuery.event.add(this, "click.specialSubmit", function( e ) {
var elem = e.target, type = elem.type;
if ( (type === "submit" || type === "image") && jQuery( elem ).closest("form").length ) {
return trigger( "submit", this, arguments );
}
});
jQuery.event.add(this, "keypress.specialSubmit", function( e ) {
var elem = e.target, type = elem.type;
if ( (type === "text" || type === "password") && jQuery( elem ).closest("form").length && e.keyCode === 13 ) {
return trigger( "submit", this, arguments );
}
});
} else {
return false;
}
},
teardown: function( namespaces ) {
jQuery.event.remove( this, ".specialSubmit" );
}
};
}
// change delegation, happens here so we have bind.
if ( !jQuery.support.changeBubbles ) {
var formElems = /textarea|input|select/i,
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 ( !formElems.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";
return jQuery.event.trigger( e, arguments[1], elem );
}
};
jQuery.event.special.change = {
filters: {
focusout: testChange,
click: function( e ) {
var elem = e.target, type = elem.type;
if ( type === "radio" || type === "checkbox" || elem.nodeName.toLowerCase() === "select" ) {
return testChange.call( this, e );
}
},
// Change has to be called before submit
// Keydown will be called before keypress, which is used in submit-event delegation
keydown: function( e ) {
var elem = e.target, type = elem.type;
if ( (e.keyCode === 13 && elem.nodeName.toLowerCase() !== "textarea") ||
(e.keyCode === 32 && (type === "checkbox" || type === "radio")) ||
type === "select-multiple" ) {
return testChange.call( this, e );
}
},
// Beforeactivate happens also before the previous element is blurred
// with this event you can't trigger a change event, but you can store
// information/focus[in] is not needed anymore
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 formElems.test( this.nodeName );
},
teardown: function( namespaces ) {
jQuery.event.remove( this, ".specialChange" );
return formElems.test( this.nodeName );
}
};
changeFilters = jQuery.event.special.change.filters;
}
function trigger( type, elem, args ) {
args[0].type = type;
return jQuery.event.handle.apply( elem, args );
}
// Create "bubbling" focus and blur events
if ( document.addEventListener ) {
jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) {
jQuery.event.special[ fix ] = {
setup: function() {
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 ) ) {
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 ( 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
context.each(function(){
jQuery.event.add( this, liveConvert( type, selector ),
{ data: data, selector: selector, handler: fn, origType: type, origHandler: fn, preType: preType } );
});
} else {
// unbind live handler
context.unbind( liveConvert( type, selector ), fn );
}
}
return this;
}
});
function liveHandler( event ) {
var stop, elems = [], selectors = [], args = arguments,
related, match, handleObj, elem, j, i, l, data,
events = jQuery.data( this, "events" );
// Make sure we avoid non-left-click bubbling in Firefox (#3861)
if ( event.liveFired === this || !events || !events.live || event.button && event.type === "click" ) {
return;
}
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++ ) {
for ( j = 0; j < live.length; j++ ) {
handleObj = live[j];
if ( match[i].selector === handleObj.selector ) {
elem = match[i].elem;
related = null;
// Those two events require additional checking
if ( handleObj.preType === "mouseenter" || handleObj.preType === "mouseleave" ) {
related = jQuery( event.relatedTarget ).closest( handleObj.selector )[0];
}
if ( !related || related !== elem ) {
elems.push({ elem: elem, handleObj: handleObj });
}
}
}
}
for ( i = 0, l = elems.length; i < l; i++ ) {
match = elems[i];
event.currentTarget = match.elem;
event.data = match.handleObj.data;
event.handleObj = match.handleObj;
if ( match.handleObj.origHandler.apply( match.elem, args ) === false ) {
stop = false;
break;
}
}
return stop;
}
function liveConvert( type, selector ) {
return "live." + (type && type !== "*" ? type + "." : "") + selector.replace(/\./g, "`").replace(/ /g, "&");
}
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( fn ) {
return fn ? this.bind( name, fn ) : this.trigger( name );
};
if ( jQuery.attrFn ) {
jQuery.attrFn[ name ] = true;
}
});
// Prevent memory leaks in IE
// Window isn't included so as not to unbind existing unload events
// More info:
// - http://isaacschlueter.com/2006/10/msie-memory-leaks/
if ( window.attachEvent && !window.addEventListener ) {
window.attachEvent("onunload", function() {
for ( var id in jQuery.cache ) {
if ( jQuery.cache[ id ].handle ) {
// Try/Catch is to handle iframes being unloaded, see #4280
try {
jQuery.event.remove( jQuery.cache[ id ].handle.elem );
} catch(e) {}
}
}
});
}
/*!
* Sizzle CSS Selector Engine - v1.0
* Copyright 2009, The Dojo Foundation
* Released under the MIT, BSD, and GPL Licenses.
* More information: http://sizzlejs.com/
*/
(function(){
var chunker = /((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^[\]]*\]|['"][^'"]*['"]|[^[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,
done = 0,
toString = Object.prototype.toString,
hasDuplicate = false,
baseHasDuplicate = true;
// Here we check if the JavaScript engine is using some sort of
// optimization where it does not always call our comparision
// function. If that is the case, discard the hasDuplicate value.
// Thus far that includes Google Chrome.
[0, 0].sort(function(){
baseHasDuplicate = false;
return 0;
});
var Sizzle = function(selector, context, results, seed) {
results = results || [];
var origContext = context = context || document;
if ( context.nodeType !== 1 && context.nodeType !== 9 ) {
return [];
}
if ( !selector || typeof selector !== "string" ) {
return results;
}
var parts = [], m, set, checkSet, extra, prune = true, contextXML = isXML(context),
soFar = selector;
// Reset the position of the chunker regexp (start from head)
while ( (chunker.exec(""), m = chunker.exec(soFar)) !== null ) {
soFar = m[3];
parts.push( m[1] );
if ( m[2] ) {
extra = m[3];
break;
}
}
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]) ) {
var ret = Sizzle.find( parts.shift(), context, contextXML );
context = ret.expr ? Sizzle.filter( ret.expr, ret.set )[0] : ret.set[0];
}
if ( context ) {
var 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 ) {
var 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 ( var i = 0; checkSet[i] != null; i++ ) {
if ( checkSet[i] && (checkSet[i] === true || checkSet[i].nodeType === 1 && contains(context, checkSet[i])) ) {
results.push( set[i] );
}
}
} else {
for ( var 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.find = function(expr, context, isXML){
var set, match;
if ( !expr ) {
return [];
}
for ( var i = 0, l = Expr.order.length; i < l; i++ ) {
var type = Expr.order[i], match;
if ( (match = Expr.leftMatch[ type ].exec( expr )) ) {
var left = match[1];
match.splice(1,1);
if ( left.substr( left.length - 1 ) !== "\\" ) {
match[1] = (match[1] || "").replace(/\\/g, "");
set = Expr.find[ type ]( match, context, isXML );
if ( set != null ) {
expr = expr.replace( Expr.match[ type ], "" );
break;
}
}
}
}
if ( !set ) {
set = context.getElementsByTagName("*");
}
return {set: set, expr: expr};
};
Sizzle.filter = function(expr, set, inplace, not){
var old = expr, result = [], curLoop = set, match, anyFound,
isXMLFilter = set && set[0] && isXML(set[0]);
while ( expr && set.length ) {
for ( var type in Expr.filter ) {
if ( (match = Expr.leftMatch[ type ].exec( expr )) != null && match[2] ) {
var filter = Expr.filter[ type ], found, item, left = match[1];
anyFound = false;
match.splice(1,1);
if ( left.substr( left.length - 1 ) === "\\" ) {
continue;
}
if ( curLoop === result ) {
result = [];
}
if ( Expr.preFilter[ type ] ) {
match = Expr.preFilter[ type ]( match, curLoop, inplace, result, not, isXMLFilter );
if ( !match ) {
anyFound = found = true;
} else if ( match === true ) {
continue;
}
}
if ( match ) {
for ( var i = 0; (item = curLoop[i]) != null; i++ ) {
if ( item ) {
found = filter( item, match, i, curLoop );
var pass = not ^ !!found;
if ( inplace && found != null ) {
if ( pass ) {
anyFound = true;
} else {
curLoop[i] = false;
}
} else if ( pass ) {
result.push( item );
anyFound = true;
}
}
}
}
if ( found !== undefined ) {
if ( !inplace ) {
curLoop = result;
}
expr = expr.replace( Expr.match[ type ], "" );
if ( !anyFound ) {
return [];
}
break;
}
}
}
// Improper expression
if ( expr === old ) {
if ( anyFound == null ) {
Sizzle.error( expr );
} else {
break;
}
}
old = expr;
}
return curLoop;
};
Sizzle.error = function( msg ) {
throw "Syntax error, unrecognized expression: " + msg;
};
var Expr = Sizzle.selectors = {
order: [ "ID", "NAME", "TAG" ],
match: {
ID: /#((?:[\w\u00c0-\uFFFF-]|\\.)+)/,
CLASS: /\.((?:[\w\u00c0-\uFFFF-]|\\.)+)/,
NAME: /\[name=['"]*((?:[\w\u00c0-\uFFFF-]|\\.)+)['"]*\]/,
ATTR: /\[\s*((?:[\w\u00c0-\uFFFF-]|\\.)+)\s*(?:(\S?=)\s*(['"]*)(.*?)\3|)\s*\]/,
TAG: /^((?:[\w\u00c0-\uFFFF\*-]|\\.)+)/,
CHILD: /:(only|nth|last|first)-child(?:\((even|odd|[\dn+-]*)\))?/,
POS: /:(nth|eq|gt|lt|first|last|even|odd)(?:\((\d*)\))?(?=[^-]|$)/,
PSEUDO: /:((?:[\w\u00c0-\uFFFF-]|\\.)+)(?:\((['"]?)((?:\([^\)]+\)|[^\(\)]*)+)\2\))?/
},
leftMatch: {},
attrMap: {
"class": "className",
"for": "htmlFor"
},
attrHandle: {
href: function(elem){
return elem.getAttribute("href");
}
},
relative: {
"+": function(checkSet, part){
var isPartStr = typeof part === "string",
isTag = isPartStr && !/\W/.test(part),
isPartStrNotTag = isPartStr && !isTag;
if ( isTag ) {
part = part.toLowerCase();
}
for ( var i = 0, l = checkSet.length, elem; i < l; i++ ) {
if ( (elem = checkSet[i]) ) {
while ( (elem = elem.previousSibling) && elem.nodeType !== 1 ) {}
checkSet[i] = isPartStrNotTag || elem && elem.nodeName.toLowerCase() === part ?
elem || false :
elem === part;
}
}
if ( isPartStrNotTag ) {
Sizzle.filter( part, checkSet, true );
}
},
">": function(checkSet, part){
var isPartStr = typeof part === "string";
if ( isPartStr && !/\W/.test(part) ) {
part = part.toLowerCase();
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
var parent = elem.parentNode;
checkSet[i] = parent.nodeName.toLowerCase() === part ? parent : false;
}
}
} else {
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var 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 doneName = done++, checkFn = dirCheck;
if ( typeof part === "string" && !/\W/.test(part) ) {
var nodeCheck = part = part.toLowerCase();
checkFn = dirNodeCheck;
}
checkFn("parentNode", part, doneName, checkSet, nodeCheck, isXML);
},
"~": function(checkSet, part, isXML){
var doneName = done++, checkFn = dirCheck;
if ( typeof part === "string" && !/\W/.test(part) ) {
var nodeCheck = part = part.toLowerCase();
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]);
return m ? [m] : [];
}
},
NAME: function(match, context){
if ( typeof context.getElementsByName !== "undefined" ) {
var ret = [], results = context.getElementsByName(match[1]);
for ( var i = 0, l = results.length; i < l; i++ ) {
if ( results[i].getAttribute("name") === match[1] ) {
ret.push( results[i] );
}
}
return ret.length === 0 ? null : ret;
}
},
TAG: function(match, context){
return context.getElementsByTagName(match[1]);
}
},
preFilter: {
CLASS: function(match, curLoop, inplace, result, not, isXML){
match = " " + match[1].replace(/\\/g, "") + " ";
if ( isXML ) {
return match;
}
for ( var i = 0, elem; (elem = curLoop[i]) != null; i++ ) {
if ( elem ) {
if ( not ^ (elem.className && (" " + elem.className + " ").replace(/[\t\n]/g, " ").indexOf(match) >= 0) ) {
if ( !inplace ) {
result.push( elem );
}
} else if ( inplace ) {
curLoop[i] = false;
}
}
}
return false;
},
ID: function(match){
return match[1].replace(/\\/g, "");
},
TAG: function(match, curLoop){
return match[1].toLowerCase();
},
CHILD: function(match){
if ( match[1] === "nth" ) {
// parse equations like 'even', 'odd', '5', '2n', '3n+2', '4n-1', '-n+6'
var test = /(-?)(\d*)n((?:\+|-)?\d*)/.exec(
match[2] === "even" && "2n" || match[2] === "odd" && "2n+1" ||
!/\D/.test( match[2] ) && "0n+" + match[2] || match[2]);
// calculate the numbers (first)n+(last) including if they are negative
match[2] = (test[1] + (test[2] || 1)) - 0;
match[3] = test[3] - 0;
}
// TODO: Move to normal caching system
match[0] = done++;
return match;
},
ATTR: function(match, curLoop, inplace, result, not, isXML){
var name = match[1].replace(/\\/g, "");
if ( !isXML && Expr.attrMap[name] ) {
match[1] = Expr.attrMap[name];
}
if ( match[2] === "~=" ) {
match[4] = " " + match[4] + " ";
}
return match;
},
PSEUDO: function(match, curLoop, inplace, result, not){
if ( match[1] === "not" ) {
// If we're dealing with a complex expression, or a simple one
if ( ( chunker.exec(match[3]) || "" ).length > 1 || /^\w/.test(match[3]) ) {
match[3] = Sizzle(match[3], null, null, curLoop);
} else {
var ret = Sizzle.filter(match[3], curLoop, inplace, true ^ not);
if ( !inplace ) {
result.push.apply( result, ret );
}
return false;
}
} else if ( Expr.match.POS.test( match[0] ) || Expr.match.CHILD.test( match[0] ) ) {
return true;
}
return match;
},
POS: function(match){
match.unshift( true );
return match;
}
},
filters: {
enabled: function(elem){
return elem.disabled === false && elem.type !== "hidden";
},
disabled: function(elem){
return elem.disabled === true;
},
checked: function(elem){
return elem.checked === true;
},
selected: function(elem){
// Accessing this property makes selected-by-default
// options in Safari work properly
elem.parentNode.selectedIndex;
return elem.selected === true;
},
parent: function(elem){
return !!elem.firstChild;
},
empty: function(elem){
return !elem.firstChild;
},
has: function(elem, i, match){
return !!Sizzle( match[3], elem ).length;
},
header: function(elem){
return /h\d/i.test( elem.nodeName );
},
text: function(elem){
return "text" === elem.type;
},
radio: function(elem){
return "radio" === elem.type;
},
checkbox: function(elem){
return "checkbox" === elem.type;
},
file: function(elem){
return "file" === elem.type;
},
password: function(elem){
return "password" === elem.type;
},
submit: function(elem){
return "submit" === elem.type;
},
image: function(elem){
return "image" === elem.type;
},
reset: function(elem){
return "reset" === elem.type;
},
button: function(elem){
return "button" === elem.type || elem.nodeName.toLowerCase() === "button";
},
input: function(elem){
return /input|select|textarea|button/i.test(elem.nodeName);
}
},
setFilters: {
first: function(elem, i){
return i === 0;
},
last: function(elem, i, match, array){
return i === array.length - 1;
},
even: function(elem, i){
return i % 2 === 0;
},
odd: function(elem, i){
return i % 2 === 1;
},
lt: function(elem, i, match){
return i < match[3] - 0;
},
gt: function(elem, i, match){
return i > match[3] - 0;
},
nth: function(elem, i, match){
return match[3] - 0 === i;
},
eq: function(elem, i, match){
return match[3] - 0 === i;
}
},
filter: {
PSEUDO: function(elem, match, i, array){
var name = match[1], filter = Expr.filters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
} else if ( name === "contains" ) {
return (elem.textContent || elem.innerText || getText([ elem ]) || "").indexOf(match[3]) >= 0;
} else if ( name === "not" ) {
var not = match[3];
for ( var i = 0, l = not.length; i < l; i++ ) {
if ( not[i] === elem ) {
return false;
}
}
return true;
} else {
Sizzle.error( "Syntax error, unrecognized expression: " + name );
}
},
CHILD: function(elem, match){
var type = match[1], node = elem;
switch (type) {
case 'only':
case 'first':
while ( (node = node.previousSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
if ( type === "first" ) {
return true;
}
node = elem;
case 'last':
while ( (node = node.nextSibling) ) {
if ( node.nodeType === 1 ) {
return false;
}
}
return true;
case 'nth':
var first = match[2], last = match[3];
if ( first === 1 && last === 0 ) {
return true;
}
var doneName = match[0],
parent = elem.parentNode;
if ( parent && (parent.sizcache !== doneName || !elem.nodeIndex) ) {
var count = 0;
for ( node = parent.firstChild; node; node = node.nextSibling ) {
if ( node.nodeType === 1 ) {
node.nodeIndex = ++count;
}
}
parent.sizcache = doneName;
}
var diff = elem.nodeIndex - last;
if ( first === 0 ) {
return diff === 0;
} else {
return ( diff % first === 0 && diff / first >= 0 );
}
}
},
ID: function(elem, match){
return elem.nodeType === 1 && elem.getAttribute("id") === match;
},
TAG: function(elem, match){
return (match === "*" && elem.nodeType === 1) || elem.nodeName.toLowerCase() === match;
},
CLASS: function(elem, match){
return (" " + (elem.className || elem.getAttribute("class")) + " ")
.indexOf( match ) > -1;
},
ATTR: function(elem, match){
var name = match[1],
result = Expr.attrHandle[ name ] ?
Expr.attrHandle[ name ]( elem ) :
elem[ name ] != null ?
elem[ name ] :
elem.getAttribute( name ),
value = result + "",
type = match[2],
check = match[4];
return result == null ?
type === "!=" :
type === "=" ?
value === check :
type === "*=" ?
value.indexOf(check) >= 0 :
type === "~=" ?
(" " + value + " ").indexOf(check) >= 0 :
!check ?
value && result !== false :
type === "!=" ?
value !== check :
type === "^=" ?
value.indexOf(check) === 0 :
type === "$=" ?
value.substr(value.length - check.length) === check :
type === "|=" ?
value === check || value.substr(0, check.length + 1) === check + "-" :
false;
},
POS: function(elem, match, i, array){
var name = match[2], filter = Expr.setFilters[ name ];
if ( filter ) {
return filter( elem, i, match, array );
}
}
}
};
var origPOS = Expr.match.POS;
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, function(all, num){
return "\\" + (num - 0 + 1);
}));
}
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 ret = results || [];
if ( toString.call(array) === "[object Array]" ) {
Array.prototype.push.apply( ret, array );
} else {
if ( typeof array.length === "number" ) {
for ( var i = 0, l = array.length; i < l; i++ ) {
ret.push( array[i] );
}
} else {
for ( var i = 0; array[i]; i++ ) {
ret.push( array[i] );
}
}
}
return ret;
};
}
var sortOrder;
if ( document.documentElement.compareDocumentPosition ) {
sortOrder = function( a, b ) {
if ( !a.compareDocumentPosition || !b.compareDocumentPosition ) {
if ( a == b ) {
hasDuplicate = true;
}
return a.compareDocumentPosition ? -1 : 1;
}
var ret = a.compareDocumentPosition(b) & 4 ? -1 : a === b ? 0 : 1;
if ( ret === 0 ) {
hasDuplicate = true;
}
return ret;
};
} else if ( "sourceIndex" in document.documentElement ) {
sortOrder = function( a, b ) {
if ( !a.sourceIndex || !b.sourceIndex ) {
if ( a == b ) {
hasDuplicate = true;
}
return a.sourceIndex ? -1 : 1;
}
var ret = a.sourceIndex - b.sourceIndex;
if ( ret === 0 ) {
hasDuplicate = true;
}
return ret;
};
} else if ( document.createRange ) {
sortOrder = function( a, b ) {
if ( !a.ownerDocument || !b.ownerDocument ) {
if ( a == b ) {
hasDuplicate = true;
}
return a.ownerDocument ? -1 : 1;
}
var aRange = a.ownerDocument.createRange(), bRange = b.ownerDocument.createRange();
aRange.setStart(a, 0);
aRange.setEnd(a, 0);
bRange.setStart(b, 0);
bRange.setEnd(b, 0);
var ret = aRange.compareBoundaryPoints(Range.START_TO_END, bRange);
if ( ret === 0 ) {
hasDuplicate = true;
}
return ret;
};
}
// Utility function for retreiving the text value of an array of DOM nodes
function getText( 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 += 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();
form.innerHTML = "<a name='" + id + "'/>";
// Inject it into the root element, check its status, and remove it quickly
var root = document.documentElement;
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 );
root = form = null; // release memory in IE
})();
(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);
};
}
div = null; // release memory in IE
})();
if ( document.querySelectorAll ) {
(function(){
var oldSizzle = Sizzle, div = document.createElement("div");
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 && context.nodeType === 9 && !isXML(context) ) {
try {
return makeArray( context.querySelectorAll(query), extra );
} catch(e){}
}
return oldSizzle(query, context, extra, seed);
};
for ( var prop in oldSizzle ) {
Sizzle[ prop ] = oldSizzle[ prop ];
}
div = null; // release memory in IE
})();
}
(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]);
}
};
div = null; // release memory in IE
})();
function dirNodeCheck( dir, cur, doneName, checkSet, nodeCheck, isXML ) {
for ( var i = 0, l = checkSet.length; i < l; i++ ) {
var elem = checkSet[i];
if ( elem ) {
elem = elem[dir];
var match = false;
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 ) {
elem = elem[dir];
var match = false;
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;
}
}
}
var contains = document.compareDocumentPosition ? function(a, b){
return !!(a.compareDocumentPosition(b) & 16);
} : function(a, b){
return a !== b && (a.contains ? a.contains(b) : true);
};
var 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 tmpSet = [], later = "", match,
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 = getText;
jQuery.isXMLDoc = isXML;
jQuery.contains = contains;
return;
window.Sizzle = Sizzle;
})();
var runtil = /Until$/,
rparentsprev = /^(?:parents|prevUntil|prevAll)/,
// Note: This RegExp should be improved, or likely pulled from Sizzle
rmultiselector = /,/,
slice = Array.prototype.slice;
// Implement the identical functionality for filter and not
var winnow = function( elements, qualifier, keep ) {
if ( jQuery.isFunction( qualifier ) ) {
return jQuery.grep(elements, function( elem, i ) {
return !!qualifier.call( elem, i, elem ) === 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;
});
};
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 ) {
if ( jQuery.isArray( selectors ) ) {
var ret = [], cur = this[0], match, matches = {}, selector;
if ( cur && selectors.length ) {
for ( var 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 });
delete matches[selector];
}
}
cur = cur.parentNode;
}
}
return ret;
}
var pos = jQuery.expr.match.POS.test( selectors ) ?
jQuery( selectors, context || this.context ) : null;
return this.map(function( i, cur ) {
while ( cur && cur.ownerDocument && cur !== context ) {
if ( pos ? pos.index(cur) > -1 : jQuery(cur).is(selectors) ) {
return cur;
}
cur = cur.parentNode;
}
return null;
});
},
// Determine the position of an element within
// the matched set of elements
index: function( elem ) {
if ( !elem || typeof elem === "string" ) {
return jQuery.inArray( this[0],
// If it receives a string, the selector is used
// If it receives nothing, the siblings are used
elem ? jQuery( elem ) : this.parent().children() );
}
// Locate the position of the desired element
return jQuery.inArray(
// If it receives a jQuery object, the first element is used
elem.jquery ? elem[0] : elem, this );
},
add: function( selector, context ) {
var set = typeof selector === "string" ?
jQuery( selector, context || this.context ) :
jQuery.makeArray( selector ),
all = jQuery.merge( this.get(), set );
return this.pushStack( isDisconnected( set[0] ) || isDisconnected( all[0] ) ?
all :
jQuery.unique( all ) );
},
andSelf: function() {
return this.add( this.prevObject );
}
});
// A painfully simple check to see if an element is disconnected
// from a document (should be improved, where feasible).
function isDisconnected( node ) {
return !node || !node.parentNode || node.parentNode.nodeType === 11;
}
jQuery.each({
parent: function( elem ) {
var parent = elem.parentNode;
return parent && parent.nodeType !== 11 ? parent : null;
},
parents: function( elem ) {
return jQuery.dir( elem, "parentNode" );
},
parentsUntil: function( elem, i, until ) {
return jQuery.dir( elem, "parentNode", until );
},
next: function( elem ) {
return jQuery.nth( elem, 2, "nextSibling" );
},
prev: function( elem ) {
return jQuery.nth( elem, 2, "previousSibling" );
},
nextAll: function( elem ) {
return jQuery.dir( elem, "nextSibling" );
},
prevAll: function( elem ) {
return jQuery.dir( elem, "previousSibling" );
},
nextUntil: function( elem, i, until ) {
return jQuery.dir( elem, "nextSibling", until );
},
prevUntil: function( elem, i, until ) {
return jQuery.dir( elem, "previousSibling", until );
},
siblings: function( elem ) {
return jQuery.sibling( elem.parentNode.firstChild, elem );
},
children: function( elem ) {
return jQuery.sibling( elem.firstChild );
},
contents: function( elem ) {
return jQuery.nodeName( elem, "iframe" ) ?
elem.contentDocument || elem.contentWindow.document :
jQuery.makeArray( elem.childNodes );
}
}, function( name, fn ) {
jQuery.fn[ name ] = function( until, selector ) {
var ret = jQuery.map( this, fn, until );
if ( !runtil.test( name ) ) {
selector = until;
}
if ( selector && typeof selector === "string" ) {
ret = jQuery.filter( selector, ret );
}
ret = this.length > 1 ? jQuery.unique( ret ) : ret;
if ( (this.length > 1 || rmultiselector.test( selector )) && rparentsprev.test( name ) ) {
ret = ret.reverse();
}
return this.pushStack( ret, name, slice.call(arguments).join(",") );
};
});
jQuery.extend({
filter: function( expr, elems, not ) {
if ( not ) {
expr = ":not(" + expr + ")";
}
return 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;
}
});
var rinlinejQuery = / jQuery\d+="(?:\d+|null)"/g,
rleadingWhitespace = /^\s+/,
rxhtmlTag = /(<([\w:]+)[^>]*?)\/>/g,
rselfClosing = /^(?:area|br|col|embed|hr|img|input|link|meta|param)$/i,
rtagName = /<([\w:]+)/,
rtbody = /<tbody/i,
rhtml = /<|&#?\w+;/,
rnocache = /<script|<object|<embed|<option|<style/i,
rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, // checked="checked" or checked (html5)
fcloseTag = function( all, front, tag ) {
return rselfClosing.test( tag ) ?
all :
front + "></" + tag + ">";
},
wrapMap = {
option: [ 1, "<select multiple='multiple'>", "</select>" ],
legend: [ 1, "<fieldset>", "</fieldset>" ],
thead: [ 1, "<table>", "</table>" ],
tr: [ 2, "<table><tbody>", "</tbody></table>" ],
td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ],
col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ],
area: [ 1, "<map>", "</map>" ],
_default: [ 0, "", "" ]
};
wrapMap.optgroup = wrapMap.option;
wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead;
wrapMap.th = wrapMap.td;
// IE can't serialize <link> and <script> tags normally
if ( !jQuery.support.htmlSerialize ) {
wrapMap._default = [ 1, "div<div>", "</div>" ];
}
jQuery.fn.extend({
text: function( text ) {
if ( jQuery.isFunction(text) ) {
return this.each(function(i) {
var self = jQuery(this);
self.text( text.call(this, i, self.text()) );
});
}
if ( typeof text !== "object" && text !== undefined ) {
return this.empty().append( (this[0] && this[0].ownerDocument || document).createTextNode( text ) );
}
return jQuery.text( this );
},
wrapAll: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapAll( html.call(this, i) );
});
}
if ( this[0] ) {
// The elements to wrap the target around
var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true);
if ( this[0].parentNode ) {
wrap.insertBefore( this[0] );
}
wrap.map(function() {
var elem = this;
while ( elem.firstChild && elem.firstChild.nodeType === 1 ) {
elem = elem.firstChild;
}
return elem;
}).append(this);
}
return this;
},
wrapInner: function( html ) {
if ( jQuery.isFunction( html ) ) {
return this.each(function(i) {
jQuery(this).wrapInner( html.call(this, i) );
});
}
return this.each(function() {
var self = jQuery( this ), contents = self.contents();
if ( contents.length ) {
contents.wrapAll( html );
} else {
self.append( html );
}
});
},
wrap: function( html ) {
return this.each(function() {
jQuery( this ).wrapAll( html );
});
},
unwrap: function() {
return this.parent().each(function() {
if ( !jQuery.nodeName( this, "body" ) ) {
jQuery( this ).replaceWith( this.childNodes );
}
}).end();
},
append: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 ) {
this.appendChild( elem );
}
});
},
prepend: function() {
return this.domManip(arguments, true, function( elem ) {
if ( this.nodeType === 1 ) {
this.insertBefore( elem, this.firstChild );
}
});
},
before: function() {
if ( this[0] && this[0].parentNode ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this );
});
} else if ( arguments.length ) {
var set = jQuery(arguments[0]);
set.push.apply( set, this.toArray() );
return this.pushStack( set, "before", arguments );
}
},
after: function() {
if ( this[0] && this[0].parentNode ) {
return this.domManip(arguments, false, function( elem ) {
this.parentNode.insertBefore( elem, this.nextSibling );
});
} else if ( arguments.length ) {
var set = this.pushStack( this, "after", arguments );
set.push.apply( set, jQuery(arguments[0]).toArray() );
return set;
}
},
// keepData is for internal use only--do not document
remove: function( selector, keepData ) {
for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
if ( !selector || jQuery.filter( selector, [ elem ] ).length ) {
if ( !keepData && elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
jQuery.cleanData( [ elem ] );
}
if ( elem.parentNode ) {
elem.parentNode.removeChild( elem );
}
}
}
return this;
},
empty: function() {
for ( var i = 0, elem; (elem = this[i]) != null; i++ ) {
// Remove element nodes and prevent memory leaks
if ( elem.nodeType === 1 ) {
jQuery.cleanData( elem.getElementsByTagName("*") );
}
// Remove any remaining nodes
while ( elem.firstChild ) {
elem.removeChild( elem.firstChild );
}
}
return this;
},
clone: function( events ) {
// Do the clone
var ret = this.map(function() {
if ( !jQuery.support.noCloneEvent && !jQuery.isXMLDoc(this) ) {
// IE copies events bound via attachEvent when
// using cloneNode. Calling detachEvent on the
// clone will also remove the events from the orignal
// In order to get around this, we use innerHTML.
// Unfortunately, this means some modifications to
// attributes in IE that are actually only stored
// as properties will not be copied (such as the
// the name attribute on an input).
var html = this.outerHTML, ownerDocument = this.ownerDocument;
if ( !html ) {
var div = ownerDocument.createElement("div");
div.appendChild( this.cloneNode(true) );
html = div.innerHTML;
}
return jQuery.clean([html.replace(rinlinejQuery, "")
// Handle the case in IE 8 where action=/test/> self-closes a tag
.replace(/=([^="'>\s]+\/)>/g, '="$1">')
.replace(rleadingWhitespace, "")], ownerDocument)[0];
} else {
return this.cloneNode(true);
}
});
// Copy the events from the original to the clone
if ( events === true ) {
cloneCopyEvent( this, ret );
cloneCopyEvent( this.find("*"), ret.find("*") );
}
// Return the cloned set
return ret;
},
html: function( value ) {
if ( value === undefined ) {
return this[0] && this[0].nodeType === 1 ?
this[0].innerHTML.replace(rinlinejQuery, "") :
null;
// See if we can take a shortcut and just use innerHTML
} else if ( typeof value === "string" && !rnocache.test( value ) &&
(jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value )) &&
!wrapMap[ (rtagName.exec( value ) || ["", ""])[1].toLowerCase() ] ) {
value = value.replace(rxhtmlTag, fcloseTag);
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), old = self.html();
self.empty().append(function(){
return value.call( this, i, old );
});
});
} 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, value = args[0], scripts = [], fragment, parent;
// 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 = buildFragment( args, this, scripts );
}
fragment = results.fragment;
if ( fragment.childNodes.length === 1 ) {
first = fragment = fragment.firstChild;
} else {
first = fragment.firstChild;
}
if ( first ) {
table = table && jQuery.nodeName( first, "tr" );
for ( var i = 0, l = this.length; i < l; i++ ) {
callback.call(
table ?
root(this[i], first) :
this[i],
i > 0 || results.cacheable || this.length > 1 ?
fragment.cloneNode(true) :
fragment
);
}
}
if ( scripts.length ) {
jQuery.each( scripts, evalScript );
}
}
return this;
function root( elem, cur ) {
return jQuery.nodeName(elem, "table") ?
(elem.getElementsByTagName("tbody")[0] ||
elem.appendChild(elem.ownerDocument.createElement("tbody"))) :
elem;
}
}
});
function cloneCopyEvent(orig, ret) {
var i = 0;
ret.each(function() {
if ( this.nodeName !== (orig[i] && orig[i].nodeName) ) {
return;
}
var oldData = jQuery.data( orig[i++] ), curData = jQuery.data( this, oldData ), events = oldData && oldData.events;
if ( events ) {
delete curData.handle;
curData.events = {};
for ( var type in events ) {
for ( var handler in events[ type ] ) {
jQuery.event.add( this, type, events[ type ][ handler ], events[ type ][ handler ].data );
}
}
}
});
}
function buildFragment( args, nodes, scripts ) {
var fragment, cacheable, cacheresults,
doc = (nodes && nodes[0] ? nodes[0].ownerDocument || nodes[0] : document);
// Only cache "small" (1/2 KB) strings that are associated with the main document
// Cloning options loses the selected state, so don't cache them
// IE 6 doesn't like it when you put <object> or <embed> elements in a fragment
// Also, WebKit does not clone 'checked' attributes on cloneNode, so don't cache
if ( args.length === 1 && typeof args[0] === "string" && args[0].length < 512 && doc === document &&
!rnocache.test( args[0] ) && (jQuery.support.checkClone || !rchecked.test( args[0] )) ) {
cacheable = true;
cacheresults = jQuery.fragments[ args[0] ];
if ( cacheresults ) {
if ( cacheresults !== 1 ) {
fragment = cacheresults;
}
}
}
if ( !fragment ) {
fragment = doc.createDocumentFragment();
jQuery.clean( args, doc, fragment, scripts );
}
if ( cacheable ) {
jQuery.fragments[ args[0] ] = cacheresults ? fragment : 1;
}
return { fragment: fragment, cacheable: cacheable };
}
jQuery.fragments = {};
jQuery.each({
appendTo: "append",
prependTo: "prepend",
insertBefore: "before",
insertAfter: "after",
replaceAll: "replaceWith"
}, function( name, original ) {
jQuery.fn[ name ] = function( selector ) {
var ret = [], insert = jQuery( selector ),
parent = this.length === 1 && this[0].parentNode;
if ( parent && parent.nodeType === 11 && parent.childNodes.length === 1 && insert.length === 1 ) {
insert[ original ]( this[0] );
return this;
} else {
for ( var i = 0, l = insert.length; i < l; i++ ) {
var elems = (i > 0 ? this.clone(true) : this).get();
jQuery.fn[ original ].apply( jQuery(insert[i]), elems );
ret = ret.concat( elems );
}
return this.pushStack( ret, name, insert.selector );
}
};
});
jQuery.extend({
clean: function( elems, context, fragment, scripts ) {
context = context || document;
// !context.createElement fails in IE with an error but returns typeof 'object'
if ( typeof context.createElement === "undefined" ) {
context = context.ownerDocument || context[0] && context[0].ownerDocument || document;
}
var ret = [];
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
if ( typeof elem === "number" ) {
elem += "";
}
if ( !elem ) {
continue;
}
// Convert html string into DOM nodes
if ( typeof elem === "string" && !rhtml.test( elem ) ) {
elem = context.createTextNode( elem );
} else if ( typeof elem === "string" ) {
// Fix "XHTML"-style tags in all browsers
elem = elem.replace(rxhtmlTag, fcloseTag);
// 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 ( var i = 0; ret[i]; i++ ) {
if ( scripts && jQuery.nodeName( ret[i], "script" ) && (!ret[i].type || ret[i].type.toLowerCase() === "text/javascript") ) {
scripts.push( ret[i].parentNode ? ret[i].parentNode.removeChild( ret[i] ) : ret[i] );
} else {
if ( ret[i].nodeType === 1 ) {
ret.splice.apply( ret, [i + 1, 0].concat(jQuery.makeArray(ret[i].getElementsByTagName("script"))) );
}
fragment.appendChild( ret[i] );
}
}
}
return ret;
},
cleanData: function( elems ) {
var data, id, cache = jQuery.cache,
special = jQuery.event.special,
deleteExpando = jQuery.support.deleteExpando;
for ( var i = 0, elem; (elem = elems[i]) != null; i++ ) {
id = elem[ jQuery.expando ];
if ( id ) {
data = cache[ id ];
if ( data.events ) {
for ( var type in data.events ) {
if ( special[ type ] ) {
jQuery.event.remove( elem, type );
} else {
removeEvent( elem, type, data.handle );
}
}
}
if ( deleteExpando ) {
delete elem[ jQuery.expando ];
} else if ( elem.removeAttribute ) {
elem.removeAttribute( jQuery.expando );
}
delete cache[ id ];
}
}
}
});
// exclude the following css properties to add px
var rexclude = /z-?index|font-?weight|opacity|zoom|line-?height/i,
ralpha = /alpha\([^)]*\)/,
ropacity = /opacity=([^)]*)/,
rfloat = /float/i,
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" ],
// cache check for defaultView.getComputedStyle
getComputedStyle = document.defaultView && document.defaultView.getComputedStyle,
// normalize float css property
styleFloat = jQuery.support.cssFloat ? "cssFloat" : "styleFloat",
fcamelCase = function( all, letter ) {
return letter.toUpperCase();
};
jQuery.fn.css = function( name, value ) {
return access( this, name, value, true, function( elem, name, value ) {
if ( value === undefined ) {
return jQuery.curCSS( elem, name );
}
if ( typeof value === "number" && !rexclude.test(name) ) {
value += "px";
}
jQuery.style( elem, name, value );
});
};
jQuery.extend({
style: function( elem, name, value ) {
// don't set styles on text and comment nodes
if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 ) {
return undefined;
}
// ignore negative width and height values #1599
if ( (name === "width" || name === "height") && parseFloat(value) < 0 ) {
value = undefined;
}
var style = elem.style || elem, set = value !== undefined;
// IE uses filters for opacity
if ( !jQuery.support.opacity && name === "opacity" ) {
if ( set ) {
// 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 = parseInt( value, 10 ) + "" === "NaN" ? "" : "alpha(opacity=" + value * 100 + ")";
var filter = style.filter || jQuery.curCSS( elem, "filter" ) || "";
style.filter = ralpha.test(filter) ? filter.replace(ralpha, opacity) : opacity;
}
return style.filter && style.filter.indexOf("opacity=") >= 0 ?
(parseFloat( ropacity.exec(style.filter)[1] ) / 100) + "":
"";
}
// Make sure we're using the right name for getting the float value
if ( rfloat.test( name ) ) {
name = styleFloat;
}
name = name.replace(rdashAlpha, fcamelCase);
if ( set ) {
style[ name ] = value;
}
return style[ name ];
},
css: function( elem, name, force, extra ) {
if ( name === "width" || name === "height" ) {
var val, props = cssShow, which = name === "width" ? cssWidth : cssHeight;
function getWH() {
val = name === "width" ? elem.offsetWidth : elem.offsetHeight;
if ( extra === "border" ) {
return;
}
jQuery.each( which, function() {
if ( !extra ) {
val -= parseFloat(jQuery.curCSS( elem, "padding" + this, true)) || 0;
}
if ( extra === "margin" ) {
val += parseFloat(jQuery.curCSS( elem, "margin" + this, true)) || 0;
} else {
val -= parseFloat(jQuery.curCSS( elem, "border" + this + "Width", true)) || 0;
}
});
}
if ( elem.offsetWidth !== 0 ) {
getWH();
} else {
jQuery.swap( elem, props, getWH );
}
return Math.max(0, Math.round(val));
}
return jQuery.curCSS( elem, name, force );
},
curCSS: function( elem, name, force ) {
var ret, style = elem.style, filter;
// IE uses filters for opacity
if ( !jQuery.support.opacity && name === "opacity" && elem.currentStyle ) {
ret = ropacity.test(elem.currentStyle.filter || "") ?
(parseFloat(RegExp.$1) / 100) + "" :
"";
return ret === "" ?
"1" :
ret;
}
// Make sure we're using the right name for getting the float value
if ( rfloat.test( name ) ) {
name = styleFloat;
}
if ( !force && style && style[ name ] ) {
ret = style[ name ];
} else if ( getComputedStyle ) {
// Only "float" is needed here
if ( rfloat.test( name ) ) {
name = "float";
}
name = name.replace( rupper, "-$1" ).toLowerCase();
var defaultView = elem.ownerDocument.defaultView;
if ( !defaultView ) {
return null;
}
var computedStyle = defaultView.getComputedStyle( elem, null );
if ( computedStyle ) {
ret = computedStyle.getPropertyValue( name );
}
// We should always get a number back from opacity
if ( name === "opacity" && ret === "" ) {
ret = "1";
}
} else if ( elem.currentStyle ) {
var camelCase = name.replace(rdashAlpha, fcamelCase);
ret = elem.currentStyle[ name ] || elem.currentStyle[ camelCase ];
// 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
var left = style.left, rsLeft = elem.runtimeStyle.left;
// Put in the new values to get a computed value out
elem.runtimeStyle.left = elem.currentStyle.left;
style.left = camelCase === "fontSize" ? "1em" : (ret || 0);
ret = style.pixelLeft + "px";
// Revert the changed values
style.left = left;
elem.runtimeStyle.left = rsLeft;
}
}
return ret;
},
// 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 ( var name in options ) {
elem.style[ name ] = old[ name ];
}
}
});
if ( jQuery.expr && jQuery.expr.filters ) {
jQuery.expr.filters.hidden = function( elem ) {
var width = elem.offsetWidth, height = elem.offsetHeight,
skip = elem.nodeName.toLowerCase() === "tr";
return width === 0 && height === 0 && !skip ?
true :
width > 0 && height > 0 && !skip ?
false :
jQuery.curCSS(elem, "display") === "none";
};
jQuery.expr.filters.visible = function( elem ) {
return !jQuery.expr.filters.hidden( elem );
};
}
var jsc = now(),
rscript = /<script(.|\s)*?\/script>/gi,
rselectTextarea = /select|textarea/i,
rinput = /color|date|datetime|email|hidden|month|number|password|range|search|tel|text|time|url|week/i,
jsre = /=\?(&|$)/,
rquery = /\?/,
rts = /(\?|&)_=.*?(&|$)/,
rurl = /^(\w+:)?\/\/([^\/?#]+)/,
r20 = /%20/g,
// Keep a copy of the old load method
_load = jQuery.fn.load;
jQuery.fn.extend({
load: function( url, params, callback ) {
if ( typeof url !== "string" ) {
return _load.call( this, url );
// Don't do a request if no elements are being requested
} else if ( !this.length ) {
return this;
}
var off = url.indexOf(" ");
if ( off >= 0 ) {
var selector = url.slice(off, url.length);
url = url.slice(0, off);
}
// Default to a GET request
var type = "GET";
// If the second parameter was provided
if ( params ) {
// If it's a function
if ( jQuery.isFunction( params ) ) {
// We assume that it's the callback
callback = params;
params = null;
// Otherwise, build a param string
} else if ( typeof params === "object" ) {
params = jQuery.param( params, jQuery.ajaxSettings.traditional );
type = "POST";
}
}
var self = this;
// Request the remote document
jQuery.ajax({
url: url,
type: type,
dataType: "html",
data: params,
complete: function( res, status ) {
// If successful, inject the HTML into all the matched elements
if ( status === "success" || status === "notmodified" ) {
// See if a selector was specified
self.html( selector ?
// Create a dummy div to hold the results
jQuery("<div />")
// inject the contents of the document in, removing the scripts
// to avoid any 'Permission Denied' errors in IE
.append(res.responseText.replace(rscript, ""))
// Locate the specified elements
.find(selector) :
// If not, just inject the full result
res.responseText );
}
if ( callback ) {
self.each( callback, [res.responseText, status, res] );
}
}
});
return this;
},
serialize: function() {
return jQuery.param(this.serializeArray());
},
serializeArray: function() {
return this.map(function() {
return this.elements ? jQuery.makeArray(this.elements) : this;
})
.filter(function() {
return this.name && !this.disabled &&
(this.checked || rselectTextarea.test(this.nodeName) ||
rinput.test(this.type));
})
.map(function( i, elem ) {
var val = jQuery(this).val();
return val == null ?
null :
jQuery.isArray(val) ?
jQuery.map( val, function( val, i ) {
return { name: elem.name, value: val };
}) :
{ name: elem.name, value: val };
}).get();
}
});
// Attach a bunch of functions for handling common AJAX events
jQuery.each( "ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "), function( i, o ) {
jQuery.fn[o] = function( f ) {
return this.bind(o, f);
};
});
jQuery.extend({
get: function( url, data, callback, type ) {
// shift arguments if data argument was omited
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = null;
}
return jQuery.ajax({
type: "GET",
url: url,
data: data,
success: callback,
dataType: type
});
},
getScript: function( url, callback ) {
return jQuery.get(url, null, callback, "script");
},
getJSON: function( url, data, callback ) {
return jQuery.get(url, data, callback, "json");
},
post: function( url, data, callback, type ) {
// shift arguments if data argument was omited
if ( jQuery.isFunction( data ) ) {
type = type || callback;
callback = data;
data = {};
}
return jQuery.ajax({
type: "POST",
url: url,
data: data,
success: callback,
dataType: type
});
},
ajaxSetup: function( settings ) {
jQuery.extend( jQuery.ajaxSettings, settings );
},
ajaxSettings: {
url: location.href,
global: true,
type: "GET",
contentType: "application/x-www-form-urlencoded",
processData: true,
async: true,
/*
timeout: 0,
data: null,
username: null,
password: null,
traditional: false,
*/
// Create the request object; Microsoft failed to properly
// implement the XMLHttpRequest in IE7 (can't request local files),
// so we use the ActiveXObject when it is available
// This function can be overriden by calling jQuery.ajaxSetup
xhr: window.XMLHttpRequest && (window.location.protocol !== "file:" || !window.ActiveXObject) ?
function() {
return new window.XMLHttpRequest();
} :
function() {
try {
return new window.ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {}
},
accepts: {
xml: "application/xml, text/xml",
html: "text/html",
script: "text/javascript, application/javascript",
json: "application/json, text/javascript",
text: "text/plain",
_default: "*/*"
}
},
// Last-Modified header cache for next request
lastModified: {},
etag: {},
ajax: function( origSettings ) {
var s = jQuery.extend(true, {}, jQuery.ajaxSettings, origSettings);
var jsonp, status, data,
callbackContext = origSettings && origSettings.context || s,
type = s.type.toUpperCase();
// convert data if not already a string
if ( s.data && s.processData && typeof s.data !== "string" ) {
s.data = jQuery.param( s.data, s.traditional );
}
// Handle JSONP Parameter Callbacks
if ( s.dataType === "jsonp" ) {
if ( type === "GET" ) {
if ( !jsre.test( s.url ) ) {
s.url += (rquery.test( s.url ) ? "&" : "?") + (s.jsonp || "callback") + "=?";
}
} else if ( !s.data || !jsre.test(s.data) ) {
s.data = (s.data ? s.data + "&" : "") + (s.jsonp || "callback") + "=?";
}
s.dataType = "json";
}
// Build temporary JSONP function
if ( s.dataType === "json" && (s.data && jsre.test(s.data) || jsre.test(s.url)) ) {
jsonp = s.jsonpCallback || ("jsonp" + jsc++);
// Replace the =? sequence both in the query string and the data
if ( s.data ) {
s.data = (s.data + "").replace(jsre, "=" + jsonp + "$1");
}
s.url = s.url.replace(jsre, "=" + jsonp + "$1");
// We need to make sure
// that a JSONP style response is executed properly
s.dataType = "script";
// Handle JSONP-style loading
window[ jsonp ] = window[ jsonp ] || function( tmp ) {
data = tmp;
success();
complete();
// Garbage collect
window[ jsonp ] = undefined;
try {
delete window[ jsonp ];
} catch(e) {}
if ( head ) {
head.removeChild( script );
}
};
}
if ( s.dataType === "script" && s.cache === null ) {
s.cache = false;
}
if ( s.cache === false && type === "GET" ) {
var ts = now();
// try replacing _= if it is there
var ret = s.url.replace(rts, "$1_=" + ts + "$2");
// if nothing was replaced, add timestamp to the end
s.url = ret + ((ret === s.url) ? (rquery.test(s.url) ? "&" : "?") + "_=" + ts : "");
}
// If data is available, append data to url for get requests
if ( s.data && type === "GET" ) {
s.url += (rquery.test(s.url) ? "&" : "?") + s.data;
}
// Watch for a new set of requests
if ( s.global && ! jQuery.active++ ) {
jQuery.event.trigger( "ajaxStart" );
}
// Matches an absolute URL, and saves the domain
var parts = rurl.exec( s.url ),
remote = parts && (parts[1] && parts[1] !== location.protocol || parts[2] !== location.host);
// If we're requesting a remote document
// and trying to load JSON or Script with a GET
if ( s.dataType === "script" && type === "GET" && remote ) {
var head = document.getElementsByTagName("head")[0] || document.documentElement;
var script = document.createElement("script");
script.src = s.url;
if ( s.scriptCharset ) {
script.charset = s.scriptCharset;
}
// Handle Script loading
if ( !jsonp ) {
var done = false;
// Attach handlers for all browsers
script.onload = script.onreadystatechange = function() {
if ( !done && (!this.readyState ||
this.readyState === "loaded" || this.readyState === "complete") ) {
done = true;
success();
complete();
// Handle memory leak in IE
script.onload = script.onreadystatechange = null;
if ( head && script.parentNode ) {
head.removeChild( script );
}
}
};
}
// Use insertBefore instead of appendChild to circumvent an IE6 bug.
// This arises when a base node is used (#2709 and #4378).
head.insertBefore( script, head.firstChild );
// We handle everything using the script element injection
return undefined;
}
var requestDone = false;
// Create the request object
var xhr = s.xhr();
if ( !xhr ) {
return;
}
// Open the socket
// Passing null username, generates a login popup on Opera (#2865)
if ( s.username ) {
xhr.open(type, s.url, s.async, s.username, s.password);
} else {
xhr.open(type, s.url, s.async);
}
// Need an extra try/catch for cross domain requests in Firefox 3
try {
// Set the correct header, if data is being sent
if ( s.data || origSettings && origSettings.contentType ) {
xhr.setRequestHeader("Content-Type", s.contentType);
}
// Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode.
if ( s.ifModified ) {
if ( jQuery.lastModified[s.url] ) {
xhr.setRequestHeader("If-Modified-Since", jQuery.lastModified[s.url]);
}
if ( jQuery.etag[s.url] ) {
xhr.setRequestHeader("If-None-Match", jQuery.etag[s.url]);
}
}
// Set header so the called script knows that it's an XMLHttpRequest
// Only send the header if it's not a remote XHR
if ( !remote ) {
xhr.setRequestHeader("X-Requested-With", "XMLHttpRequest");
}
// Set the Accepts header for the server, depending on the dataType
xhr.setRequestHeader("Accept", s.dataType && s.accepts[ s.dataType ] ?
s.accepts[ s.dataType ] + ", */*" :
s.accepts._default );
} catch(e) {}
// Allow custom headers/mimetypes and early abort
if ( s.beforeSend && s.beforeSend.call(callbackContext, xhr, s) === false ) {
// Handle the global AJAX counter
if ( s.global && ! --jQuery.active ) {
jQuery.event.trigger( "ajaxStop" );
}
// close opended socket
xhr.abort();
return false;
}
if ( s.global ) {
trigger("ajaxSend", [xhr, s]);
}
// Wait for a response to come back
var onreadystatechange = xhr.onreadystatechange = function( isTimeout ) {
// The request was aborted
if ( !xhr || xhr.readyState === 0 || isTimeout === "abort" ) {
// Opera doesn't call onreadystatechange before this point
// so we simulate the call
if ( !requestDone ) {
complete();
}
requestDone = true;
if ( xhr ) {
xhr.onreadystatechange = jQuery.noop;
}
// The transfer is complete and the data is available, or the request timed out
} else if ( !requestDone && xhr && (xhr.readyState === 4 || isTimeout === "timeout") ) {
requestDone = true;
xhr.onreadystatechange = jQuery.noop;
status = isTimeout === "timeout" ?
"timeout" :
!jQuery.httpSuccess( xhr ) ?
"error" :
s.ifModified && jQuery.httpNotModified( xhr, s.url ) ?
"notmodified" :
"success";
var errMsg;
if ( status === "success" ) {
// Watch for, and catch, XML document parse errors
try {
// process the data (runs the xml through httpData regardless of callback)
data = jQuery.httpData( xhr, s.dataType, s );
} catch(err) {
status = "parsererror";
errMsg = err;
}
}
// Make sure that the request was successful or notmodified
if ( status === "success" || status === "notmodified" ) {
// JSONP handles its own success callback
if ( !jsonp ) {
success();
}
} else {
jQuery.handleError(s, xhr, status, errMsg);
}
// Fire the complete handlers
complete();
if ( isTimeout === "timeout" ) {
xhr.abort();
}
// Stop memory leaks
if ( s.async ) {
xhr = null;
}
}
};
// Override the abort handler, if we can (IE doesn't allow it, but that's OK)
// Opera doesn't fire onreadystatechange at all on abort
try {
var oldAbort = xhr.abort;
xhr.abort = function() {
if ( xhr ) {
oldAbort.call( xhr );
}
onreadystatechange( "abort" );
};
} catch(e) { }
// Timeout checker
if ( s.async && s.timeout > 0 ) {
setTimeout(function() {
// Check to see if the request is still happening
if ( xhr && !requestDone ) {
onreadystatechange( "timeout" );
}
}, s.timeout);
}
// Send the data
try {
xhr.send( type === "POST" || type === "PUT" || type === "DELETE" ? s.data : null );
} catch(e) {
jQuery.handleError(s, xhr, null, e);
// Fire the complete handlers
complete();
}
// firefox 1.5 doesn't fire statechange for sync requests
if ( !s.async ) {
onreadystatechange();
}
function success() {
// If a local callback was specified, fire it and pass it the data
if ( s.success ) {
s.success.call( callbackContext, data, status, xhr );
}
// Fire the global callback
if ( s.global ) {
trigger( "ajaxSuccess", [xhr, s] );
}
}
function complete() {
// Process result
if ( s.complete ) {
s.complete.call( callbackContext, xhr, status);
}
// The request was completed
if ( s.global ) {
trigger( "ajaxComplete", [xhr, s] );
}
// Handle the global AJAX counter
if ( s.global && ! --jQuery.active ) {
jQuery.event.trigger( "ajaxStop" );
}
}
function trigger(type, args) {
(s.context ? jQuery(s.context) : jQuery.event).trigger(type, args);
}
// return XMLHttpRequest to allow aborting the request etc.
return xhr;
},
handleError: function( s, xhr, status, e ) {
// If a local callback was specified, fire it
if ( s.error ) {
s.error.call( s.context || s, xhr, status, e );
}
// Fire the global callback
if ( s.global ) {
(s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );
}
},
// Counter for holding the number of active queries
active: 0,
// Determines if an XMLHttpRequest was successful or not
httpSuccess: function( xhr ) {
try {
// IE error sometimes returns 1223 when it should be 204 so treat it as success, see #1450
return !xhr.status && location.protocol === "file:" ||
// Opera returns 0 when status is 304
( xhr.status >= 200 && xhr.status < 300 ) ||
xhr.status === 304 || xhr.status === 1223 || xhr.status === 0;
} catch(e) {}
return false;
},
// Determines if an XMLHttpRequest returns NotModified
httpNotModified: function( xhr, url ) {
var lastModified = xhr.getResponseHeader("Last-Modified"),
etag = xhr.getResponseHeader("Etag");
if ( lastModified ) {
jQuery.lastModified[url] = lastModified;
}
if ( etag ) {
jQuery.etag[url] = etag;
}
// Opera returns 0 when status is 304
return xhr.status === 304 || xhr.status === 0;
},
httpData: function( xhr, type, s ) {
var ct = xhr.getResponseHeader("content-type") || "",
xml = type === "xml" || !type && ct.indexOf("xml") >= 0,
data = xml ? xhr.responseXML : xhr.responseText;
if ( xml && data.documentElement.nodeName === "parsererror" ) {
jQuery.error( "parsererror" );
}
// Allow a pre-filtering function to sanitize the response
// s is checked to keep backwards compatibility
if ( s && s.dataFilter ) {
data = s.dataFilter( data, type );
}
// The filter can actually parse the response
if ( typeof data === "string" ) {
// Get the JavaScript object, if JSON is used.
if ( type === "json" || !type && ct.indexOf("json") >= 0 ) {
data = jQuery.parseJSON( data );
// If the type is "script", eval it in global context
} else if ( type === "script" || !type && ct.indexOf("javascript") >= 0 ) {
jQuery.globalEval( data );
}
}
return data;
},
// Serialize an array of form elements or a set of
// key/values into a query string
param: function( a, traditional ) {
var s = [];
// Set traditional to true for jQuery <= 1.3.2 behavior.
if ( traditional === undefined ) {
traditional = jQuery.ajaxSettings.traditional;
}
// If an array was passed in, assume that it is an array of form elements.
if ( jQuery.isArray(a) || a.jquery ) {
// Serialize the form elements
jQuery.each( a, function() {
add( this.name, this.value );
});
} else {
// If traditional, encode the "old" way (the way 1.3.2 or older
// did it), otherwise encode params recursively.
for ( var prefix in a ) {
buildParams( prefix, a[prefix] );
}
}
// Return the resulting serialization
return s.join("&").replace(r20, "+");
function buildParams( prefix, obj ) {
if ( jQuery.isArray(obj) ) {
// Serialize array item.
jQuery.each( obj, function( i, v ) {
if ( traditional || /\[\]$/.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 );
}
});
} else if ( !traditional && obj != null && typeof obj === "object" ) {
// Serialize object item.
jQuery.each( obj, function( k, v ) {
buildParams( prefix + "[" + k + "]", v );
});
} else {
// Serialize scalar item.
add( prefix, obj );
}
}
function add( 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);
}
}
});
var elemdisplay = {},
rfxtypes = /toggle|show|hide/,
rfxnum = /^([+-]=)?([\d+-.]+)(.*)$/,
timerId,
fxAttrs = [
// height animations
[ "height", "marginTop", "marginBottom", "paddingTop", "paddingBottom" ],
// width animations
[ "width", "marginLeft", "marginRight", "paddingLeft", "paddingRight" ],
// opacity animations
[ "opacity" ]
];
jQuery.fn.extend({
show: function( speed, callback ) {
if ( speed || speed === 0) {
return this.animate( genFx("show", 3), speed, callback);
} else {
for ( var i = 0, l = this.length; i < l; i++ ) {
var old = jQuery.data(this[i], "olddisplay");
this[i].style.display = old || "";
if ( jQuery.css(this[i], "display") === "none" ) {
var nodeName = this[i].nodeName, display;
if ( elemdisplay[ nodeName ] ) {
display = elemdisplay[ nodeName ];
} else {
var elem = jQuery("<" + nodeName + " />").appendTo("body");
display = elem.css("display");
if ( display === "none" ) {
display = "block";
}
elem.remove();
elemdisplay[ nodeName ] = display;
}
jQuery.data(this[i], "olddisplay", display);
}
}
// Set the display of the elements in a second loop
// to avoid the constant reflow
for ( var j = 0, k = this.length; j < k; j++ ) {
this[j].style.display = jQuery.data(this[j], "olddisplay") || "";
}
return this;
}
},
hide: function( speed, callback ) {
if ( speed || speed === 0 ) {
return this.animate( genFx("hide", 3), speed, callback);
} else {
for ( var i = 0, l = this.length; i < l; i++ ) {
var old = jQuery.data(this[i], "olddisplay");
if ( !old && old !== "none" ) {
jQuery.data(this[i], "olddisplay", jQuery.css(this[i], "display"));
}
}
// Set the display of the elements in a second loop
// to avoid the constant reflow
for ( var j = 0, k = this.length; j < k; j++ ) {
this[j].style.display = "none";
}
return this;
}
},
// Save the old toggle function
_toggle: jQuery.fn.toggle,
toggle: function( fn, fn2 ) {
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);
}
return this;
},
fadeTo: function( speed, to, callback ) {
return this.filter(":hidden").css("opacity", 0).show().end()
.animate({opacity: to}, speed, 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() {
var opt = jQuery.extend({}, optall), p,
hidden = this.nodeType === 1 && jQuery(this).is(":hidden"),
self = this;
for ( p in prop ) {
var name = p.replace(rdashAlpha, fcamelCase);
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 ( ( p === "height" || p === "width" ) && this.style ) {
// Store display property
opt.display = jQuery.css(this, "display");
// Make sure that nothing sneaks out
opt.overflow = this.style.overflow;
}
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(true) || 0;
if ( parts ) {
var end = parseFloat( parts[2] ),
unit = parts[3] || "px";
// We need to compute starting value
if ( unit !== "px" ) {
self.style[ name ] = (end || 1) + unit;
start = ((end || 1) / e.cur(true)) * start;
self.style[ 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;
}
});
// 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" }
}, function( name, props ) {
jQuery.fn[ name ] = function( speed, callback ) {
return this.animate( props, speed, callback );
};
});
jQuery.extend({
speed: function( speed, easing, fn ) {
var opt = speed && typeof speed === "object" ? 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 :
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 );
// Set display property to block for height/width animations
if ( ( this.prop === "height" || this.prop === "width" ) && this.elem.style ) {
this.elem.style.display = "block";
}
},
// Get the current size
cur: function( force ) {
if ( this.elem[this.prop] != null && (!this.elem.style || this.elem.style[this.prop] == null) ) {
return this.elem[ this.prop ];
}
var r = parseFloat(jQuery.css(this.elem, this.prop, force));
return r && r > -10000 ? r : parseFloat(jQuery.curCSS(this.elem, this.prop)) || 0;
},
// Start an animation from one number to another
custom: function( from, to, unit ) {
this.startTime = now();
this.start = from;
this.end = to;
this.unit = unit || this.unit || "px";
this.now = this.start;
this.pos = this.state = 0;
var self = this;
function t( gotoEnd ) {
return self.step(gotoEnd);
}
t.elem = this.elem;
if ( t() && jQuery.timers.push(t) && !timerId ) {
timerId = setInterval(jQuery.fx.tick, 13);
}
},
// 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 = 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 ) {
if ( this.options.display != null ) {
// Reset the overflow
this.elem.style.overflow = this.options.overflow;
// Reset the display
var old = jQuery.data(this.elem, "olddisplay");
this.elem.style.display = old ? old : this.options.display;
if ( jQuery.css(this.elem, "display") === "none" ) {
this.elem.style.display = "block";
}
}
// 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();
}
},
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 genFx( type, num ) {
var obj = {};
jQuery.each( fxAttrs.concat.apply([], fxAttrs.slice(0,num)), function() {
obj[ this ] = type;
});
return obj;
}
if ( "getBoundingClientRect" in document.documentElement ) {
jQuery.fn.offset = function( options ) {
var elem = this[0];
if ( options ) {
return this.each(function( i ) {
jQuery.offset.setOffset( this, options, i );
});
}
if ( !elem || !elem.ownerDocument ) {
return null;
}
if ( elem === elem.ownerDocument.body ) {
return jQuery.offset.bodyOffset( elem );
}
var box = elem.getBoundingClientRect(), doc = elem.ownerDocument, body = doc.body, docElem = doc.documentElement,
clientTop = docElem.clientTop || body.clientTop || 0, clientLeft = docElem.clientLeft || body.clientLeft || 0,
top = box.top + (self.pageYOffset || jQuery.support.boxModel && docElem.scrollTop || body.scrollTop ) - clientTop,
left = box.left + (self.pageXOffset || jQuery.support.boxModel && docElem.scrollLeft || body.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 offsetParent = elem.offsetParent, prevOffsetParent = elem,
doc = elem.ownerDocument, computedStyle, 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 && /^t(able|d|h)$/i.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.curCSS(body, "marginTop", true) ) || 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.curCSS(body, "marginTop", true) ) || 0;
left += parseFloat( jQuery.curCSS(body, "marginLeft", true) ) || 0;
}
return { top: top, left: left };
},
setOffset: function( elem, options, i ) {
// set position first, in-case top/left are set even on static elem
if ( /static/.test( jQuery.curCSS( elem, "position" ) ) ) {
elem.style.position = "relative";
}
var curElem = jQuery( elem ),
curOffset = curElem.offset(),
curTop = parseInt( jQuery.curCSS( elem, "top", true ), 10 ) || 0,
curLeft = parseInt( jQuery.curCSS( elem, "left", true ), 10 ) || 0;
if ( jQuery.isFunction( options ) ) {
options = options.call( elem, i, curOffset );
}
var props = {
top: (options.top - curOffset.top) + curTop,
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 = /^body|html$/i.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.curCSS(elem, "marginTop", true) ) || 0;
offset.left -= parseFloat( jQuery.curCSS(elem, "marginLeft", true) ) || 0;
// Add offsetParent borders
parentOffset.top += parseFloat( jQuery.curCSS(offsetParent[0], "borderTopWidth", true) ) || 0;
parentOffset.left += parseFloat( jQuery.curCSS(offsetParent[0], "borderLeftWidth", true) ) || 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 && (!/^body|html$/i.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 ("scrollTo" in elem && elem.document) ?
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] ?
jQuery.css( this[0], type, false, "padding" ) :
null;
};
// outerHeight and outerWidth
jQuery.fn["outer" + name] = function( margin ) {
return this[0] ?
jQuery.css( this[0], type, false, 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 ]() ) );
});
}
return ("scrollTo" in elem && elem.document) ? // does it walk and quack like a window?
// Everyone else use document.documentElement or document.body depending on Quirks vs Standards mode
elem.document.compatMode === "CSS1Compat" && elem.document.documentElement[ "client" + name ] ||
elem.document.body[ "client" + name ] :
// Get document width or height
(elem.nodeType === 9) ? // is it a document
// Either scroll[Width/Height] or offset[Width/Height], whichever is greater
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
size === undefined ?
// Get width or height on the element
jQuery.css( elem, type ) :
// Set the width or height on the element (default to pixels if value is unitless)
this.css( type, typeof size === "string" ? size : size + "px" );
};
});
// Expose jQuery to the global object
window.jQuery = window.$ = jQuery;
})(window); |
ajax/libs/6to5/1.14.4/browser-polyfill.js | aashish24/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]); |
ui/src/main/frontend/src/components/EmployeeModal.js | Dokuro-YH/alice-projects | import React, { Component } from 'react';
import {
Modal,
Form,
FormGroup,
Col,
FormControl,
ControlLabel,
Button
} from 'react-bootstrap';
class EmployeeModal extends Component {
constructor(props) {
super(props);
this.state = {
data: props.data || {}
}
}
componentWillReceiveProps(nextProps) {
if ('data' in nextProps) {
this.setState({ data: nextProps.data });
}
}
handleChange = (e) => {
const target = e.target;
const isNumber = target.type === 'number';
const name = target.id;
const value = target.type === 'checkbox' ? target.checked : target.value;
this.setState({
data: {
...this.state.data,
[name]: isNumber ? Number(value) : value
}
});
}
triggerSubmit = e => {
e.preventDefault();
const onSubmit = this.props.onSubmit;
if (onSubmit) {
onSubmit(this.state.data);
}
}
render() {
const { show, isModify, onClose } = this.props;
const { data } = this.state;
return (
<Modal show={show} onHide={onClose}>
<Modal.Header closeButton>
<Modal.Title>{isModify ? 'Update' : 'Create'} employee</Modal.Title>
</Modal.Header>
<Modal.Body>
<Form horizontal onSubmit={this.triggerSubmit}>
<FormGroup controlId="name">
<Col componentClass={ControlLabel} sm={2}>Name</Col>
<Col sm={10}>
<FormControl type="text" onChange={this.handleChange} value={data.name || ''} />
</Col>
</FormGroup>
<FormGroup controlId="age">
<Col componentClass={ControlLabel} sm={2}>Age</Col>
<Col sm={10}>
<FormControl type="number" onChange={this.handleChange} value={data.age || ''} />
</Col>
</FormGroup>
<FormGroup controlId="description">
<Col componentClass={ControlLabel} sm={2}>Description</Col>
<Col sm={10}>
<FormControl type="text" onChange={this.handleChange} value={data.description || ''} />
</Col>
</FormGroup>
<FormGroup>
<Col smOffset={2} sm={10}>
<Button bsStyle="primary" type="submit">Save</Button></Col>
</FormGroup>
</Form>
</Modal.Body>
</Modal>
);
}
}
export default EmployeeModal;
|
examples/using-remark-copy-linked-files/src/pages/index.js | fk/gatsby | import React from "react"
import { Link } from "gatsby"
import get from "lodash/get"
import Helmet from "react-helmet"
import Layout from "../components/layout"
import Bio from "../components/Bio"
import typography from "../utils/typography"
const { rhythm } = typography
class BlogIndex extends React.Component {
render() {
const siteTitle = get(this, `props.data.site.siteMetadata.title`)
const posts = get(this, `props.data.allMarkdownRemark.edges`)
return (
<Layout location={this.props.location}>
<Helmet title={siteTitle} />
<Bio />
{posts.map(post => {
if (post.node.frontmatter.path !== `/404/`) {
const title = get(post, `node.frontmatter.title`) || post.node.path
return (
<div key={post.node.frontmatter.path}>
<h3
style={{
marginBottom: rhythm(1 / 4),
}}
>
<Link
style={{ boxShadow: `none` }}
to={post.node.frontmatter.path}
>
{title}
</Link>
</h3>
<small>{post.node.frontmatter.date}</small>
<p dangerouslySetInnerHTML={{ __html: post.node.excerpt }} />
</div>
)
}
})}
</Layout>
)
}
}
export default BlogIndex
export const pageQuery = graphql`
query {
site {
siteMetadata {
title
}
}
allMarkdownRemark(sort: { fields: [frontmatter___date], order: DESC }) {
edges {
node {
excerpt
frontmatter {
path
date(formatString: "DD MMMM, YYYY")
}
frontmatter {
title
}
}
}
}
}
`
|
packages/material-ui-icons/src/StarSharp.js | kybarg/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<React.Fragment><g fill="none"><path d="M0 0h24v24H0V0z" /><path d="M0 0h24v24H0V0z" /></g><path d="M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21 12 17.27z" /></React.Fragment>
, 'StarSharp');
|
src/main.js | bumbu/trainline-test | import React from 'react'
import ReactDOM from 'react-dom'
import createStore from './store/createStore'
import AppContainer from './containers/AppContainer'
// ========================================================
// Store Instantiation
// ========================================================
const initialState = window.___INITIAL_STATE__
const store = createStore(initialState)
// ========================================================
// Render Setup
// ========================================================
const MOUNT_NODE = document.getElementById('root')
let render = () => {
const routes = require('./routes/index').default(store)
ReactDOM.render(
<AppContainer store={store} routes={routes} />,
MOUNT_NODE
)
}
// This code is excluded from production bundle
if (__DEV__) {
if (module.hot) {
// Development render functions
const renderApp = render
const renderError = (error) => {
const RedBox = require('redbox-react').default
ReactDOM.render(<RedBox error={error} />, MOUNT_NODE)
}
// Wrap render in try/catch
render = () => {
try {
renderApp()
} catch (error) {
renderError(error)
}
}
// Setup hot module replacement
module.hot.accept('./routes/index', () =>
setImmediate(() => {
ReactDOM.unmountComponentAtNode(MOUNT_NODE)
render()
})
)
}
}
// ========================================================
// Go!
// ========================================================
render()
|
tests/react_custom_funs/create_factory.js | claudiopro/flow | // @flow
import React from 'react';
declare var any: any;
React.createFactory(any)(); // OK
React.createFactory(any)({}); // OK
React.createFactory(any)(undefined); // OK
React.createFactory(any)(null); // OK
class A extends React.Component<{foo: number, bar: number}, void> {}
function B(props: {foo: number, bar: number}) {}
const aFactory = React.createFactory(A);
const bFactory = React.createFactory(B);
aFactory({foo: 1, bar: 2}); // OK
bFactory({foo: 1, bar: 2}); // OK
aFactory({
foo: 42,
bar: 'Hello, world!', // Error: `bar` is a string.
});
bFactory({
foo: 42,
bar: 'Hello, world!', // Error: `bar` is a string.
});
aFactory({foo: 42}); // Error: `bar` is missing.
bFactory({foo: 42}); // Error: `bar` is missing.
aFactory(undefined); // Error: `foo` and `bar` are missing.
bFactory(undefined); // Error: `foo` and `bar` are missing.
aFactory(null); // Error: `foo` and `bar` are missing.
bFactory(null); // Error: `foo` and `bar` are missing.
(aFactory({foo: 1, bar: 2}).type: Class<A>); // OK
(bFactory({foo: 1, bar: 2}).type: typeof B); // OK
(aFactory({foo: 1, bar: 2}).props.foo: number); // OK
(bFactory({foo: 1, bar: 2}).props.foo: number); // OK
(aFactory({foo: 1, bar: 2}).props.foo: boolean); // Error: `foo` is `number`.
(bFactory({foo: 1, bar: 2}).props.foo: boolean); // Error: `foo` is `number`.
aFactory({foo: 1, bar: 2}).nope; // Error: `nope` does not exist.
bFactory({foo: 1, bar: 2}).nope; // Error: `nope` does not exist.
aFactory(); // Error: Missing `foo` and `bar`.
bFactory(); // Error: Missing `foo` and `bar`.
class C extends React.Component<{foo: number, bar: number}, void> {
static defaultProps = {bar: 42};
}
function D(props: {foo: number, bar: number}) {}
D.defaultProps = {bar: 42};
const cFactory = React.createFactory(C);
const dFactory = React.createFactory(D);
cFactory({foo: 1, bar: 2}); // OK
dFactory({foo: 1, bar: 2}); // OK
cFactory({
foo: 42,
bar: 'Hello, world!', // Error: `bar` is a string.
});
dFactory({
foo: 42,
bar: 'Hello, world!', // Error: `bar` is a string.
});
cFactory({foo: 42}); // OK: `bar` is in `defaultProps`.
dFactory({foo: 42}); // OK: `bar` is in `defaultProps`.
(cFactory({foo: 42}).props.bar: number); // OK
(dFactory({foo: 42}).props.bar: number); // OK
const anyFactory = React.createFactory(any);
anyFactory({whateverYouWant: 'yes'}); // OK
class E extends React.Component<{children: number}, void> {}
const eFactory = React.createFactory(E);
eFactory({}); // Error
eFactory(undefined); // Error
eFactory(null); // Error
eFactory({}, 1); // OK
eFactory(undefined, 1); // OK
eFactory(null, 1); // OK
eFactory({}, 1, 2); // Error
eFactory(undefined, 1, 2); // Error
eFactory(null, 1, 2); // Error
eFactory({}, 1, 2, 3); // Error
eFactory({}, [1, 2]); // Error
eFactory({}, [1, 2], [3, 4]); // Error
eFactory({}, ...[]); // Error
eFactory({}, ...[1]); // OK
eFactory({}, ...[1, 2]); // Error
eFactory({}, ...(any: Array<number>)); // Error
eFactory({}, 1, ...[]); // OK
eFactory({}, 1, ...[2]); // Error
eFactory({}, 1, ...(any: Array<number>)); // Error
class F extends React.Component<{children: Array<number>}, void> {}
const fFactory = React.createFactory(F);
fFactory({}); // Error
fFactory(undefined); // Error
fFactory(null); // Error
fFactory({}, 1); // Error
fFactory(undefined, 1); // Error
fFactory(null, 1); // Error
fFactory({}, 1, 2); // OK
fFactory(undefined, 1, 2); // OK
fFactory(null, 1, 2); // OK
fFactory({}, 1, 2, 3); // OK
fFactory({}, [1, 2]); // OK
fFactory({}, [1, 2], [3, 4]); // Error
fFactory({}, ...[]); // Error
fFactory({}, ...[1]); // Error
fFactory({}, ...[1, 2]); // OK
fFactory({}, ...(any: Array<number>)); // Error
fFactory({}, 1, ...[]); // Error
fFactory({}, 1, ...[2]); // OK
fFactory({}, 1, ...(any: Array<number>)); // Error
class G extends React.Component<{children: number | Array<number>}, void> {}
const gFactory = React.createFactory(G);
gFactory({}); // Error
gFactory({}, 1); // OK
gFactory({}, 1, 2); // OK
gFactory({}, 1, 2, 3); // OK
gFactory({}, [1, 2]); // OK
gFactory({}, [1, 2], [3, 4]); // Error
gFactory({}, ...[]); // Error
gFactory({}, ...[1]); // OK
gFactory({}, ...[1, 2]); // OK
gFactory({}, ...(any: Array<number>)); // Error
gFactory({}, 1, ...[]); // OK
gFactory({}, 1, ...[2]); // OK
gFactory({}, 1, ...(any: Array<number>)); // OK
type NumberArrayRecursive = number | Array<NumberArrayRecursive>;
class H extends React.Component<{children: NumberArrayRecursive}, void> {}
const hFactory = React.createFactory(H);
hFactory({}); // Error
hFactory({}, 1); // OK
hFactory({}, 1, 2); // OK
hFactory({}, 1, 2, 3); // OK
hFactory({}, [1, 2]); // OK
hFactory({}, [1, 2], [3, 4]); // OK
hFactory({}, ...[]); // Error
hFactory({}, ...[1]); // OK
hFactory({}, ...[1, 2]); // OK
hFactory({}, ...(any: Array<number>)); // Error
hFactory({}, 1, ...[]); // OK
hFactory({}, 1, ...[2]); // OK
hFactory({}, 1, ...(any: Array<number>)); // OK
class I extends React.Component<{children?: number}, void> {}
const iFactory = React.createFactory(I);
iFactory({}); // OK
iFactory({}, undefined); // OK
iFactory({}, null); // Error
iFactory({}, 1); // OK
iFactory({}, 1, 2); // Error
iFactory({}, ...[]); // OK
iFactory({}, ...[1]); // OK
iFactory({}, ...[1, 2]); // Error
iFactory({}, ...(any: Array<number>)); // Error
iFactory({}, 1, ...[]); // OK
iFactory({}, 1, ...[2]); // Error
iFactory({}, 1, ...(any: Array<number>)); // Error
class J extends React.Component<{children: ?number}, void> {}
const jFactory = React.createFactory(J);
jFactory({}); // Error
jFactory({}, undefined); // OK
jFactory({}, null); // OK
jFactory({}, 1); // OK
jFactory({}, 1, 2); // Error
jFactory({}, ...[]); // Error
jFactory({}, ...[1]); // OK
jFactory({}, ...[1, 2]); // Error
jFactory({}, ...(any: Array<number>)); // Error
jFactory({}, 1, ...[]); // OK
jFactory({}, 1, ...[2]); // Error
jFactory({}, 1, ...(any: Array<number>)); // Error
class K extends React.Component<{children: number}, void> {}
const kFactory = React.createFactory(K);
kFactory({}, 42); // OK
kFactory({children: 42}); // OK
kFactory({children: 42}, 42); // OK
kFactory({}, '42'); // Error
kFactory({children: '42'}); // Error
kFactory({children: '42'}, 42); // Error
kFactory({children: 42}, '42'); // Error
kFactory({children: '42'}, '42'); // Error
class L extends React.Component<{
foo: number,
bar: number,
children: number,
}, void> {
static defaultProps = {bar: 42};
}
const lFactory = React.createFactory(L);
lFactory({foo: 1, bar: 2}, 3); // OK
lFactory({foo: 1, bar: 2, children: 3}); // OK
lFactory({foo: 1}, 2); // OK
lFactory({foo: 1, children: 2}); // OK
lFactory({}, 1); // Error
lFactory({children: 1}); // Error
lFactory({bar: 1}, 2); // Error
lFactory({bar: 1, children: 2}); // Error
lFactory({foo: '1', bar: 2}, 3); // Error
lFactory({foo: '1', bar: 2, children: 3}); // Error
lFactory({foo: 1, bar: '2'}, 3); // Error
lFactory({foo: 1, bar: '2', children: 3}); // Error
lFactory({foo: 1, bar: 2}, '3'); // Error
lFactory({foo: 1, bar: 2, children: '3'}); // Error
class M extends React.Component<{}> {}
class N extends React.Component<{}> {}
const mFactory = React.createFactory(M);
(mFactory().type: typeof M); // OK
(mFactory().type: typeof N); // Error
|
node_modules/babel-plugin-react-transform/test/fixtures/code-class-extends-component-with-render-method/actual.js | kelong/react-native-with-amazon-s3 | import React, { Component } from 'react';
class Foo extends Component {
render() {}
}
|
js/settings/StatusBarItem.js | sotayamashita/wizardsLifeCounter | // @flow
import React from 'react';
import { View, Text, TouchableOpacity, Switch, StyleSheet } from 'react-native';
import { StyledItem, StyledItemIcon, StyledItemIconImage, StyledItemContent } from './StyledItem';
const StatusBarItem = ({ isStatusBarEnabled, onUserChangeStatusBar }) => {
return (
<StyledItem>
<StyledItemIcon>
<StyledItemIconImage source={require('./image/battery.ios.png')}/>
</StyledItemIcon>
<StyledItemContent>
<View style={styles.container}>
<Text style={styles.text}>Show the status bar</Text>
<Switch onValueChange={(value) => onUserChangeStatusBar(value)}
value={isStatusBarEnabled}/>
</View>
</StyledItemContent>
</StyledItem>
)
};
const styles = StyleSheet.create({
container: {
flexDirection: 'row',
alignItems: 'center',
justifyContent: 'space-between',
},
text: {
fontSize: 16,
color: '#000',
},
});
export default StatusBarItem;
|
packages/benchmarks/react-jss/client/Table.js | A-gambit/CSS-IN-JS-Benchmarks | import React from 'react';
import injectSheet from 'react-jss';
const styles = {
table: {
display: 'table',
marginTop: 10,
},
row: {
display: 'table-row',
},
};
const stylesCell = {
cell: {
display: 'table-cell',
padding: 10,
background: props => `rgba(74, 174, 53, ${props.value})`,
},
};
const CellComponent = ({ classes, children }) => (
<div className={classes.cell}>{children}</div>
);
const Cell = injectSheet(stylesCell)(CellComponent);
const Table = ({ classes, table, toPercent }) => (
<div className={classes.table}>
{table.map((row, i) => (
<div className={classes.row} key={i}>
{row.map((x, j) => (
<Cell key={`${i}${j}`} value={x}>{toPercent(x)}</Cell>
))}
</div>
))}
</div>
);
export default injectSheet(styles)(Table);
|
packages/material-ui-icons/src/Accessibility.js | kybarg/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M12 2c1.1 0 2 .9 2 2s-.9 2-2 2-2-.9-2-2 .9-2 2-2zm9 7h-6v13h-2v-6h-2v6H9V9H3V7h18v2z" />
, 'Accessibility');
|
node_modules/bs-recipes/recipes/webpack.react-hot-loader/app/js/main.js | arthurchan1111/EventPlanner | import React from 'react';
// It's important to not define HelloWorld component right in this file
// because in that case it will do full page reload on change
import HelloWorld from './HelloWorld.jsx';
React.render(<HelloWorld />, document.getElementById('react-root'));
|
mobile/src/PosterCardList/presenter.js | TailorDev/pauling | /* @flow */
import React from 'react';
import { FlatList } from 'react-native';
import { Toast } from 'native-base';
import LoadingMessage from 'app/LoadingMessage';
import PosterCard from 'app/PosterCard';
import Empty from './Empty';
import type { Poster } from 'app/types';
import type { State as NavigationState } from 'app/reducers/navigation';
import styles from './styles';
type Props = {|
errored: boolean,
loading: boolean,
navigation: NavigationState,
posters: Array<Poster>,
toastComponent: typeof Toast,
|};
class PosterCardList extends React.Component {
props: Props;
static defaultProps = {
toastComponent: Toast,
};
renderItem = ({ item }: { item: Poster }) => {
return <PosterCard poster={item} navigation={this.props.navigation} />;
};
render() {
const { errored, loading, posters, toastComponent } = this.props;
if (errored) {
toastComponent.show({
text: 'Failed to load the poster. Please try again later.',
position: 'bottom',
buttonText: 'Dismiss',
});
}
const isFetching = loading && !errored;
if (isFetching) {
return (
<LoadingMessage>
Fetching the poster from Pauling, this should not take too long (in
theory).
</LoadingMessage>
);
}
return (
<FlatList
style={styles.List}
data={posters}
keyExtractor={item => item.id}
renderItem={this.renderItem}
ListEmptyComponent={Empty}
/>
);
}
}
export default PosterCardList;
|
examples/dev.js | ericbiewener/react-global-events | import React from 'react'
import {render} from 'react-dom'
import GlobalEvents, {listenFor} from '../src/index.js'
const RootComponent = () => (
<div id="app-root" {...listenFor('mouseUp', 'mouseDown')}>
<MySubComponent />
</div>
)
const MySubComponent = React.createClass({
getInitialState: function() {
return { text: '' }
},
componentDidMount: function() {
GlobalEvents.subscribe(this, 'mouseDown', 'mouseUp')
},
componentWillUnmount: function() {
GlobalEvents.unsubscribe(this, 'mouseDown', 'mouseUp')
},
onGlobalMouseDown: function(e) {
this.setState({ text: 'Mouse down!' })
},
onGlobalMouseUp: function(e) {
this.setState({ text: 'Mouse up!' })
},
render: function() {
return <div className='event-listener'>
<div>
<div>I'm listening for events anywhere!</div>
<div>{this.state.text}</div>
</div>
</div>
}
})
render(
<RootComponent />,
document.getElementById('root')
) |
jquery-1.7.0.min.js | tkrmnz/WebMSO19fcgi | /*! jQuery v1.7 jquery.com | jquery.org/license */
(function(a,b){function cA(a){return f.isWindow(a)?a:a.nodeType===9?a.defaultView||a.parentWindow:!1}function cx(a){if(!cm[a]){var b=c.body,d=f("<"+a+">").appendTo(b),e=d.css("display");d.remove();if(e==="none"||e===""){cn||(cn=c.createElement("iframe"),cn.frameBorder=cn.width=cn.height=0),b.appendChild(cn);if(!co||!cn.createElement)co=(cn.contentWindow||cn.contentDocument).document,co.write((c.compatMode==="CSS1Compat"?"<!doctype html>":"")+"<html><body>"),co.close();d=co.createElement(a),co.body.appendChild(d),e=f.css(d,"display"),b.removeChild(cn)}cm[a]=e}return cm[a]}function cw(a,b){var c={};f.each(cs.concat.apply([],cs.slice(0,b)),function(){c[this]=a});return c}function cv(){ct=b}function cu(){setTimeout(cv,0);return ct=f.now()}function cl(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function ck(){try{return new a.XMLHttpRequest}catch(b){}}function ce(a,c){a.dataFilter&&(c=a.dataFilter(c,a.dataType));var d=a.dataTypes,e={},g,h,i=d.length,j,k=d[0],l,m,n,o,p;for(g=1;g<i;g++){if(g===1)for(h in a.converters)typeof h=="string"&&(e[h.toLowerCase()]=a.converters[h]);l=k,k=d[g];if(k==="*")k=l;else if(l!=="*"&&l!==k){m=l+" "+k,n=e[m]||e["* "+k];if(!n){p=b;for(o in e){j=o.split(" ");if(j[0]===l||j[0]==="*"){p=e[j[1]+" "+k];if(p){o=e[o],o===!0?n=p:p===!0&&(n=o);break}}}}!n&&!p&&f.error("No conversion from "+m.replace(" "," to ")),n!==!0&&(c=n?n(c):p(o(c)))}}return c}function cd(a,c,d){var e=a.contents,f=a.dataTypes,g=a.responseFields,h,i,j,k;for(i in g)i in d&&(c[g[i]]=d[i]);while(f[0]==="*")f.shift(),h===b&&(h=a.mimeType||c.getResponseHeader("content-type"));if(h)for(i in e)if(e[i]&&e[i].test(h)){f.unshift(i);break}if(f[0]in d)j=f[0];else{for(i in d){if(!f[0]||a.converters[i+" "+f[0]]){j=i;break}k||(k=i)}j=j||k}if(j){j!==f[0]&&f.unshift(j);return d[j]}}function cc(a,b,c,d){if(f.isArray(b))f.each(b,function(b,e){c||bG.test(a)?d(a,e):cc(a+"["+(typeof e=="object"||f.isArray(e)?b:"")+"]",e,c,d)});else if(!c&&b!=null&&typeof b=="object")for(var e in b)cc(a+"["+e+"]",b[e],c,d);else d(a,b)}function cb(a,c){var d,e,g=f.ajaxSettings.flatOptions||{};for(d in c)c[d]!==b&&((g[d]?a:e||(e={}))[d]=c[d]);e&&f.extend(!0,a,e)}function ca(a,c,d,e,f,g){f=f||c.dataTypes[0],g=g||{},g[f]=!0;var h=a[f],i=0,j=h?h.length:0,k=a===bV,l;for(;i<j&&(k||!l);i++)l=h[i](c,d,e),typeof l=="string"&&(!k||g[l]?l=b:(c.dataTypes.unshift(l),l=ca(a,c,d,e,l,g)));(k||!l)&&!g["*"]&&(l=ca(a,c,d,e,"*",g));return l}function b_(a){return function(b,c){typeof b!="string"&&(c=b,b="*");if(f.isFunction(c)){var d=b.toLowerCase().split(bR),e=0,g=d.length,h,i,j;for(;e<g;e++)h=d[e],j=/^\+/.test(h),j&&(h=h.substr(1)||"*"),i=a[h]=a[h]||[],i[j?"unshift":"push"](c)}}}function bE(a,b,c){var d=b==="width"?a.offsetWidth:a.offsetHeight,e=b==="width"?bz:bA;if(d>0){c!=="border"&&f.each(e,function(){c||(d-=parseFloat(f.css(a,"padding"+this))||0),c==="margin"?d+=parseFloat(f.css(a,c+this))||0:d-=parseFloat(f.css(a,"border"+this+"Width"))||0});return d+"px"}d=bB(a,b,b);if(d<0||d==null)d=a.style[b]||0;d=parseFloat(d)||0,c&&f.each(e,function(){d+=parseFloat(f.css(a,"padding"+this))||0,c!=="padding"&&(d+=parseFloat(f.css(a,"border"+this+"Width"))||0),c==="margin"&&(d+=parseFloat(f.css(a,c+this))||0)});return d+"px"}function br(a,b){b.src?f.ajax({url:b.src,async:!1,dataType:"script"}):f.globalEval((b.text||b.textContent||b.innerHTML||"").replace(bi,"/*$0*/")),b.parentNode&&b.parentNode.removeChild(b)}function bq(a){var b=(a.nodeName||"").toLowerCase();b==="input"?bp(a):b!=="script"&&typeof a.getElementsByTagName!="undefined"&&f.grep(a.getElementsByTagName("input"),bp)}function bp(a){if(a.type==="checkbox"||a.type==="radio")a.defaultChecked=a.checked}function bo(a){return typeof a.getElementsByTagName!="undefined"?a.getElementsByTagName("*"):typeof a.querySelectorAll!="undefined"?a.querySelectorAll("*"):[]}function bn(a,b){var c;if(b.nodeType===1){b.clearAttributes&&b.clearAttributes(),b.mergeAttributes&&b.mergeAttributes(a),c=b.nodeName.toLowerCase();if(c==="object")b.outerHTML=a.outerHTML;else if(c!=="input"||a.type!=="checkbox"&&a.type!=="radio"){if(c==="option")b.selected=a.defaultSelected;else if(c==="input"||c==="textarea")b.defaultValue=a.defaultValue}else a.checked&&(b.defaultChecked=b.checked=a.checked),b.value!==a.value&&(b.value=a.value);b.removeAttribute(f.expando)}}function bm(a,b){if(b.nodeType===1&&!!f.hasData(a)){var c,d,e,g=f._data(a),h=f._data(b,g),i=g.events;if(i){delete h.handle,h.events={};for(c in i)for(d=0,e=i[c].length;d<e;d++)f.event.add(b,c+(i[c][d].namespace?".":"")+i[c][d].namespace,i[c][d],i[c][d].data)}h.data&&(h.data=f.extend({},h.data))}}function bl(a,b){return f.nodeName(a,"table")?a.getElementsByTagName("tbody")[0]||a.appendChild(a.ownerDocument.createElement("tbody")):a}function X(a){var b=Y.split(" "),c=a.createDocumentFragment();if(c.createElement)while(b.length)c.createElement(b.pop());return c}function W(a,b,c){b=b||0;if(f.isFunction(b))return f.grep(a,function(a,d){var e=!!b.call(a,d,a);return e===c});if(b.nodeType)return f.grep(a,function(a,d){return a===b===c});if(typeof b=="string"){var d=f.grep(a,function(a){return a.nodeType===1});if(R.test(b))return f.filter(b,d,!c);b=f.filter(b,d)}return f.grep(a,function(a,d){return f.inArray(a,b)>=0===c})}function V(a){return!a||!a.parentNode||a.parentNode.nodeType===11}function N(){return!0}function M(){return!1}function n(a,b,c){var d=b+"defer",e=b+"queue",g=b+"mark",h=f._data(a,d);h&&(c==="queue"||!f._data(a,e))&&(c==="mark"||!f._data(a,g))&&setTimeout(function(){!f._data(a,e)&&!f._data(a,g)&&(f.removeData(a,d,!0),h.fire())},0)}function m(a){for(var b in a){if(b==="data"&&f.isEmptyObject(a[b]))continue;if(b!=="toJSON")return!1}return!0}function l(a,c,d){if(d===b&&a.nodeType===1){var e="data-"+c.replace(k,"-$1").toLowerCase();d=a.getAttribute(e);if(typeof d=="string"){try{d=d==="true"?!0:d==="false"?!1:d==="null"?null:f.isNumeric(d)?parseFloat(d):j.test(d)?f.parseJSON(d):d}catch(g){}f.data(a,c,d)}else d=b}return d}function h(a){var b=g[a]={},c,d;a=a.split(/\s+/);for(c=0,d=a.length;c<d;c++)b[a[c]]=!0;return b}var c=a.document,d=a.navigator,e=a.location,f=function(){function K(){if(!e.isReady){try{c.documentElement.doScroll("left")}catch(a){setTimeout(K,1);return}e.ready()}}var e=function(a,b){return new e.fn.init(a,b,h)},f=a.jQuery,g=a.$,h,i=/^(?:[^#<]*(<[\w\W]+>)[^>]*$|#([\w\-]*)$)/,j=/\S/,k=/^\s+/,l=/\s+$/,m=/\d/,n=/^<(\w+)\s*\/?>(?:<\/\1>)?$/,o=/^[\],:{}\s]*$/,p=/\\(?:["\\\/bfnrt]|u[0-9a-fA-F]{4})/g,q=/"[^"\\\n\r]*"|true|false|null|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?/g,r=/(?:^|:|,)(?:\s*\[)+/g,s=/(webkit)[ \/]([\w.]+)/,t=/(opera)(?:.*version)?[ \/]([\w.]+)/,u=/(msie) ([\w.]+)/,v=/(mozilla)(?:.*? rv:([\w.]+))?/,w=/-([a-z]|[0-9])/ig,x=/^-ms-/,y=function(a,b){return(b+"").toUpperCase()},z=d.userAgent,A,B,C,D=Object.prototype.toString,E=Object.prototype.hasOwnProperty,F=Array.prototype.push,G=Array.prototype.slice,H=String.prototype.trim,I=Array.prototype.indexOf,J={};e.fn=e.prototype={constructor:e,init:function(a,d,f){var g,h,j,k;if(!a)return this;if(a.nodeType){this.context=this[0]=a,this.length=1;return this}if(a==="body"&&!d&&c.body){this.context=c,this[0]=c.body,this.selector=a,this.length=1;return this}if(typeof a=="string"){a.charAt(0)!=="<"||a.charAt(a.length-1)!==">"||a.length<3?g=i.exec(a):g=[null,a,null];if(g&&(g[1]||!d)){if(g[1]){d=d instanceof e?d[0]:d,k=d?d.ownerDocument||d:c,j=n.exec(a),j?e.isPlainObject(d)?(a=[c.createElement(j[1])],e.fn.attr.call(a,d,!0)):a=[k.createElement(j[1])]:(j=e.buildFragment([g[1]],[k]),a=(j.cacheable?e.clone(j.fragment):j.fragment).childNodes);return e.merge(this,a)}h=c.getElementById(g[2]);if(h&&h.parentNode){if(h.id!==g[2])return f.find(a);this.length=1,this[0]=h}this.context=c,this.selector=a;return this}return!d||d.jquery?(d||f).find(a):this.constructor(d).find(a)}if(e.isFunction(a))return f.ready(a);a.selector!==b&&(this.selector=a.selector,this.context=a.context);return e.makeArray(a,this)},selector:"",jquery:"1.7",length:0,size:function(){return this.length},toArray:function(){return G.call(this,0)},get:function(a){return a==null?this.toArray():a<0?this[this.length+a]:this[a]},pushStack:function(a,b,c){var d=this.constructor();e.isArray(a)?F.apply(d,a):e.merge(d,a),d.prevObject=this,d.context=this.context,b==="find"?d.selector=this.selector+(this.selector?" ":"")+c:b&&(d.selector=this.selector+"."+b+"("+c+")");return d},each:function(a,b){return e.each(this,a,b)},ready:function(a){e.bindReady(),B.add(a);return this},eq:function(a){return 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(G.apply(this,arguments),"slice",G.call(arguments).join(","))},map:function(a){return this.pushStack(e.map(this,function(b,c){return a.call(b,c,b)}))},end:function(){return this.prevObject||this.constructor(null)},push:F,sort:[].sort,splice:[].splice},e.fn.init.prototype=e.fn,e.extend=e.fn.extend=function(){var a,c,d,f,g,h,i=arguments[0]||{},j=1,k=arguments.length,l=!1;typeof i=="boolean"&&(l=i,i=arguments[1]||{},j=2),typeof i!="object"&&!e.isFunction(i)&&(i={}),k===j&&(i=this,--j);for(;j<k;j++)if((a=arguments[j])!=null)for(c in a){d=i[c],f=a[c];if(i===f)continue;l&&f&&(e.isPlainObject(f)||(g=e.isArray(f)))?(g?(g=!1,h=d&&e.isArray(d)?d:[]):h=d&&e.isPlainObject(d)?d:{},i[c]=e.extend(l,h,f)):f!==b&&(i[c]=f)}return i},e.extend({noConflict:function(b){a.$===e&&(a.$=g),b&&a.jQuery===e&&(a.jQuery=f);return e},isReady:!1,readyWait:1,holdReady:function(a){a?e.readyWait++:e.ready(!0)},ready:function(a){if(a===!0&&!--e.readyWait||a!==!0&&!e.isReady){if(!c.body)return setTimeout(e.ready,1);e.isReady=!0;if(a!==!0&&--e.readyWait>0)return;B.fireWith(c,[e]),e.fn.trigger&&e(c).trigger("ready").unbind("ready")}},bindReady:function(){if(!B){B=e.Callbacks("once memory");if(c.readyState==="complete")return setTimeout(e.ready,1);if(c.addEventListener)c.addEventListener("DOMContentLoaded",C,!1),a.addEventListener("load",e.ready,!1);else if(c.attachEvent){c.attachEvent("onreadystatechange",C),a.attachEvent("onload",e.ready);var b=!1;try{b=a.frameElement==null}catch(d){}c.documentElement.doScroll&&b&&K()}}},isFunction:function(a){return e.type(a)==="function"},isArray:Array.isArray||function(a){return e.type(a)==="array"},isWindow:function(a){return a&&typeof a=="object"&&"setInterval"in a},isNumeric:function(a){return a!=null&&m.test(a)&&!isNaN(a)},type:function(a){return a==null?String(a):J[D.call(a)]||"object"},isPlainObject:function(a){if(!a||e.type(a)!=="object"||a.nodeType||e.isWindow(a))return!1;try{if(a.constructor&&!E.call(a,"constructor")&&!E.call(a.constructor.prototype,"isPrototypeOf"))return!1}catch(c){return!1}var d;for(d in a);return d===b||E.call(a,d)},isEmptyObject:function(a){for(var b in a)return!1;return!0},error:function(a){throw a},parseJSON:function(b){if(typeof b!="string"||!b)return null;b=e.trim(b);if(a.JSON&&a.JSON.parse)return a.JSON.parse(b);if(o.test(b.replace(p,"@").replace(q,"]").replace(r,"")))return(new Function("return "+b))();e.error("Invalid JSON: "+b)},parseXML:function(c){var d,f;try{a.DOMParser?(f=new DOMParser,d=f.parseFromString(c,"text/xml")):(d=new ActiveXObject("Microsoft.XMLDOM"),d.async="false",d.loadXML(c))}catch(g){d=b}(!d||!d.documentElement||d.getElementsByTagName("parsererror").length)&&e.error("Invalid XML: "+c);return d},noop:function(){},globalEval:function(b){b&&j.test(b)&&(a.execScript||function(b){a.eval.call(a,b)})(b)},camelCase:function(a){return a.replace(x,"ms-").replace(w,y)},nodeName:function(a,b){return a.nodeName&&a.nodeName.toUpperCase()===b.toUpperCase()},each:function(a,c,d){var f,g=0,h=a.length,i=h===b||e.isFunction(a);if(d){if(i){for(f in a)if(c.apply(a[f],d)===!1)break}else for(;g<h;)if(c.apply(a[g++],d)===!1)break}else if(i){for(f in a)if(c.call(a[f],f,a[f])===!1)break}else for(;g<h;)if(c.call(a[g],g,a[g++])===!1)break;return a},trim:H?function(a){return a==null?"":H.call(a)}:function(a){return a==null?"":(a+"").replace(k,"").replace(l,"")},makeArray:function(a,b){var c=b||[];if(a!=null){var d=e.type(a);a.length==null||d==="string"||d==="function"||d==="regexp"||e.isWindow(a)?F.call(c,a):e.merge(c,a)}return c},inArray:function(a,b,c){var d;if(b){if(I)return I.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=a.length,e=0;if(typeof c.length=="number")for(var f=c.length;e<f;e++)a[d++]=c[e];else while(c[e]!==b)a[d++]=c[e++];a.length=d;return a},grep:function(a,b,c){var d=[],e;c=!!c;for(var f=0,g=a.length;f<g;f++)e=!!b(a[f],f),c!==e&&d.push(a[f]);return d},map:function(a,c,d){var f,g,h=[],i=0,j=a.length,k=a instanceof e||j!==b&&typeof j=="number"&&(j>0&&a[0]&&a[j-1]||j===0||e.isArray(a));if(k)for(;i<j;i++)f=c(a[i],i,d),f!=null&&(h[h.length]=f);else for(g in a)f=c(a[g],g,d),f!=null&&(h[h.length]=f);return h.concat.apply([],h)},guid:1,proxy:function(a,c){if(typeof c=="string"){var d=a[c];c=a,a=d}if(!e.isFunction(a))return b;var f=G.call(arguments,2),g=function(){return a.apply(c,f.concat(G.call(arguments)))};g.guid=a.guid=a.guid||g.guid||e.guid++;return g},access:function(a,c,d,f,g,h){var i=a.length;if(typeof c=="object"){for(var j in c)e.access(a,j,c[j],f,g,d);return a}if(d!==b){f=!h&&f&&e.isFunction(d);for(var k=0;k<i;k++)g(a[k],c,f?d.call(a[k],k,g(a[k],c)):d,h);return a}return i?g(a[0],c):b},now:function(){return(new Date).getTime()},uaMatch:function(a){a=a.toLowerCase();var b=s.exec(a)||t.exec(a)||u.exec(a)||a.indexOf("compatible")<0&&v.exec(a)||[];return{browser:b[1]||"",version:b[2]||"0"}},sub:function(){function a(b,c){return new a.fn.init(b,c)}e.extend(!0,a,this),a.superclass=this,a.fn=a.prototype=this(),a.fn.constructor=a,a.sub=this.sub,a.fn.init=function(d,f){f&&f instanceof e&&!(f instanceof a)&&(f=a(f));return e.fn.init.call(this,d,f,b)},a.fn.init.prototype=a.fn;var b=a(c);return a},browser:{}}),e.each("Boolean Number String Function Array Date RegExp Object".split(" "),function(a,b){J["[object "+b+"]"]=b.toLowerCase()}),A=e.uaMatch(z),A.browser&&(e.browser[A.browser]=!0,e.browser.version=A.version),e.browser.webkit&&(e.browser.safari=!0),j.test(" ")&&(k=/^[\s\xA0]+/,l=/[\s\xA0]+$/),h=e(c),c.addEventListener?C=function(){c.removeEventListener("DOMContentLoaded",C,!1),e.ready()}:c.attachEvent&&(C=function(){c.readyState==="complete"&&(c.detachEvent("onreadystatechange",C),e.ready())}),typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return e});return e}(),g={};f.Callbacks=function(a){a=a?g[a]||h(a):{};var c=[],d=[],e,i,j,k,l,m=function(b){var d,e,g,h,i;for(d=0,e=b.length;d<e;d++)g=b[d],h=f.type(g),h==="array"?m(g):h==="function"&&(!a.unique||!o.has(g))&&c.push(g)},n=function(b,f){f=f||[],e=!a.memory||[b,f],i=!0,l=j||0,j=0,k=c.length;for(;c&&l<k;l++)if(c[l].apply(b,f)===!1&&a.stopOnFalse){e=!0;break}i=!1,c&&(a.once?e===!0?o.disable():c=[]:d&&d.length&&(e=d.shift(),o.fireWith(e[0],e[1])))},o={add:function(){if(c){var a=c.length;m(arguments),i?k=c.length:e&&e!==!0&&(j=a,n(e[0],e[1]))}return this},remove:function(){if(c){var b=arguments,d=0,e=b.length;for(;d<e;d++)for(var f=0;f<c.length;f++)if(b[d]===c[f]){i&&f<=k&&(k--,f<=l&&l--),c.splice(f--,1);if(a.unique)break}}return this},has:function(a){if(c){var b=0,d=c.length;for(;b<d;b++)if(a===c[b])return!0}return!1},empty:function(){c=[];return this},disable:function(){c=d=e=b;return this},disabled:function(){return!c},lock:function(){d=b,(!e||e===!0)&&o.disable();return this},locked:function(){return!d},fireWith:function(b,c){d&&(i?a.once||d.push([b,c]):(!a.once||!e)&&n(b,c));return this},fire:function(){o.fireWith(this,arguments);return this},fired:function(){return!!e}};return o};var i=[].slice;f.extend({Deferred:function(a){var b=f.Callbacks("once memory"),c=f.Callbacks("once memory"),d=f.Callbacks("memory"),e="pending",g={resolve:b,reject:c,notify:d},h={done:b.add,fail:c.add,progress:d.add,state:function(){return e},isResolved:b.fired,isRejected:c.fired,then:function(a,b,c){i.done(a).fail(b).progress(c);return this},always:function(){return i.done.apply(i,arguments).fail.apply(i,arguments)},pipe:function(a,b,c){return f.Deferred(function(d){f.each({done:[a,"resolve"],fail:[b,"reject"],progress:[c,"notify"]},function(a,b){var c=b[0],e=b[1],g;f.isFunction(c)?i[a](function(){g=c.apply(this,arguments),g&&f.isFunction(g.promise)?g.promise().then(d.resolve,d.reject,d.notify):d[e+"With"](this===i?d:this,[g])}):i[a](d[e])})}).promise()},promise:function(a){if(a==null)a=h;else for(var b in h)a[b]=h[b];return a}},i=h.promise({}),j;for(j in g)i[j]=g[j].fire,i[j+"With"]=g[j].fireWith;i.done(function(){e="resolved"},c.disable,d.lock).fail(function(){e="rejected"},b.disable,d.lock),a&&a.call(i,i);return i},when:function(a){function m(a){return function(b){e[a]=arguments.length>1?i.call(arguments,0):b,j.notifyWith(k,e)}}function l(a){return function(c){b[a]=arguments.length>1?i.call(arguments,0):c,--g||j.resolveWith(j,b)}}var b=i.call(arguments,0),c=0,d=b.length,e=Array(d),g=d,h=d,j=d<=1&&a&&f.isFunction(a.promise)?a:f.Deferred(),k=j.promise();if(d>1){for(;c<d;c++)b[c]&&b[c].promise&&f.isFunction(b[c].promise)?b[c].promise().then(l(c),j.reject,m(c)):--g;g||j.resolveWith(j,b)}else j!==a&&j.resolveWith(j,d?[a]:[]);return k}}),f.support=function(){var a=c.createElement("div"),b=c.documentElement,d,e,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u;a.setAttribute("className","t"),a.innerHTML=" <link/><table></table><a href='/a' style='top:1px;float:left;opacity:.55;'>a</a><input type='checkbox'/><nav></nav>",d=a.getElementsByTagName("*"),e=a.getElementsByTagName("a")[0];if(!d||!d.length||!e)return{};g=c.createElement("select"),h=g.appendChild(c.createElement("option")),i=a.getElementsByTagName("input")[0],k={leadingWhitespace:a.firstChild.nodeType===3,tbody:!a.getElementsByTagName("tbody").length,htmlSerialize:!!a.getElementsByTagName("link").length,style:/top/.test(e.getAttribute("style")),hrefNormalized:e.getAttribute("href")==="/a",opacity:/^0.55/.test(e.style.opacity),cssFloat:!!e.style.cssFloat,unknownElems:!!a.getElementsByTagName("nav").length,checkOn:i.value==="on",optSelected:h.selected,getSetAttribute:a.className!=="t",enctype:!!c.createElement("form").enctype,submitBubbles:!0,changeBubbles:!0,focusinBubbles:!1,deleteExpando:!0,noCloneEvent:!0,inlineBlockNeedsLayout:!1,shrinkWrapBlocks:!1,reliableMarginRight:!0},i.checked=!0,k.noCloneChecked=i.cloneNode(!0).checked,g.disabled=!0,k.optDisabled=!h.disabled;try{delete a.test}catch(v){k.deleteExpando=!1}!a.addEventListener&&a.attachEvent&&a.fireEvent&&(a.attachEvent("onclick",function(){k.noCloneEvent=!1}),a.cloneNode(!0).fireEvent("onclick")),i=c.createElement("input"),i.value="t",i.setAttribute("type","radio"),k.radioValue=i.value==="t",i.setAttribute("checked","checked"),a.appendChild(i),l=c.createDocumentFragment(),l.appendChild(a.lastChild),k.checkClone=l.cloneNode(!0).cloneNode(!0).lastChild.checked,a.innerHTML="",a.style.width=a.style.paddingLeft="1px",m=c.getElementsByTagName("body")[0],o=c.createElement(m?"div":"body"),p={visibility:"hidden",width:0,height:0,border:0,margin:0,background:"none"},m&&f.extend(p,{position:"absolute",left:"-999px",top:"-999px"});for(t in p)o.style[t]=p[t];o.appendChild(a),n=m||b,n.insertBefore(o,n.firstChild),k.appendChecked=i.checked,k.boxModel=a.offsetWidth===2,"zoom"in a.style&&(a.style.display="inline",a.style.zoom=1,k.inlineBlockNeedsLayout=a.offsetWidth===2,a.style.display="",a.innerHTML="<div style='width:4px;'></div>",k.shrinkWrapBlocks=a.offsetWidth!==2),a.innerHTML="<table><tr><td style='padding:0;border:0;display:none'></td><td>t</td></tr></table>",q=a.getElementsByTagName("td"),u=q[0].offsetHeight===0,q[0].style.display="",q[1].style.display="none",k.reliableHiddenOffsets=u&&q[0].offsetHeight===0,a.innerHTML="",c.defaultView&&c.defaultView.getComputedStyle&&(j=c.createElement("div"),j.style.width="0",j.style.marginRight="0",a.appendChild(j),k.reliableMarginRight=(parseInt((c.defaultView.getComputedStyle(j,null)||{marginRight:0}).marginRight,10)||0)===0);if(a.attachEvent)for(t in{submit:1,change:1,focusin:1})s="on"+t,u=s in a,u||(a.setAttribute(s,"return;"),u=typeof a[s]=="function"),k[t+"Bubbles"]=u;f(function(){var a,b,d,e,g,h,i=1,j="position:absolute;top:0;left:0;width:1px;height:1px;margin:0;",l="visibility:hidden;border:0;",n="style='"+j+"border:5px solid #000;padding:0;'",p="<div "+n+"><div></div></div>"+"<table "+n+" cellpadding='0' cellspacing='0'>"+"<tr><td></td></tr></table>";m=c.getElementsByTagName("body")[0];!m||(a=c.createElement("div"),a.style.cssText=l+"width:0;height:0;position:static;top:0;margin-top:"+i+"px",m.insertBefore(a,m.firstChild),o=c.createElement("div"),o.style.cssText=j+l,o.innerHTML=p,a.appendChild(o),b=o.firstChild,d=b.firstChild,g=b.nextSibling.firstChild.firstChild,h={doesNotAddBorder:d.offsetTop!==5,doesAddBorderForTableAndCells:g.offsetTop===5},d.style.position="fixed",d.style.top="20px",h.fixedPosition=d.offsetTop===20||d.offsetTop===15,d.style.position=d.style.top="",b.style.overflow="hidden",b.style.position="relative",h.subtractsBorderForOverflowNotVisible=d.offsetTop===-5,h.doesNotIncludeMarginInBodyOffset=m.offsetTop!==i,m.removeChild(a),o=a=null,f.extend(k,h))}),o.innerHTML="",n.removeChild(o),o=l=g=h=m=j=a=i=null;return k}(),f.boxModel=f.support.boxModel;var j=/^(?:\{.*\}|\[.*\])$/,k=/([A-Z])/g;f.extend({cache:{},uuid:0,expando:"jQuery"+(f.fn.jquery+Math.random()).replace(/\D/g,""),noData:{embed:!0,object:"clsid:D27CDB6E-AE6D-11cf-96B8-444553540000",applet:!0},hasData:function(a){a=a.nodeType?f.cache[a[f.expando]]:a[f.expando];return!!a&&!m(a)},data:function(a,c,d,e){if(!!f.acceptData(a)){var g,h,i,j=f.expando,k=typeof c=="string",l=a.nodeType,m=l?f.cache:a,n=l?a[f.expando]:a[f.expando]&&f.expando,o=c==="events";if((!n||!m[n]||!o&&!e&&!m[n].data)&&k&&d===b)return;n||(l?a[f.expando]=n=++f.uuid:n=f.expando),m[n]||(m[n]={},l||(m[n].toJSON=f.noop));if(typeof c=="object"||typeof c=="function")e?m[n]=f.extend(m[n],c):m[n].data=f.extend(m[n].data,c);g=h=m[n],e||(h.data||(h.data={}),h=h.data),d!==b&&(h[f.camelCase(c)]=d);if(o&&!h[c])return g.events;k?(i=h[c],i==null&&(i=h[f.camelCase(c)])):i=h;return i}},removeData:function(a,b,c){if(!!f.acceptData(a)){var d,e,g,h=f.expando,i=a.nodeType,j=i?f.cache:a,k=i?a[f.expando]:f.expando;if(!j[k])return;if(b){d=c?j[k]:j[k].data;if(d){f.isArray(b)?b=b:b in d?b=[b]:(b=f.camelCase(b),b in d?b=[b]:b=b.split(" "));for(e=0,g=b.length;e<g;e++)delete d[b[e]];if(!(c?m:f.isEmptyObject)(d))return}}if(!c){delete j[k].data;if(!m(j[k]))return}f.support.deleteExpando||!j.setInterval?delete j[k]:j[k]=null,i&&(f.support.deleteExpando?delete a[f.expando]:a.removeAttribute?a.removeAttribute(f.expando):a[f.expando]=null)}},_data:function(a,b,c){return f.data(a,b,c,!0)},acceptData:function(a){if(a.nodeName){var b=f.noData[a.nodeName.toLowerCase()];if(b)return b!==!0&&a.getAttribute("classid")===b}return!0}}),f.fn.extend({data:function(a,c){var d,e,g,h=null;if(typeof a=="undefined"){if(this.length){h=f.data(this[0]);if(this[0].nodeType===1&&!f._data(this[0],"parsedAttrs")){e=this[0].attributes;for(var i=0,j=e.length;i<j;i++)g=e[i].name,g.indexOf("data-")===0&&(g=f.camelCase(g.substring(5)),l(this[0],g,h[g]));f._data(this[0],"parsedAttrs",!0)}}return h}if(typeof a=="object")return this.each(function(){f.data(this,a)});d=a.split("."),d[1]=d[1]?"."+d[1]:"";if(c===b){h=this.triggerHandler("getData"+d[1]+"!",[d[0]]),h===b&&this.length&&(h=f.data(this[0],a),h=l(this[0],a,h));return h===b&&d[1]?this.data(d[0]):h}return this.each(function(){var b=f(this),e=[d[0],c];b.triggerHandler("setData"+d[1]+"!",e),f.data(this,a,c),b.triggerHandler("changeData"+d[1]+"!",e)})},removeData:function(a){return this.each(function(){f.removeData(this,a)})}}),f.extend({_mark:function(a,b){a&&(b=(b||"fx")+"mark",f._data(a,b,(f._data(a,b)||0)+1))},_unmark:function(a,b,c){a!==!0&&(c=b,b=a,a=!1);if(b){c=c||"fx";var d=c+"mark",e=a?0:(f._data(b,d)||1)-1;e?f._data(b,d,e):(f.removeData(b,d,!0),n(b,c,"mark"))}},queue:function(a,b,c){var d;if(a){b=(b||"fx")+"queue",d=f._data(a,b),c&&(!d||f.isArray(c)?d=f._data(a,b,f.makeArray(c)):d.push(c));return d||[]}},dequeue:function(a,b){b=b||"fx";var c=f.queue(a,b),d=c.shift(),e={};d==="inprogress"&&(d=c.shift()),d&&(b==="fx"&&c.unshift("inprogress"),f._data(a,b+".run",e),d.call(a,function(){f.dequeue(a,b)},e)),c.length||(f.removeData(a,b+"queue "+b+".run",!0),n(a,b,"queue"))}}),f.fn.extend({queue:function(a,c){typeof a!="string"&&(c=a,a="fx");if(c===b)return f.queue(this[0],a);return this.each(function(){var b=f.queue(this,a,c);a==="fx"&&b[0]!=="inprogress"&&f.dequeue(this,a)})},dequeue:function(a){return this.each(function(){f.dequeue(this,a)})},delay:function(a,b){a=f.fx?f.fx.speeds[a]||a:a,b=b||"fx";return 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){function m(){--h||d.resolveWith(e,[e])}typeof a!="string"&&(c=a,a=b),a=a||"fx";var d=f.Deferred(),e=this,g=e.length,h=1,i=a+"defer",j=a+"queue",k=a+"mark",l;while(g--)if(l=f.data(e[g],i,b,!0)||(f.data(e[g],j,b,!0)||f.data(e[g],k,b,!0))&&f.data(e[g],i,f.Callbacks("once memory"),!0))h++,l.add(m);m();return d.promise()}});var o=/[\n\t\r]/g,p=/\s+/,q=/\r/g,r=/^(?:button|input)$/i,s=/^(?:button|input|object|select|textarea)$/i,t=/^a(?:rea)?$/i,u=/^(?:autofocus|autoplay|async|checked|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped|selected)$/i,v=f.support.getSetAttribute,w,x,y;f.fn.extend({attr:function(a,b){return f.access(this,a,b,!0,f.attr)},removeAttr:function(a){return this.each(function(){f.removeAttr(this,a)})},prop:function(a,b){return f.access(this,a,b,!0,f.prop)},removeProp:function(a){a=f.propFix[a]||a;return this.each(function(){try{this[a]=b,delete this[a]}catch(c){}})},addClass:function(a){var b,c,d,e,g,h,i;if(f.isFunction(a))return this.each(function(b){f(this).addClass(a.call(this,b,this.className))});if(a&&typeof a=="string"){b=a.split(p);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{g=" "+e.className+" ";for(h=0,i=b.length;h<i;h++)~g.indexOf(" "+b[h]+" ")||(g+=b[h]+" ");e.className=f.trim(g)}}}return this},removeClass:function(a){var c,d,e,g,h,i,j;if(f.isFunction(a))return this.each(function(b){f(this).removeClass(a.call(this,b,this.className))});if(a&&typeof a=="string"||a===b){c=(a||"").split(p);for(d=0,e=this.length;d<e;d++){g=this[d];if(g.nodeType===1&&g.className)if(a){h=(" "+g.className+" ").replace(o," ");for(i=0,j=c.length;i<j;i++)h=h.replace(" "+c[i]+" "," ");g.className=f.trim(h)}else g.className=""}}return this},toggleClass:function(a,b){var c=typeof a,d=typeof b=="boolean";if(f.isFunction(a))return this.each(function(c){f(this).toggleClass(a.call(this,c,this.className,b),b)});return this.each(function(){if(c==="string"){var e,g=0,h=f(this),i=b,j=a.split(p);while(e=j[g++])i=d?i:!h.hasClass(e),h[i?"addClass":"removeClass"](e)}else if(c==="undefined"||c==="boolean")this.className&&f._data(this,"__className__",this.className),this.className=this.className||a===!1?"":f._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,g=this[0];if(!arguments.length){if(g){c=f.valHooks[g.nodeName.toLowerCase()]||f.valHooks[g.type];if(c&&"get"in c&&(d=c.get(g,"value"))!==b)return d;d=g.value;return typeof d=="string"?d.replace(q,""):d==null?"":d}return b}e=f.isFunction(a);return this.each(function(d){var g=f(this),h;if(this.nodeType===1){e?h=a.call(this,d,g.val()):h=a,h==null?h="":typeof h=="number"?h+="":f.isArray(h)&&(h=f.map(h,function(a){return a==null?"":a+""})),c=f.valHooks[this.nodeName.toLowerCase()]||f.valHooks[this.type];if(!c||!("set"in c)||c.set(this,h,"value")===b)this.value=h}})}}),f.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,g=a.selectedIndex,h=[],i=a.options,j=a.type==="select-one";if(g<0)return null;c=j?g:0,d=j?g+1:i.length;for(;c<d;c++){e=i[c];if(e.selected&&(f.support.optDisabled?!e.disabled:e.getAttribute("disabled")===null)&&(!e.parentNode.disabled||!f.nodeName(e.parentNode,"optgroup"))){b=f(e).val();if(j)return b;h.push(b)}}if(j&&!h.length&&i.length)return f(i[g]).val();return h},set:function(a,b){var c=f.makeArray(b);f(a).find("option").each(function(){this.selected=f.inArray(f(this).val(),c)>=0}),c.length||(a.selectedIndex=-1);return c}}},attrFn:{val:!0,css:!0,html:!0,text:!0,data:!0,width:!0,height:!0,offset:!0},attr:function(a,c,d,e){var g,h,i,j=a.nodeType;if(!a||j===3||j===8||j===2)return b;if(e&&c in f.attrFn)return f(a)[c](d);if(!("getAttribute"in a))return f.prop(a,c,d);i=j!==1||!f.isXMLDoc(a),i&&(c=c.toLowerCase(),h=f.attrHooks[c]||(u.test(c)?x:w));if(d!==b){if(d===null){f.removeAttr(a,c);return b}if(h&&"set"in h&&i&&(g=h.set(a,d,c))!==b)return g;a.setAttribute(c,""+d);return d}if(h&&"get"in h&&i&&(g=h.get(a,c))!==null)return g;g=a.getAttribute(c);return g===null?b:g},removeAttr:function(a,b){var c,d,e,g,h=0;if(a.nodeType===1){d=(b||"").split(p),g=d.length;for(;h<g;h++)e=d[h].toLowerCase(),c=f.propFix[e]||e,f.attr(a,e,""),a.removeAttribute(v?e:c),u.test(e)&&c in a&&(a[c]=!1)}},attrHooks:{type:{set:function(a,b){if(r.test(a.nodeName)&&a.parentNode)f.error("type property can't be changed");else if(!f.support.radioValue&&b==="radio"&&f.nodeName(a,"input")){var c=a.value;a.setAttribute("type",b),c&&(a.value=c);return b}}},value:{get:function(a,b){if(w&&f.nodeName(a,"button"))return w.get(a,b);return b in a?a.value:null},set:function(a,b,c){if(w&&f.nodeName(a,"button"))return w.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,g,h,i=a.nodeType;if(!a||i===3||i===8||i===2)return b;h=i!==1||!f.isXMLDoc(a),h&&(c=f.propFix[c]||c,g=f.propHooks[c]);return d!==b?g&&"set"in g&&(e=g.set(a,d,c))!==b?e:a[c]=d:g&&"get"in g&&(e=g.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):s.test(a.nodeName)||t.test(a.nodeName)&&a.href?0:b}}}}),f.attrHooks.tabindex=f.propHooks.tabIndex,x={get:function(a,c){var d,e=f.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;b===!1?f.removeAttr(a,c):(d=f.propFix[c]||c,d in a&&(a[d]=!0),a.setAttribute(c,c.toLowerCase()));return c}},v||(y={name:!0,id:!0},w=f.valHooks.button={get:function(a,c){var d;d=a.getAttributeNode(c);return d&&(y[c]?d.nodeValue!=="":d.specified)?d.nodeValue:b},set:function(a,b,d){var e=a.getAttributeNode(d);e||(e=c.createAttribute(d),a.setAttributeNode(e));return e.nodeValue=b+""}},f.attrHooks.tabindex.set=w.set,f.each(["width","height"],function(a,b){f.attrHooks[b]=f.extend(f.attrHooks[b],{set:function(a,c){if(c===""){a.setAttribute(b,"auto");return c}}})}),f.attrHooks.contenteditable={get:w.get,set:function(a,b,c){b===""&&(b="false"),w.set(a,b,c)}}),f.support.hrefNormalized||f.each(["href","src","width","height"],function(a,c){f.attrHooks[c]=f.extend(f.attrHooks[c],{get:function(a){var d=a.getAttribute(c,2);return d===null?b:d}})}),f.support.style||(f.attrHooks.style={get:function(a){return a.style.cssText.toLowerCase()||b},set:function(a,b){return a.style.cssText=""+b}}),f.support.optSelected||(f.propHooks.selected=f.extend(f.propHooks.selected,{get:function(a){var b=a.parentNode;b&&(b.selectedIndex,b.parentNode&&b.parentNode.selectedIndex);return null}})),f.support.enctype||(f.propFix.enctype="encoding"),f.support.checkOn||f.each(["radio","checkbox"],function(){f.valHooks[this]={get:function(a){return a.getAttribute("value")===null?"on":a.value}}}),f.each(["radio","checkbox"],function(){f.valHooks[this]=f.extend(f.valHooks[this],{set:function(a,b){if(f.isArray(b))return a.checked=f.inArray(f(a).val(),b)>=0}})});var z=/\.(.*)$/,A=/^(?:textarea|input|select)$/i,B=/\./g,C=/ /g,D=/[^\w\s.|`]/g,E=/^([^\.]*)?(?:\.(.+))?$/,F=/\bhover(\.\S+)?/,G=/^key/,H=/^(?:mouse|contextmenu)|click/,I=/^(\w*)(?:#([\w\-]+))?(?:\.([\w\-]+))?$/,J=function(a){var b=I.exec(a);b&&
(b[1]=(b[1]||"").toLowerCase(),b[3]=b[3]&&new RegExp("(?:^|\\s)"+b[3]+"(?:\\s|$)"));return b},K=function(a,b){return(!b[1]||a.nodeName.toLowerCase()===b[1])&&(!b[2]||a.id===b[2])&&(!b[3]||b[3].test(a.className))},L=function(a){return f.event.special.hover?a:a.replace(F,"mouseenter$1 mouseleave$1")};f.event={add:function(a,c,d,e,g){var h,i,j,k,l,m,n,o,p,q,r,s;if(!(a.nodeType===3||a.nodeType===8||!c||!d||!(h=f._data(a)))){d.handler&&(p=d,d=p.handler),d.guid||(d.guid=f.guid++),j=h.events,j||(h.events=j={}),i=h.handle,i||(h.handle=i=function(a){return typeof f!="undefined"&&(!a||f.event.triggered!==a.type)?f.event.dispatch.apply(i.elem,arguments):b},i.elem=a),c=L(c).split(" ");for(k=0;k<c.length;k++){l=E.exec(c[k])||[],m=l[1],n=(l[2]||"").split(".").sort(),s=f.event.special[m]||{},m=(g?s.delegateType:s.bindType)||m,s=f.event.special[m]||{},o=f.extend({type:m,origType:l[1],data:e,handler:d,guid:d.guid,selector:g,namespace:n.join(".")},p),g&&(o.quick=J(g),!o.quick&&f.expr.match.POS.test(g)&&(o.isPositional=!0)),r=j[m];if(!r){r=j[m]=[],r.delegateCount=0;if(!s.setup||s.setup.call(a,e,n,i)===!1)a.addEventListener?a.addEventListener(m,i,!1):a.attachEvent&&a.attachEvent("on"+m,i)}s.add&&(s.add.call(a,o),o.handler.guid||(o.handler.guid=d.guid)),g?r.splice(r.delegateCount++,0,o):r.push(o),f.event.global[m]=!0}a=null}},global:{},remove:function(a,b,c,d){var e=f.hasData(a)&&f._data(a),g,h,i,j,k,l,m,n,o,p,q;if(!!e&&!!(m=e.events)){b=L(b||"").split(" ");for(g=0;g<b.length;g++){h=E.exec(b[g])||[],i=h[1],j=h[2];if(!i){j=j?"."+j:"";for(l in m)f.event.remove(a,l+j,c,d);return}n=f.event.special[i]||{},i=(d?n.delegateType:n.bindType)||i,p=m[i]||[],k=p.length,j=j?new RegExp("(^|\\.)"+j.split(".").sort().join("\\.(?:.*\\.)?")+"(\\.|$)"):null;if(c||j||d||n.remove)for(l=0;l<p.length;l++){q=p[l];if(!c||c.guid===q.guid)if(!j||j.test(q.namespace))if(!d||d===q.selector||d==="**"&&q.selector)p.splice(l--,1),q.selector&&p.delegateCount--,n.remove&&n.remove.call(a,q)}else p.length=0;p.length===0&&k!==p.length&&((!n.teardown||n.teardown.call(a,j)===!1)&&f.removeEvent(a,i,e.handle),delete m[i])}f.isEmptyObject(m)&&(o=e.handle,o&&(o.elem=null),f.removeData(a,["events","handle"],!0))}},customEvent:{getData:!0,setData:!0,changeData:!0},trigger:function(c,d,e,g){if(!e||e.nodeType!==3&&e.nodeType!==8){var h=c.type||c,i=[],j,k,l,m,n,o,p,q,r,s;h.indexOf("!")>=0&&(h=h.slice(0,-1),k=!0),h.indexOf(".")>=0&&(i=h.split("."),h=i.shift(),i.sort());if((!e||f.event.customEvent[h])&&!f.event.global[h])return;c=typeof c=="object"?c[f.expando]?c:new f.Event(h,c):new f.Event(h),c.type=h,c.isTrigger=!0,c.exclusive=k,c.namespace=i.join("."),c.namespace_re=c.namespace?new RegExp("(^|\\.)"+i.join("\\.(?:.*\\.)?")+"(\\.|$)"):null,o=h.indexOf(":")<0?"on"+h:"",(g||!e)&&c.preventDefault();if(!e){j=f.cache;for(l in j)j[l].events&&j[l].events[h]&&f.event.trigger(c,d,j[l].handle.elem,!0);return}c.result=b,c.target||(c.target=e),d=d!=null?f.makeArray(d):[],d.unshift(c),p=f.event.special[h]||{};if(p.trigger&&p.trigger.apply(e,d)===!1)return;r=[[e,p.bindType||h]];if(!g&&!p.noBubble&&!f.isWindow(e)){s=p.delegateType||h,n=null;for(m=e.parentNode;m;m=m.parentNode)r.push([m,s]),n=m;n&&n===e.ownerDocument&&r.push([n.defaultView||n.parentWindow||a,s])}for(l=0;l<r.length;l++){m=r[l][0],c.type=r[l][1],q=(f._data(m,"events")||{})[c.type]&&f._data(m,"handle"),q&&q.apply(m,d),q=o&&m[o],q&&f.acceptData(m)&&q.apply(m,d);if(c.isPropagationStopped())break}c.type=h,c.isDefaultPrevented()||(!p._default||p._default.apply(e.ownerDocument,d)===!1)&&(h!=="click"||!f.nodeName(e,"a"))&&f.acceptData(e)&&o&&e[h]&&(h!=="focus"&&h!=="blur"||c.target.offsetWidth!==0)&&!f.isWindow(e)&&(n=e[o],n&&(e[o]=null),f.event.triggered=h,e[h](),f.event.triggered=b,n&&(e[o]=n));return c.result}},dispatch:function(c){c=f.event.fix(c||a.event);var d=(f._data(this,"events")||{})[c.type]||[],e=d.delegateCount,g=[].slice.call(arguments,0),h=!c.exclusive&&!c.namespace,i=(f.event.special[c.type]||{}).handle,j=[],k,l,m,n,o,p,q,r,s,t,u;g[0]=c,c.delegateTarget=this;if(e&&!c.target.disabled&&(!c.button||c.type!=="click"))for(m=c.target;m!=this;m=m.parentNode||this){o={},q=[];for(k=0;k<e;k++)r=d[k],s=r.selector,t=o[s],r.isPositional?t=(t||(o[s]=f(s))).index(m)>=0:t===b&&(t=o[s]=r.quick?K(m,r.quick):f(m).is(s)),t&&q.push(r);q.length&&j.push({elem:m,matches:q})}d.length>e&&j.push({elem:this,matches:d.slice(e)});for(k=0;k<j.length&&!c.isPropagationStopped();k++){p=j[k],c.currentTarget=p.elem;for(l=0;l<p.matches.length&&!c.isImmediatePropagationStopped();l++){r=p.matches[l];if(h||!c.namespace&&!r.namespace||c.namespace_re&&c.namespace_re.test(r.namespace))c.data=r.data,c.handleObj=r,n=(i||r.handler).apply(p.elem,g),n!==b&&(c.result=n,n===!1&&(c.preventDefault(),c.stopPropagation()))}}return 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){a.which==null&&(a.which=b.charCode!=null?b.charCode:b.keyCode);return a}},mouseHooks:{props:"button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement wheelDelta".split(" "),filter:function(a,d){var e,f,g,h=d.button,i=d.fromElement;a.pageX==null&&d.clientX!=null&&(e=a.target.ownerDocument||c,f=e.documentElement,g=e.body,a.pageX=d.clientX+(f&&f.scrollLeft||g&&g.scrollLeft||0)-(f&&f.clientLeft||g&&g.clientLeft||0),a.pageY=d.clientY+(f&&f.scrollTop||g&&g.scrollTop||0)-(f&&f.clientTop||g&&g.clientTop||0)),!a.relatedTarget&&i&&(a.relatedTarget=i===a.target?d.toElement:i),!a.which&&h!==b&&(a.which=h&1?1:h&2?3:h&4?2:0);return a}},fix:function(a){if(a[f.expando])return a;var d,e,g=a,h=f.event.fixHooks[a.type]||{},i=h.props?this.props.concat(h.props):this.props;a=f.Event(g);for(d=i.length;d;)e=i[--d],a[e]=g[e];a.target||(a.target=g.srcElement||c),a.target.nodeType===3&&(a.target=a.target.parentNode),a.metaKey===b&&(a.metaKey=a.ctrlKey);return h.filter?h.filter(a,g):a},special:{ready:{setup:f.bindReady},focus:{delegateType:"focusin",noBubble:!0},blur:{delegateType:"focusout",noBubble:!0},beforeunload:{setup:function(a,b,c){f.isWindow(this)&&(this.onbeforeunload=c)},teardown:function(a,b){this.onbeforeunload===b&&(this.onbeforeunload=null)}}},simulate:function(a,b,c,d){var e=f.extend(new f.Event,c,{type:a,isSimulated:!0,originalEvent:{}});d?f.event.trigger(e,null,b):f.event.dispatch.call(b,e),e.isDefaultPrevented()&&c.preventDefault()}},f.event.handle=f.event.dispatch,f.removeEvent=c.removeEventListener?function(a,b,c){a.removeEventListener&&a.removeEventListener(b,c,!1)}:function(a,b,c){a.detachEvent&&a.detachEvent("on"+b,c)},f.Event=function(a,b){if(!(this instanceof f.Event))return new f.Event(a,b);a&&a.type?(this.originalEvent=a,this.type=a.type,this.isDefaultPrevented=a.defaultPrevented||a.returnValue===!1||a.getPreventDefault&&a.getPreventDefault()?N:M):this.type=a,b&&f.extend(this,b),this.timeStamp=a&&a.timeStamp||f.now(),this[f.expando]=!0},f.Event.prototype={preventDefault:function(){this.isDefaultPrevented=N;var a=this.originalEvent;!a||(a.preventDefault?a.preventDefault():a.returnValue=!1)},stopPropagation:function(){this.isPropagationStopped=N;var a=this.originalEvent;!a||(a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)},stopImmediatePropagation:function(){this.isImmediatePropagationStopped=N,this.stopPropagation()},isDefaultPrevented:M,isPropagationStopped:M,isImmediatePropagationStopped:M},f.each({mouseenter:"mouseover",mouseleave:"mouseout"},function(a,b){f.event.special[a]=f.event.special[b]={delegateType:b,bindType:b,handle:function(a){var b=this,c=a.relatedTarget,d=a.handleObj,e=d.selector,g,h;if(!c||d.origType===a.type||c!==b&&!f.contains(b,c))g=a.type,a.type=d.origType,h=d.handler.apply(this,arguments),a.type=g;return h}}}),f.support.submitBubbles||(f.event.special.submit={setup:function(){if(f.nodeName(this,"form"))return!1;f.event.add(this,"click._submit keypress._submit",function(a){var c=a.target,d=f.nodeName(c,"input")||f.nodeName(c,"button")?c.form:b;d&&!d._submit_attached&&(f.event.add(d,"submit._submit",function(a){this.parentNode&&f.event.simulate("submit",this.parentNode,a,!0)}),d._submit_attached=!0)})},teardown:function(){if(f.nodeName(this,"form"))return!1;f.event.remove(this,"._submit")}}),f.support.changeBubbles||(f.event.special.change={setup:function(){if(A.test(this.nodeName)){if(this.type==="checkbox"||this.type==="radio")f.event.add(this,"propertychange._change",function(a){a.originalEvent.propertyName==="checked"&&(this._just_changed=!0)}),f.event.add(this,"click._change",function(a){this._just_changed&&(this._just_changed=!1,f.event.simulate("change",this,a,!0))});return!1}f.event.add(this,"beforeactivate._change",function(a){var b=a.target;A.test(b.nodeName)&&!b._change_attached&&(f.event.add(b,"change._change",function(a){this.parentNode&&!a.isSimulated&&f.event.simulate("change",this.parentNode,a,!0)}),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(){f.event.remove(this,"._change");return A.test(this.nodeName)}}),f.support.focusinBubbles||f.each({focus:"focusin",blur:"focusout"},function(a,b){var d=0,e=function(a){f.event.simulate(b,a.target,f.event.fix(a),!0)};f.event.special[b]={setup:function(){d++===0&&c.addEventListener(a,e,!0)},teardown:function(){--d===0&&c.removeEventListener(a,e,!0)}}}),f.fn.extend({on:function(a,c,d,e,g){var h,i;if(typeof a=="object"){typeof c!="string"&&(d=c,c=b);for(i in a)this.on(i,c,d,a[i],g);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=M;else if(!e)return this;g===1&&(h=e,e=function(a){f().off(a);return h.apply(this,arguments)},e.guid=h.guid||(h.guid=f.guid++));return this.each(function(){f.event.add(this,a,e,d,c)})},one:function(a,b,c,d){return this.on.call(this,a,b,c,d,1)},off:function(a,c,d){if(a&&a.preventDefault&&a.handleObj){var e=a.handleObj;f(a.delegateTarget).off(e.namespace?e.type+"."+e.namespace:e.type,e.selector,e.handler);return this}if(typeof a=="object"){for(var g in a)this.off(g,c,a[g]);return this}if(c===!1||typeof c=="function")d=c,c=b;d===!1&&(d=M);return this.each(function(){f.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){f(this.context).on(a,this.selector,b,c);return this},die:function(a,b){f(this.context).off(a,this.selector||"**",b);return 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(){f.event.trigger(a,b,this)})},triggerHandler:function(a,b){if(this[0])return f.event.trigger(a,b,this[0],!0)},toggle:function(a){var b=arguments,c=a.guid||f.guid++,d=0,e=function(c){var e=(f._data(this,"lastToggle"+a.guid)||0)%d;f._data(this,"lastToggle"+a.guid,e+1),c.preventDefault();return 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)}}),f.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){f.fn[b]=function(a,c){c==null&&(c=a,a=null);return arguments.length>0?this.bind(b,a,c):this.trigger(b)},f.attrFn&&(f.attrFn[b]=!0),G.test(b)&&(f.event.fixHooks[b]=f.event.keyHooks),H.test(b)&&(f.event.fixHooks[b]=f.event.mouseHooks)}),function(){function x(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}if(j.nodeType===1){g||(j[d]=c,j.sizset=h);if(typeof b!="string"){if(j===b){k=!0;break}}else if(m.filter(b,[j]).length>0){k=j;break}}j=j[a]}e[h]=k}}}function w(a,b,c,e,f,g){for(var h=0,i=e.length;h<i;h++){var j=e[h];if(j){var k=!1;j=j[a];while(j){if(j[d]===c){k=e[j.sizset];break}j.nodeType===1&&!g&&(j[d]=c,j.sizset=h);if(j.nodeName.toLowerCase()===b){k=j;break}j=j[a]}e[h]=k}}}var a=/((?:\((?:\([^()]+\)|[^()]+)+\)|\[(?:\[[^\[\]]*\]|['"][^'"]*['"]|[^\[\]'"]+)+\]|\\.|[^ >+~,(\[\\]+)+|[>+~])(\s*,\s*)?((?:.|\r|\n)*)/g,d="sizcache"+(Math.random()+"").replace(".",""),e=0,g=Object.prototype.toString,h=!1,i=!0,j=/\\/g,k=/\r\n/g,l=/\W/;[0,0].sort(function(){i=!1;return 0});var m=function(b,d,e,f){e=e||[],d=d||c;var h=d;if(d.nodeType!==1&&d.nodeType!==9)return[];if(!b||typeof b!="string")return e;var i,j,k,l,n,q,r,t,u=!0,v=m.isXML(d),w=[],x=b;do{a.exec(""),i=a.exec(x);if(i){x=i[3],w.push(i[1]);if(i[2]){l=i[3];break}}}while(i);if(w.length>1&&p.exec(b))if(w.length===2&&o.relative[w[0]])j=y(w[0]+w[1],d,f);else{j=o.relative[w[0]]?[d]:m(w.shift(),d);while(w.length)b=w.shift(),o.relative[b]&&(b+=w.shift()),j=y(b,j,f)}else{!f&&w.length>1&&d.nodeType===9&&!v&&o.match.ID.test(w[0])&&!o.match.ID.test(w[w.length-1])&&(n=m.find(w.shift(),d,v),d=n.expr?m.filter(n.expr,n.set)[0]:n.set[0]);if(d){n=f?{expr:w.pop(),set:s(f)}:m.find(w.pop(),w.length===1&&(w[0]==="~"||w[0]==="+")&&d.parentNode?d.parentNode:d,v),j=n.expr?m.filter(n.expr,n.set):n.set,w.length>0?k=s(j):u=!1;while(w.length)q=w.pop(),r=q,o.relative[q]?r=w.pop():q="",r==null&&(r=d),o.relative[q](k,r,v)}else k=w=[]}k||(k=j),k||m.error(q||b);if(g.call(k)==="[object Array]")if(!u)e.push.apply(e,k);else if(d&&d.nodeType===1)for(t=0;k[t]!=null;t++)k[t]&&(k[t]===!0||k[t].nodeType===1&&m.contains(d,k[t]))&&e.push(j[t]);else for(t=0;k[t]!=null;t++)k[t]&&k[t].nodeType===1&&e.push(j[t]);else s(k,e);l&&(m(l,h,e,f),m.uniqueSort(e));return e};m.uniqueSort=function(a){if(u){h=i,a.sort(u);if(h)for(var b=1;b<a.length;b++)a[b]===a[b-1]&&a.splice(b--,1)}return a},m.matches=function(a,b){return m(a,null,null,b)},m.matchesSelector=function(a,b){return m(b,null,null,[a]).length>0},m.find=function(a,b,c){var d,e,f,g,h,i;if(!a)return[];for(e=0,f=o.order.length;e<f;e++){h=o.order[e];if(g=o.leftMatch[h].exec(a)){i=g[1],g.splice(1,1);if(i.substr(i.length-1)!=="\\"){g[1]=(g[1]||"").replace(j,""),d=o.find[h](g,b,c);if(d!=null){a=a.replace(o.match[h],"");break}}}}d||(d=typeof b.getElementsByTagName!="undefined"?b.getElementsByTagName("*"):[]);return{set:d,expr:a}},m.filter=function(a,c,d,e){var f,g,h,i,j,k,l,n,p,q=a,r=[],s=c,t=c&&c[0]&&m.isXML(c[0]);while(a&&c.length){for(h in o.filter)if((f=o.leftMatch[h].exec(a))!=null&&f[2]){k=o.filter[h],l=f[1],g=!1,f.splice(1,1);if(l.substr(l.length-1)==="\\")continue;s===r&&(r=[]);if(o.preFilter[h]){f=o.preFilter[h](f,s,d,r,e,t);if(!f)g=i=!0;else if(f===!0)continue}if(f)for(n=0;(j=s[n])!=null;n++)j&&(i=k(j,f,n,s),p=e^i,d&&i!=null?p?g=!0:s[n]=!1:p&&(r.push(j),g=!0));if(i!==b){d||(s=r),a=a.replace(o.match[h],"");if(!g)return[];break}}if(a===q)if(g==null)m.error(a);else break;q=a}return s},m.error=function(a){throw"Syntax error, unrecognized expression: "+a};var n=m.getText=function(a){var b,c,d=a.nodeType,e="";if(d){if(d===1){if(typeof a.textContent=="string")return a.textContent;if(typeof a.innerText=="string")return a.innerText.replace(k,"");for(a=a.firstChild;a;a=a.nextSibling)e+=n(a)}else if(d===3||d===4)return a.nodeValue}else for(b=0;c=a[b];b++)c.nodeType!==8&&(e+=n(c));return e},o=m.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(a){return a.getAttribute("href")},type:function(a){return a.getAttribute("type")}},relative:{"+":function(a,b){var c=typeof b=="string",d=c&&!l.test(b),e=c&&!d;d&&(b=b.toLowerCase());for(var f=0,g=a.length,h;f<g;f++)if(h=a[f]){while((h=h.previousSibling)&&h.nodeType!==1);a[f]=e||h&&h.nodeName.toLowerCase()===b?h||!1:h===b}e&&m.filter(b,a,!0)},">":function(a,b){var c,d=typeof b=="string",e=0,f=a.length;if(d&&!l.test(b)){b=b.toLowerCase();for(;e<f;e++){c=a[e];if(c){var g=c.parentNode;a[e]=g.nodeName.toLowerCase()===b?g:!1}}}else{for(;e<f;e++)c=a[e],c&&(a[e]=d?c.parentNode:c.parentNode===b);d&&m.filter(b,a,!0)}},"":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("parentNode",b,f,a,d,c)},"~":function(a,b,c){var d,f=e++,g=x;typeof b=="string"&&!l.test(b)&&(b=b.toLowerCase(),d=b,g=w),g("previousSibling",b,f,a,d,c)}},find:{ID:function(a,b,c){if(typeof b.getElementById!="undefined"&&!c){var d=b.getElementById(a[1]);return d&&d.parentNode?[d]:[]}},NAME:function(a,b){if(typeof b.getElementsByName!="undefined"){var c=[],d=b.getElementsByName(a[1]);for(var e=0,f=d.length;e<f;e++)d[e].getAttribute("name")===a[1]&&c.push(d[e]);return c.length===0?null:c}},TAG:function(a,b){if(typeof b.getElementsByTagName!="undefined")return b.getElementsByTagName(a[1])}},preFilter:{CLASS:function(a,b,c,d,e,f){a=" "+a[1].replace(j,"")+" ";if(f)return a;for(var g=0,h;(h=b[g])!=null;g++)h&&(e^(h.className&&(" "+h.className+" ").replace(/[\t\n\r]/g," ").indexOf(a)>=0)?c||d.push(h):c&&(b[g]=!1));return!1},ID:function(a){return a[1].replace(j,"")},TAG:function(a,b){return a[1].replace(j,"").toLowerCase()},CHILD:function(a){if(a[1]==="nth"){a[2]||m.error(a[0]),a[2]=a[2].replace(/^\+|\s*/g,"");var b=/(-?)(\d*)(?:n([+\-]?\d*))?/.exec(a[2]==="even"&&"2n"||a[2]==="odd"&&"2n+1"||!/\D/.test(a[2])&&"0n+"+a[2]||a[2]);a[2]=b[1]+(b[2]||1)-0,a[3]=b[3]-0}else a[2]&&m.error(a[0]);a[0]=e++;return a},ATTR:function(a,b,c,d,e,f){var g=a[1]=a[1].replace(j,"");!f&&o.attrMap[g]&&(a[1]=o.attrMap[g]),a[4]=(a[4]||a[5]||"").replace(j,""),a[2]==="~="&&(a[4]=" "+a[4]+" ");return a},PSEUDO:function(b,c,d,e,f){if(b[1]==="not")if((a.exec(b[3])||"").length>1||/^\w/.test(b[3]))b[3]=m(b[3],null,null,c);else{var g=m.filter(b[3],c,d,!0^f);d||e.push.apply(e,g);return!1}else if(o.match.POS.test(b[0])||o.match.CHILD.test(b[0]))return!0;return b},POS:function(a){a.unshift(!0);return a}},filters:{enabled:function(a){return a.disabled===!1&&a.type!=="hidden"},disabled:function(a){return a.disabled===!0},checked:function(a){return a.checked===!0},selected:function(a){a.parentNode&&a.parentNode.selectedIndex;return a.selected===!0},parent:function(a){return!!a.firstChild},empty:function(a){return!a.firstChild},has:function(a,b,c){return!!m(c[3],a).length},header:function(a){return/h\d/i.test(a.nodeName)},text:function(a){var b=a.getAttribute("type"),c=a.type;return a.nodeName.toLowerCase()==="input"&&"text"===c&&(b===c||b===null)},radio:function(a){return a.nodeName.toLowerCase()==="input"&&"radio"===a.type},checkbox:function(a){return a.nodeName.toLowerCase()==="input"&&"checkbox"===a.type},file:function(a){return a.nodeName.toLowerCase()==="input"&&"file"===a.type},password:function(a){return a.nodeName.toLowerCase()==="input"&&"password"===a.type},submit:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"submit"===a.type},image:function(a){return a.nodeName.toLowerCase()==="input"&&"image"===a.type},reset:function(a){var b=a.nodeName.toLowerCase();return(b==="input"||b==="button")&&"reset"===a.type},button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&"button"===a.type||b==="button"},input:function(a){return/input|select|textarea|button/i.test(a.nodeName)},focus:function(a){return a===a.ownerDocument.activeElement}},setFilters:{first:function(a,b){return b===0},last:function(a,b,c,d){return b===d.length-1},even:function(a,b){return b%2===0},odd:function(a,b){return b%2===1},lt:function(a,b,c){return b<c[3]-0},gt:function(a,b,c){return b>c[3]-0},nth:function(a,b,c){return c[3]-0===b},eq:function(a,b,c){return c[3]-0===b}},filter:{PSEUDO:function(a,b,c,d){var e=b[1],f=o.filters[e];if(f)return f(a,c,b,d);if(e==="contains")return(a.textContent||a.innerText||n([a])||"").indexOf(b[3])>=0;if(e==="not"){var g=b[3];for(var h=0,i=g.length;h<i;h++)if(g[h]===a)return!1;return!0}m.error(e)},CHILD:function(a,b){var c,e,f,g,h,i,j,k=b[1],l=a;switch(k){case"only":case"first":while(l=l.previousSibling)if(l.nodeType===1)return!1;if(k==="first")return!0;l=a;case"last":while(l=l.nextSibling)if(l.nodeType===1)return!1;return!0;case"nth":c=b[2],e=b[3];if(c===1&&e===0)return!0;f=b[0],g=a.parentNode;if(g&&(g[d]!==f||!a.nodeIndex)){i=0;for(l=g.firstChild;l;l=l.nextSibling)l.nodeType===1&&(l.nodeIndex=++i);g[d]=f}j=a.nodeIndex-e;return c===0?j===0:j%c===0&&j/c>=0}},ID:function(a,b){return a.nodeType===1&&a.getAttribute("id")===b},TAG:function(a,b){return b==="*"&&a.nodeType===1||!!a.nodeName&&a.nodeName.toLowerCase()===b},CLASS:function(a,b){return(" "+(a.className||a.getAttribute("class"))+" ").indexOf(b)>-1},ATTR:function(a,b){var c=b[1],d=m.attr?m.attr(a,c):o.attrHandle[c]?o.attrHandle[c](a):a[c]!=null?a[c]:a.getAttribute(c),e=d+"",f=b[2],g=b[4];return d==null?f==="!=":!f&&m.attr?d!=null:f==="="?e===g:f==="*="?e.indexOf(g)>=0:f==="~="?(" "+e+" ").indexOf(g)>=0:g?f==="!="?e!==g:f==="^="?e.indexOf(g)===0:f==="$="?e.substr(e.length-g.length)===g:f==="|="?e===g||e.substr(0,g.length+1)===g+"-":!1:e&&d!==!1},POS:function(a,b,c,d){var e=b[2],f=o.setFilters[e];if(f)return f(a,c,b,d)}}},p=o.match.POS,q=function(a,b){return"\\"+(b-0+1)};for(var r in o.match)o.match[r]=new RegExp(o.match[r].source+/(?![^\[]*\])(?![^\(]*\))/.source),o.leftMatch[r]=new RegExp(/(^(?:.|\r|\n)*?)/.source+o.match[r].source.replace(/\\(\d+)/g,q));var s=function(a,b){a=Array.prototype.slice.call(a,0);if(b){b.push.apply(b,a);return b}return a};try{Array.prototype.slice.call(c.documentElement.childNodes,0)[0].nodeType}catch(t){s=function(a,b){var c=0,d=b||[];if(g.call(a)==="[object Array]")Array.prototype.push.apply(d,a);else if(typeof a.length=="number")for(var e=a.length;c<e;c++)d.push(a[c]);else for(;a[c];c++)d.push(a[c]);return d}}var u,v;c.documentElement.compareDocumentPosition?u=function(a,b){if(a===b){h=!0;return 0}if(!a.compareDocumentPosition||!b.compareDocumentPosition)return a.compareDocumentPosition?-1:1;return a.compareDocumentPosition(b)&4?-1:1}:(u=function(a,b){if(a===b){h=!0;return 0}if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],f=[],g=a.parentNode,i=b.parentNode,j=g;if(g===i)return v(a,b);if(!g)return-1;if(!i)return 1;while(j)e.unshift(j),j=j.parentNode;j=i;while(j)f.unshift(j),j=j.parentNode;c=e.length,d=f.length;for(var k=0;k<c&&k<d;k++)if(e[k]!==f[k])return v(e[k],f[k]);return k===c?v(a,f[k],-1):v(e[k],b,1)},v=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}),function(){var a=c.createElement("div"),d="script"+(new Date).getTime(),e=c.documentElement;a.innerHTML="<a name='"+d+"'/>",e.insertBefore(a,e.firstChild),c.getElementById(d)&&(o.find.ID=function(a,c,d){if(typeof c.getElementById!="undefined"&&!d){var e=c.getElementById(a[1]);return e?e.id===a[1]||typeof e.getAttributeNode!="undefined"&&e.getAttributeNode("id").nodeValue===a[1]?[e]:b:[]}},o.filter.ID=function(a,b){var c=typeof a.getAttributeNode!="undefined"&&a.getAttributeNode("id");return a.nodeType===1&&c&&c.nodeValue===b}),e.removeChild(a),e=a=null}(),function(){var a=c.createElement("div");a.appendChild(c.createComment("")),a.getElementsByTagName("*").length>0&&(o.find.TAG=function(a,b){var c=b.getElementsByTagName(a[1]);if(a[1]==="*"){var d=[];for(var e=0;c[e];e++)c[e].nodeType===1&&d.push(c[e]);c=d}return c}),a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!="undefined"&&a.firstChild.getAttribute("href")!=="#"&&(o.attrHandle.href=function(a){return a.getAttribute("href",2)}),a=null}(),c.querySelectorAll&&function(){var a=m,b=c.createElement("div"),d="__sizzle__";b.innerHTML="<p class='TEST'></p>";if(!b.querySelectorAll||b.querySelectorAll(".TEST").length!==0){m=function(b,e,f,g){e=e||c;if(!g&&!m.isXML(e)){var h=/^(\w+$)|^\.([\w\-]+$)|^#([\w\-]+$)/.exec(b);if(h&&(e.nodeType===1||e.nodeType===9)){if(h[1])return s(e.getElementsByTagName(b),f);if(h[2]&&o.find.CLASS&&e.getElementsByClassName)return s(e.getElementsByClassName(h[2]),f)}if(e.nodeType===9){if(b==="body"&&e.body)return s([e.body],f);if(h&&h[3]){var i=e.getElementById(h[3]);if(!i||!i.parentNode)return s([],f);if(i.id===h[3])return s([i],f)}try{return s(e.querySelectorAll(b),f)}catch(j){}}else if(e.nodeType===1&&e.nodeName.toLowerCase()!=="object"){var k=e,l=e.getAttribute("id"),n=l||d,p=e.parentNode,q=/^\s*[+~]/.test(b);l?n=n.replace(/'/g,"\\$&"):e.setAttribute("id",n),q&&p&&(e=e.parentNode);try{if(!q||p)return s(e.querySelectorAll("[id='"+n+"'] "+b),f)}catch(r){}finally{l||k.removeAttribute("id")}}}return a(b,e,f,g)};for(var e in a)m[e]=a[e];b=null}}(),function(){var a=c.documentElement,b=a.matchesSelector||a.mozMatchesSelector||a.webkitMatchesSelector||a.msMatchesSelector;if(b){var d=!b.call(c.createElement("div"),"div"),e=!1;try{b.call(c.documentElement,"[test!='']:sizzle")}catch(f){e=!0}m.matchesSelector=function(a,c){c=c.replace(/\=\s*([^'"\]]*)\s*\]/g,"='$1']");if(!m.isXML(a))try{if(e||!o.match.PSEUDO.test(c)&&!/!=/.test(c)){var f=b.call(a,c);if(f||!d||a.document&&a.document.nodeType!==11)return f}}catch(g){}return m(c,null,null,[a]).length>0}}}(),function(){var a=c.createElement("div");a.innerHTML="<div class='test e'></div><div class='test'></div>";if(!!a.getElementsByClassName&&a.getElementsByClassName("e").length!==0){a.lastChild.className="e";if(a.getElementsByClassName("e").length===1)return;o.order.splice(1,0,"CLASS"),o.find.CLASS=function(a,b,c){if(typeof b.getElementsByClassName!="undefined"&&!c)return b.getElementsByClassName(a[1])},a=null}}(),c.documentElement.contains?m.contains=function(a,b){return a!==b&&(a.contains?a.contains(b):!0)}:c.documentElement.compareDocumentPosition?m.contains=function(a,b){return!!(a.compareDocumentPosition(b)&16)}:m.contains=function(){return!1},m.isXML=function(a){var b=(a?a.ownerDocument||a:0).documentElement;return b?b.nodeName!=="HTML":!1};var y=function(a,b,c){var d,e=[],f="",g=b.nodeType?[b]:b;while(d=o.match.PSEUDO.exec(a))f+=d[0],a=a.replace(o.match.PSEUDO,"");a=o.relative[a]?a+"*":a;for(var h=0,i=g.length;h<i;h++)m(a,g[h],e,c);return m.filter(f,e)};m.attr=f.attr,m.selectors.attrMap={},f.find=m,f.expr=m.selectors,f.expr[":"]=f.expr.filters,f.unique=m.uniqueSort,f.text=m.getText,f.isXMLDoc=m.isXML,f.contains=m.contains}();var O=/Until$/,P=/^(?:parents|prevUntil|prevAll)/,Q=/,/,R=/^.[^:#\[\.,]*$/,S=Array.prototype.slice,T=f.expr.match.POS,U={children:!0,contents:!0,next:!0,prev:!0};f.fn.extend({find:function(a){var b=this,c,d;if(typeof a!="string")return f(a).filter(function(){for(c=0,d=b.length;c<d;c++)if(f.contains(b[c],this))return!0});var e=this.pushStack("","find",a),g,h,i;for(c=0,d=this.length;c<d;c++){g=e.length,f.find(a,this[c],e);if(c>0)for(h=g;h<e.length;h++)for(i=0;i<g;i++)if(e[i]===e[h]){e.splice(h--,1);break}}return e},has:function(a){var b=f(a);return this.filter(function(){for(var a=0,c=b.length;a<c;a++)if(f.contains(this,b[a]))return!0})},not:function(a){return this.pushStack(W(this,a,!1),"not",a)},filter:function(a){return this.pushStack(W(this,a,!0),"filter",a)},is:function(a){return!!a&&(typeof a=="string"?T.test(a)?f(a,this.context).index(this[0])>=0:f.filter(a,this).length>0:this.filter(a).length>0)},closest:function(a,b){var c=[],d,e,g=this[0];if(f.isArray(a)){var h=1;while(g&&g.ownerDocument&&g!==b){for(d=0;d<a.length;d++)f(g).is(a[d])&&c.push({selector:a[d],elem:g,level:h});g=g.parentNode,h++}return c}var i=T.test(a)||typeof a!="string"?f(a,b||this.context):0;for(d=0,e=this.length;d<e;d++){g=this[d];while(g){if(i?i.index(g)>-1:f.find.matchesSelector(g,a)){c.push(g);break}g=g.parentNode;if(!g||!g.ownerDocument||g===b||g.nodeType===11)break}}c=c.length>1?f.unique(c):c;return this.pushStack(c,"closest",a)},index:function(a){if(!a)return this[0]&&this[0].parentNode?this.prevAll().length:-1;if(typeof a=="string")return f.inArray(this[0],f(a));return f.inArray(a.jquery?a[0]:a,this)},add:function(a,b){var c=typeof a=="string"?f(a,b):f.makeArray(a&&a.nodeType?[a]:a),d=f.merge(this.get(),c);return this.pushStack(V(c[0])||V(d[0])?d:f.unique(d))},andSelf:function(){return this.add(this.prevObject)}}),f.each({parent:function(a){var b=a.parentNode;return b&&b.nodeType!==11?b:null},parents:function(a){return f.dir(a,"parentNode")},parentsUntil:function(a,b,c){return f.dir(a,"parentNode",c)},next:function(a){return f.nth(a,2,"nextSibling")},prev:function(a){return f.nth(a,2,"previousSibling")},nextAll:function(a){return f.dir(a,"nextSibling")},prevAll:function(a){return f.dir(a,"previousSibling")},nextUntil:function(a,b,c){return f.dir(a,"nextSibling",c)},prevUntil:function(a,b,c){return f.dir(a,"previousSibling",c)},siblings:function(a){return f.sibling(a.parentNode.firstChild,a)},children:function(a){return f.sibling(a.firstChild)},contents:function(a){return f.nodeName(a,"iframe")?a.contentDocument||a.contentWindow.document:f.makeArray(a.childNodes)}},function(a,b){f.fn[a]=function(c,d){var e=f.map(this,b,c),g=S.call(arguments);O.test(a)||(d=c),d&&typeof d=="string"&&(e=f.filter(d,e)),e=this.length>1&&!U[a]?f.unique(e):e,(this.length>1||Q.test(d))&&P.test(a)&&(e=e.reverse());return this.pushStack(e,a,g.join(","))}}),f.extend({filter:function(a,b,c){c&&(a=":not("+a+")");return b.length===1?f.find.matchesSelector(b[0],a)?[b[0]]:[]:f.find.matches(a,b)},dir:function(a,c,d){var e=[],g=a[c];while(g&&g.nodeType!==9&&(d===b||g.nodeType!==1||!f(g).is(d)))g.nodeType===1&&e.push(g),g=g[c];return e},nth:function(a,b,c,d){b=b||1;var e=0;for(;a;a=a[c])if(a.nodeType===1&&++e===b)break;return a},sibling:function(a,b){var c=[];for(;a;a=a.nextSibling)a.nodeType===1&&a!==b&&c.push(a);return c}});var Y="abbr article aside audio canvas datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video",Z=/ jQuery\d+="(?:\d+|null)"/g,$=/^\s+/,_=/<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/ig,ba=/<([\w:]+)/,bb=/<tbody/i,bc=/<|&#?\w+;/,bd=/<(?:script|style)/i,be=/<(?:script|object|embed|option|style)/i,bf=new RegExp("<(?:"+Y.replace(" ","|")+")","i"),bg=/checked\s*(?:[^=]|=\s*.checked.)/i,bh=/\/(java|ecma)script/i,bi=/^\s*<!(?:\[CDATA\[|\-\-)/,bj={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,"",""]},bk=X(c);bj.optgroup=bj.option,bj.tbody=bj.tfoot=bj.colgroup=bj.caption=bj.thead,bj.th=bj.td,f.support.htmlSerialize||(bj._default=[1,"div<div>","</div>"]),f.fn.extend({text:function(a){if(f.isFunction(a))return this.each(function(b){var c=f(this);c.text(a.call(this,b,c.text()))});if(typeof a!="object"&&a!==b)return this.empty().append((this[0]&&this[0].ownerDocument||c).createTextNode(a));return f.text(this)},wrapAll:function(a){if(f.isFunction(a))return this.each(function(b){f(this).wrapAll(a.call(this,b))});if(this[0]){var b=f(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){if(f.isFunction(a))return this.each(function(b){f(this).wrapInner(a.call(this,b))});return this.each(function(){var b=f(this),c=b.contents();c.length?c.wrapAll(a):b.append(a)})},wrap:function(a){return this.each(function(){f(this).wrapAll(a)})},unwrap:function(){return this.parent().each(function(){f.nodeName(this,"body")||f(this).replaceWith(this.childNodes)}).end()},append:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.appendChild(a)})},prepend:function(){return this.domManip(arguments,!0,function(a){this.nodeType===1&&this.insertBefore(a,this.firstChild)})},before:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this)});if(arguments.length){var a=f(arguments[0]);a.push.apply(a,this.toArray());return this.pushStack(a,"before",arguments)}},after:function(){if(this[0]&&this[0].parentNode)return this.domManip(arguments,!1,function(a){this.parentNode.insertBefore(a,this.nextSibling)});if(arguments.length){var a=this.pushStack(this,"after"
,arguments);a.push.apply(a,f(arguments[0]).toArray());return a}},remove:function(a,b){for(var c=0,d;(d=this[c])!=null;c++)if(!a||f.filter(a,[d]).length)!b&&d.nodeType===1&&(f.cleanData(d.getElementsByTagName("*")),f.cleanData([d])),d.parentNode&&d.parentNode.removeChild(d);return this},empty:function(){for(var a=0,b;(b=this[a])!=null;a++){b.nodeType===1&&f.cleanData(b.getElementsByTagName("*"));while(b.firstChild)b.removeChild(b.firstChild)}return this},clone:function(a,b){a=a==null?!1:a,b=b==null?a:b;return this.map(function(){return f.clone(this,a,b)})},html:function(a){if(a===b)return this[0]&&this[0].nodeType===1?this[0].innerHTML.replace(Z,""):null;if(typeof a=="string"&&!bd.test(a)&&(f.support.leadingWhitespace||!$.test(a))&&!bj[(ba.exec(a)||["",""])[1].toLowerCase()]){a=a.replace(_,"<$1></$2>");try{for(var c=0,d=this.length;c<d;c++)this[c].nodeType===1&&(f.cleanData(this[c].getElementsByTagName("*")),this[c].innerHTML=a)}catch(e){this.empty().append(a)}}else f.isFunction(a)?this.each(function(b){var c=f(this);c.html(a.call(this,b,c.html()))}):this.empty().append(a);return this},replaceWith:function(a){if(this[0]&&this[0].parentNode){if(f.isFunction(a))return this.each(function(b){var c=f(this),d=c.html();c.replaceWith(a.call(this,b,d))});typeof a!="string"&&(a=f(a).detach());return this.each(function(){var b=this.nextSibling,c=this.parentNode;f(this).remove(),b?f(b).before(a):f(c).append(a)})}return this.length?this.pushStack(f(f.isFunction(a)?a():a),"replaceWith",a):this},detach:function(a){return this.remove(a,!0)},domManip:function(a,c,d){var e,g,h,i,j=a[0],k=[];if(!f.support.checkClone&&arguments.length===3&&typeof j=="string"&&bg.test(j))return this.each(function(){f(this).domManip(a,c,d,!0)});if(f.isFunction(j))return this.each(function(e){var g=f(this);a[0]=j.call(this,e,c?g.html():b),g.domManip(a,c,d)});if(this[0]){i=j&&j.parentNode,f.support.parentNode&&i&&i.nodeType===11&&i.childNodes.length===this.length?e={fragment:i}:e=f.buildFragment(a,this,k),h=e.fragment,h.childNodes.length===1?g=h=h.firstChild:g=h.firstChild;if(g){c=c&&f.nodeName(g,"tr");for(var l=0,m=this.length,n=m-1;l<m;l++)d.call(c?bl(this[l],g):this[l],e.cacheable||m>1&&l<n?f.clone(h,!0,!0):h)}k.length&&f.each(k,br)}return this}}),f.buildFragment=function(a,b,d){var e,g,h,i,j=a[0];b&&b[0]&&(i=b[0].ownerDocument||b[0]),i.createDocumentFragment||(i=c),a.length===1&&typeof j=="string"&&j.length<512&&i===c&&j.charAt(0)==="<"&&!be.test(j)&&(f.support.checkClone||!bg.test(j))&&!f.support.unknownElems&&bf.test(j)&&(g=!0,h=f.fragments[j],h&&h!==1&&(e=h)),e||(e=i.createDocumentFragment(),f.clean(a,i,e,d)),g&&(f.fragments[j]=h?e:1);return{fragment:e,cacheable:g}},f.fragments={},f.each({appendTo:"append",prependTo:"prepend",insertBefore:"before",insertAfter:"after",replaceAll:"replaceWith"},function(a,b){f.fn[a]=function(c){var d=[],e=f(c),g=this.length===1&&this[0].parentNode;if(g&&g.nodeType===11&&g.childNodes.length===1&&e.length===1){e[b](this[0]);return this}for(var h=0,i=e.length;h<i;h++){var j=(h>0?this.clone(!0):this).get();f(e[h])[b](j),d=d.concat(j)}return this.pushStack(d,a,e.selector)}}),f.extend({clone:function(a,b,c){var d=a.cloneNode(!0),e,g,h;if((!f.support.noCloneEvent||!f.support.noCloneChecked)&&(a.nodeType===1||a.nodeType===11)&&!f.isXMLDoc(a)){bn(a,d),e=bo(a),g=bo(d);for(h=0;e[h];++h)g[h]&&bn(e[h],g[h])}if(b){bm(a,d);if(c){e=bo(a),g=bo(d);for(h=0;e[h];++h)bm(e[h],g[h])}}e=g=null;return d},clean:function(a,b,d,e){var g;b=b||c,typeof b.createElement=="undefined"&&(b=b.ownerDocument||b[0]&&b[0].ownerDocument||c);var h=[],i;for(var j=0,k;(k=a[j])!=null;j++){typeof k=="number"&&(k+="");if(!k)continue;if(typeof k=="string")if(!bc.test(k))k=b.createTextNode(k);else{k=k.replace(_,"<$1></$2>");var l=(ba.exec(k)||["",""])[1].toLowerCase(),m=bj[l]||bj._default,n=m[0],o=b.createElement("div");b===c?bk.appendChild(o):X(b).appendChild(o),o.innerHTML=m[1]+k+m[2];while(n--)o=o.lastChild;if(!f.support.tbody){var p=bb.test(k),q=l==="table"&&!p?o.firstChild&&o.firstChild.childNodes:m[1]==="<table>"&&!p?o.childNodes:[];for(i=q.length-1;i>=0;--i)f.nodeName(q[i],"tbody")&&!q[i].childNodes.length&&q[i].parentNode.removeChild(q[i])}!f.support.leadingWhitespace&&$.test(k)&&o.insertBefore(b.createTextNode($.exec(k)[0]),o.firstChild),k=o.childNodes}var r;if(!f.support.appendChecked)if(k[0]&&typeof (r=k.length)=="number")for(i=0;i<r;i++)bq(k[i]);else bq(k);k.nodeType?h.push(k):h=f.merge(h,k)}if(d){g=function(a){return!a.type||bh.test(a.type)};for(j=0;h[j];j++)if(e&&f.nodeName(h[j],"script")&&(!h[j].type||h[j].type.toLowerCase()==="text/javascript"))e.push(h[j].parentNode?h[j].parentNode.removeChild(h[j]):h[j]);else{if(h[j].nodeType===1){var s=f.grep(h[j].getElementsByTagName("script"),g);h.splice.apply(h,[j+1,0].concat(s))}d.appendChild(h[j])}}return h},cleanData:function(a){var b,c,d=f.cache,e=f.event.special,g=f.support.deleteExpando;for(var h=0,i;(i=a[h])!=null;h++){if(i.nodeName&&f.noData[i.nodeName.toLowerCase()])continue;c=i[f.expando];if(c){b=d[c];if(b&&b.events){for(var j in b.events)e[j]?f.event.remove(i,j):f.removeEvent(i,j,b.handle);b.handle&&(b.handle.elem=null)}g?delete i[f.expando]:i.removeAttribute&&i.removeAttribute(f.expando),delete d[c]}}}});var bs=/alpha\([^)]*\)/i,bt=/opacity=([^)]*)/,bu=/([A-Z]|^ms)/g,bv=/^-?\d+(?:px)?$/i,bw=/^-?\d/,bx=/^([\-+])=([\-+.\de]+)/,by={position:"absolute",visibility:"hidden",display:"block"},bz=["Left","Right"],bA=["Top","Bottom"],bB,bC,bD;f.fn.css=function(a,c){if(arguments.length===2&&c===b)return this;return f.access(this,a,c,!0,function(a,c,d){return d!==b?f.style(a,c,d):f.css(a,c)})},f.extend({cssHooks:{opacity:{get:function(a,b){if(b){var c=bB(a,"opacity","opacity");return c===""?"1":c}return a.style.opacity}}},cssNumber:{fillOpacity:!0,fontWeight:!0,lineHeight:!0,opacity:!0,orphans:!0,widows:!0,zIndex:!0,zoom:!0},cssProps:{"float":f.support.cssFloat?"cssFloat":"styleFloat"},style:function(a,c,d,e){if(!!a&&a.nodeType!==3&&a.nodeType!==8&&!!a.style){var g,h,i=f.camelCase(c),j=a.style,k=f.cssHooks[i];c=f.cssProps[i]||i;if(d===b){if(k&&"get"in k&&(g=k.get(a,!1,e))!==b)return g;return j[c]}h=typeof d,h==="string"&&(g=bx.exec(d))&&(d=+(g[1]+1)*+g[2]+parseFloat(f.css(a,c)),h="number");if(d==null||h==="number"&&isNaN(d))return;h==="number"&&!f.cssNumber[i]&&(d+="px");if(!k||!("set"in k)||(d=k.set(a,d))!==b)try{j[c]=d}catch(l){}}},css:function(a,c,d){var e,g;c=f.camelCase(c),g=f.cssHooks[c],c=f.cssProps[c]||c,c==="cssFloat"&&(c="float");if(g&&"get"in g&&(e=g.get(a,!0,d))!==b)return e;if(bB)return bB(a,c)},swap:function(a,b,c){var d={};for(var e in b)d[e]=a.style[e],a.style[e]=b[e];c.call(a);for(e in b)a.style[e]=d[e]}}),f.curCSS=f.css,f.each(["height","width"],function(a,b){f.cssHooks[b]={get:function(a,c,d){var e;if(c){if(a.offsetWidth!==0)return bE(a,b,d);f.swap(a,by,function(){e=bE(a,b,d)});return e}},set:function(a,b){if(!bv.test(b))return b;b=parseFloat(b);if(b>=0)return b+"px"}}}),f.support.opacity||(f.cssHooks.opacity={get:function(a,b){return bt.test((b&&a.currentStyle?a.currentStyle.filter:a.style.filter)||"")?parseFloat(RegExp.$1)/100+"":b?"1":""},set:function(a,b){var c=a.style,d=a.currentStyle,e=f.isNumeric(b)?"alpha(opacity="+b*100+")":"",g=d&&d.filter||c.filter||"";c.zoom=1;if(b>=1&&f.trim(g.replace(bs,""))===""){c.removeAttribute("filter");if(d&&!d.filter)return}c.filter=bs.test(g)?g.replace(bs,e):g+" "+e}}),f(function(){f.support.reliableMarginRight||(f.cssHooks.marginRight={get:function(a,b){var c;f.swap(a,{display:"inline-block"},function(){b?c=bB(a,"margin-right","marginRight"):c=a.style.marginRight});return c}})}),c.defaultView&&c.defaultView.getComputedStyle&&(bC=function(a,c){var d,e,g;c=c.replace(bu,"-$1").toLowerCase();if(!(e=a.ownerDocument.defaultView))return b;if(g=e.getComputedStyle(a,null))d=g.getPropertyValue(c),d===""&&!f.contains(a.ownerDocument.documentElement,a)&&(d=f.style(a,c));return d}),c.documentElement.currentStyle&&(bD=function(a,b){var c,d,e,f=a.currentStyle&&a.currentStyle[b],g=a.style;f===null&&g&&(e=g[b])&&(f=e),!bv.test(f)&&bw.test(f)&&(c=g.left,d=a.runtimeStyle&&a.runtimeStyle.left,d&&(a.runtimeStyle.left=a.currentStyle.left),g.left=b==="fontSize"?"1em":f||0,f=g.pixelLeft+"px",g.left=c,d&&(a.runtimeStyle.left=d));return f===""?"auto":f}),bB=bC||bD,f.expr&&f.expr.filters&&(f.expr.filters.hidden=function(a){var b=a.offsetWidth,c=a.offsetHeight;return b===0&&c===0||!f.support.reliableHiddenOffsets&&(a.style&&a.style.display||f.css(a,"display"))==="none"},f.expr.filters.visible=function(a){return!f.expr.filters.hidden(a)});var bF=/%20/g,bG=/\[\]$/,bH=/\r?\n/g,bI=/#.*$/,bJ=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,bK=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,bL=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,bM=/^(?:GET|HEAD)$/,bN=/^\/\//,bO=/\?/,bP=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,bQ=/^(?:select|textarea)/i,bR=/\s+/,bS=/([?&])_=[^&]*/,bT=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+))?)?/,bU=f.fn.load,bV={},bW={},bX,bY,bZ=["*/"]+["*"];try{bX=e.href}catch(b$){bX=c.createElement("a"),bX.href="",bX=bX.href}bY=bT.exec(bX.toLowerCase())||[],f.fn.extend({load:function(a,c,d){if(typeof a!="string"&&bU)return bU.apply(this,arguments);if(!this.length)return this;var e=a.indexOf(" ");if(e>=0){var g=a.slice(e,a.length);a=a.slice(0,e)}var h="GET";c&&(f.isFunction(c)?(d=c,c=b):typeof c=="object"&&(c=f.param(c,f.ajaxSettings.traditional),h="POST"));var i=this;f.ajax({url:a,type:h,dataType:"html",data:c,complete:function(a,b,c){c=a.responseText,a.isResolved()&&(a.done(function(a){c=a}),i.html(g?f("<div>").append(c.replace(bP,"")).find(g):c)),d&&i.each(d,[c,b,a])}});return this},serialize:function(){return f.param(this.serializeArray())},serializeArray:function(){return this.map(function(){return this.elements?f.makeArray(this.elements):this}).filter(function(){return this.name&&!this.disabled&&(this.checked||bQ.test(this.nodeName)||bK.test(this.type))}).map(function(a,b){var c=f(this).val();return c==null?null:f.isArray(c)?f.map(c,function(a,c){return{name:b.name,value:a.replace(bH,"\r\n")}}):{name:b.name,value:c.replace(bH,"\r\n")}}).get()}}),f.each("ajaxStart ajaxStop ajaxComplete ajaxError ajaxSuccess ajaxSend".split(" "),function(a,b){f.fn[b]=function(a){return this.bind(b,a)}}),f.each(["get","post"],function(a,c){f[c]=function(a,d,e,g){f.isFunction(d)&&(g=g||e,e=d,d=b);return f.ajax({type:c,url:a,data:d,success:e,dataType:g})}}),f.extend({getScript:function(a,c){return f.get(a,b,c,"script")},getJSON:function(a,b,c){return f.get(a,b,c,"json")},ajaxSetup:function(a,b){b?cb(a,f.ajaxSettings):(b=a,a=f.ajaxSettings),cb(a,b);return a},ajaxSettings:{url:bX,isLocal:bL.test(bY[1]),global:!0,type:"GET",contentType:"application/x-www-form-urlencoded",processData:!0,async:!0,accepts:{xml:"application/xml, text/xml",html:"text/html",text:"text/plain",json:"application/json, text/javascript","*":bZ},contents:{xml:/xml/,html:/html/,json:/json/},responseFields:{xml:"responseXML",text:"responseText"},converters:{"* text":a.String,"text html":!0,"text json":f.parseJSON,"text xml":f.parseXML},flatOptions:{context:!0,url:!0}},ajaxPrefilter:b_(bV),ajaxTransport:b_(bW),ajax:function(a,c){function w(a,c,l,m){if(s!==2){s=2,q&&clearTimeout(q),p=b,n=m||"",v.readyState=a>0?4:0;var o,r,u,w=c,x=l?cd(d,v,l):b,y,z;if(a>=200&&a<300||a===304){if(d.ifModified){if(y=v.getResponseHeader("Last-Modified"))f.lastModified[k]=y;if(z=v.getResponseHeader("Etag"))f.etag[k]=z}if(a===304)w="notmodified",o=!0;else try{r=ce(d,x),w="success",o=!0}catch(A){w="parsererror",u=A}}else{u=w;if(!w||a)w="error",a<0&&(a=0)}v.status=a,v.statusText=""+(c||w),o?h.resolveWith(e,[r,w,v]):h.rejectWith(e,[v,w,u]),v.statusCode(j),j=b,t&&g.trigger("ajax"+(o?"Success":"Error"),[v,d,o?r:u]),i.fireWith(e,[v,w]),t&&(g.trigger("ajaxComplete",[v,d]),--f.active||f.event.trigger("ajaxStop"))}}typeof a=="object"&&(c=a,a=b),c=c||{};var d=f.ajaxSetup({},c),e=d.context||d,g=e!==d&&(e.nodeType||e instanceof f)?f(e):f.event,h=f.Deferred(),i=f.Callbacks("once memory"),j=d.statusCode||{},k,l={},m={},n,o,p,q,r,s=0,t,u,v={readyState:0,setRequestHeader:function(a,b){if(!s){var c=a.toLowerCase();a=m[c]=m[c]||a,l[a]=b}return this},getAllResponseHeaders:function(){return s===2?n:null},getResponseHeader:function(a){var c;if(s===2){if(!o){o={};while(c=bJ.exec(n))o[c[1].toLowerCase()]=c[2]}c=o[a.toLowerCase()]}return c===b?null:c},overrideMimeType:function(a){s||(d.mimeType=a);return this},abort:function(a){a=a||"abort",p&&p.abort(a),w(0,a);return this}};h.promise(v),v.success=v.done,v.error=v.fail,v.complete=i.add,v.statusCode=function(a){if(a){var b;if(s<2)for(b in a)j[b]=[j[b],a[b]];else b=a[v.status],v.then(b,b)}return this},d.url=((a||d.url)+"").replace(bI,"").replace(bN,bY[1]+"//"),d.dataTypes=f.trim(d.dataType||"*").toLowerCase().split(bR),d.crossDomain==null&&(r=bT.exec(d.url.toLowerCase()),d.crossDomain=!(!r||r[1]==bY[1]&&r[2]==bY[2]&&(r[3]||(r[1]==="http:"?80:443))==(bY[3]||(bY[1]==="http:"?80:443)))),d.data&&d.processData&&typeof d.data!="string"&&(d.data=f.param(d.data,d.traditional)),ca(bV,d,c,v);if(s===2)return!1;t=d.global,d.type=d.type.toUpperCase(),d.hasContent=!bM.test(d.type),t&&f.active++===0&&f.event.trigger("ajaxStart");if(!d.hasContent){d.data&&(d.url+=(bO.test(d.url)?"&":"?")+d.data,delete d.data),k=d.url;if(d.cache===!1){var x=f.now(),y=d.url.replace(bS,"$1_="+x);d.url=y+(y===d.url?(bO.test(d.url)?"&":"?")+"_="+x:"")}}(d.data&&d.hasContent&&d.contentType!==!1||c.contentType)&&v.setRequestHeader("Content-Type",d.contentType),d.ifModified&&(k=k||d.url,f.lastModified[k]&&v.setRequestHeader("If-Modified-Since",f.lastModified[k]),f.etag[k]&&v.setRequestHeader("If-None-Match",f.etag[k])),v.setRequestHeader("Accept",d.dataTypes[0]&&d.accepts[d.dataTypes[0]]?d.accepts[d.dataTypes[0]]+(d.dataTypes[0]!=="*"?", "+bZ+"; q=0.01":""):d.accepts["*"]);for(u in d.headers)v.setRequestHeader(u,d.headers[u]);if(d.beforeSend&&(d.beforeSend.call(e,v,d)===!1||s===2)){v.abort();return!1}for(u in{success:1,error:1,complete:1})v[u](d[u]);p=ca(bW,d,c,v);if(!p)w(-1,"No Transport");else{v.readyState=1,t&&g.trigger("ajaxSend",[v,d]),d.async&&d.timeout>0&&(q=setTimeout(function(){v.abort("timeout")},d.timeout));try{s=1,p.send(l,w)}catch(z){s<2?w(-1,z):f.error(z)}}return v},param:function(a,c){var d=[],e=function(a,b){b=f.isFunction(b)?b():b,d[d.length]=encodeURIComponent(a)+"="+encodeURIComponent(b)};c===b&&(c=f.ajaxSettings.traditional);if(f.isArray(a)||a.jquery&&!f.isPlainObject(a))f.each(a,function(){e(this.name,this.value)});else for(var g in a)cc(g,a[g],c,e);return d.join("&").replace(bF,"+")}}),f.extend({active:0,lastModified:{},etag:{}});var cf=f.now(),cg=/(\=)\?(&|$)|\?\?/i;f.ajaxSetup({jsonp:"callback",jsonpCallback:function(){return f.expando+"_"+cf++}}),f.ajaxPrefilter("json jsonp",function(b,c,d){var e=b.contentType==="application/x-www-form-urlencoded"&&typeof b.data=="string";if(b.dataTypes[0]==="jsonp"||b.jsonp!==!1&&(cg.test(b.url)||e&&cg.test(b.data))){var g,h=b.jsonpCallback=f.isFunction(b.jsonpCallback)?b.jsonpCallback():b.jsonpCallback,i=a[h],j=b.url,k=b.data,l="$1"+h+"$2";b.jsonp!==!1&&(j=j.replace(cg,l),b.url===j&&(e&&(k=k.replace(cg,l)),b.data===k&&(j+=(/\?/.test(j)?"&":"?")+b.jsonp+"="+h))),b.url=j,b.data=k,a[h]=function(a){g=[a]},d.always(function(){a[h]=i,g&&f.isFunction(i)&&a[h](g[0])}),b.converters["script json"]=function(){g||f.error(h+" was not called");return g[0]},b.dataTypes[0]="json";return"script"}}),f.ajaxSetup({accepts:{script:"text/javascript, application/javascript, application/ecmascript, application/x-ecmascript"},contents:{script:/javascript|ecmascript/},converters:{"text script":function(a){f.globalEval(a);return a}}}),f.ajaxPrefilter("script",function(a){a.cache===b&&(a.cache=!1),a.crossDomain&&(a.type="GET",a.global=!1)}),f.ajaxTransport("script",function(a){if(a.crossDomain){var d,e=c.head||c.getElementsByTagName("head")[0]||c.documentElement;return{send:function(f,g){d=c.createElement("script"),d.async="async",a.scriptCharset&&(d.charset=a.scriptCharset),d.src=a.url,d.onload=d.onreadystatechange=function(a,c){if(c||!d.readyState||/loaded|complete/.test(d.readyState))d.onload=d.onreadystatechange=null,e&&d.parentNode&&e.removeChild(d),d=b,c||g(200,"success")},e.insertBefore(d,e.firstChild)},abort:function(){d&&d.onload(0,1)}}}});var ch=a.ActiveXObject?function(){for(var a in cj)cj[a](0,1)}:!1,ci=0,cj;f.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&ck()||cl()}:ck,function(a){f.extend(f.support,{ajax:!!a,cors:!!a&&"withCredentials"in a})}(f.ajaxSettings.xhr()),f.support.ajax&&f.ajaxTransport(function(c){if(!c.crossDomain||f.support.cors){var d;return{send:function(e,g){var h=c.xhr(),i,j;c.username?h.open(c.type,c.url,c.async,c.username,c.password):h.open(c.type,c.url,c.async);if(c.xhrFields)for(j in c.xhrFields)h[j]=c.xhrFields[j];c.mimeType&&h.overrideMimeType&&h.overrideMimeType(c.mimeType),!c.crossDomain&&!e["X-Requested-With"]&&(e["X-Requested-With"]="XMLHttpRequest");try{for(j in e)h.setRequestHeader(j,e[j])}catch(k){}h.send(c.hasContent&&c.data||null),d=function(a,e){var j,k,l,m,n;try{if(d&&(e||h.readyState===4)){d=b,i&&(h.onreadystatechange=f.noop,ch&&delete cj[i]);if(e)h.readyState!==4&&h.abort();else{j=h.status,l=h.getAllResponseHeaders(),m={},n=h.responseXML,n&&n.documentElement&&(m.xml=n),m.text=h.responseText;try{k=h.statusText}catch(o){k=""}!j&&c.isLocal&&!c.crossDomain?j=m.text?200:404:j===1223&&(j=204)}}}catch(p){e||g(-1,p)}m&&g(j,k,m,l)},!c.async||h.readyState===4?d():(i=++ci,ch&&(cj||(cj={},f(a).unload(ch)),cj[i]=d),h.onreadystatechange=d)},abort:function(){d&&d(0,1)}}}});var cm={},cn,co,cp=/^(?:toggle|show|hide)$/,cq=/^([+\-]=)?([\d+.\-]+)([a-z%]*)$/i,cr,cs=[["height","marginTop","marginBottom","paddingTop","paddingBottom"],["width","marginLeft","marginRight","paddingLeft","paddingRight"],["opacity"]],ct;f.fn.extend({show:function(a,b,c){var d,e;if(a||a===0)return this.animate(cw("show",3),a,b,c);for(var g=0,h=this.length;g<h;g++)d=this[g],d.style&&(e=d.style.display,!f._data(d,"olddisplay")&&e==="none"&&(e=d.style.display=""),e===""&&f.css(d,"display")==="none"&&f._data(d,"olddisplay",cx(d.nodeName)));for(g=0;g<h;g++){d=this[g];if(d.style){e=d.style.display;if(e===""||e==="none")d.style.display=f._data(d,"olddisplay")||""}}return this},hide:function(a,b,c){if(a||a===0)return this.animate(cw("hide",3),a,b,c);var d,e,g=0,h=this.length;for(;g<h;g++)d=this[g],d.style&&(e=f.css(d,"display"),e!=="none"&&!f._data(d,"olddisplay")&&f._data(d,"olddisplay",e));for(g=0;g<h;g++)this[g].style&&(this[g].style.display="none");return this},_toggle:f.fn.toggle,toggle:function(a,b,c){var d=typeof a=="boolean";f.isFunction(a)&&f.isFunction(b)?this._toggle.apply(this,arguments):a==null||d?this.each(function(){var b=d?a:f(this).is(":hidden");f(this)[b?"show":"hide"]()}):this.animate(cw("toggle",3),a,b,c);return this},fadeTo:function(a,b,c,d){return this.filter(":hidden").css("opacity",0).show().end().animate({opacity:b},a,c,d)},animate:function(a,b,c,d){function g(){e.queue===!1&&f._mark(this);var b=f.extend({},e),c=this.nodeType===1,d=c&&f(this).is(":hidden"),g,h,i,j,k,l,m,n,o;b.animatedProperties={};for(i in a){g=f.camelCase(i),i!==g&&(a[g]=a[i],delete a[i]),h=a[g],f.isArray(h)?(b.animatedProperties[g]=h[1],h=a[g]=h[0]):b.animatedProperties[g]=b.specialEasing&&b.specialEasing[g]||b.easing||"swing";if(h==="hide"&&d||h==="show"&&!d)return b.complete.call(this);c&&(g==="height"||g==="width")&&(b.overflow=[this.style.overflow,this.style.overflowX,this.style.overflowY],f.css(this,"display")==="inline"&&f.css(this,"float")==="none"&&(!f.support.inlineBlockNeedsLayout||cx(this.nodeName)==="inline"?this.style.display="inline-block":this.style.zoom=1))}b.overflow!=null&&(this.style.overflow="hidden");for(i in a)j=new f.fx(this,b,i),h=a[i],cp.test(h)?(o=f._data(this,"toggle"+i)||(h==="toggle"?d?"show":"hide":0),o?(f._data(this,"toggle"+i,o==="show"?"hide":"show"),j[o]()):j[h]()):(k=cq.exec(h),l=j.cur(),k?(m=parseFloat(k[2]),n=k[3]||(f.cssNumber[i]?"":"px"),n!=="px"&&(f.style(this,i,(m||1)+n),l=(m||1)/j.cur()*l,f.style(this,i,l+n)),k[1]&&(m=(k[1]==="-="?-1:1)*m+l),j.custom(l,m,n)):j.custom(l,h,""));return!0}var e=f.speed(b,c,d);if(f.isEmptyObject(a))return this.each(e.complete,[!1]);a=f.extend({},a);return e.queue===!1?this.each(g):this.queue(e.queue,g)},stop:function(a,c,d){typeof a!="string"&&(d=c,c=a,a=b),c&&a!==!1&&this.queue(a||"fx",[]);return this.each(function(){function h(a,b,c){var e=b[c];f.removeData(a,c,!0),e.stop(d)}var b,c=!1,e=f.timers,g=f._data(this);d||f._unmark(!0,this);if(a==null)for(b in g)g[b].stop&&b.indexOf(".run")===b.length-4&&h(this,g,b);else g[b=a+".run"]&&g[b].stop&&h(this,g,b);for(b=e.length;b--;)e[b].elem===this&&(a==null||e[b].queue===a)&&(d?e[b](!0):e[b].saveState(),c=!0,e.splice(b,1));(!d||!c)&&f.dequeue(this,a)})}}),f.each({slideDown:cw("show",1),slideUp:cw("hide",1),slideToggle:cw("toggle",1),fadeIn:{opacity:"show"},fadeOut:{opacity:"hide"},fadeToggle:{opacity:"toggle"}},function(a,b){f.fn[a]=function(a,c,d){return this.animate(b,a,c,d)}}),f.extend({speed:function(a,b,c){var d=a&&typeof a=="object"?f.extend({},a):{complete:c||!c&&b||f.isFunction(a)&&a,duration:a,easing:c&&b||b&&!f.isFunction(b)&&b};d.duration=f.fx.off?0:typeof d.duration=="number"?d.duration:d.duration in f.fx.speeds?f.fx.speeds[d.duration]:f.fx.speeds._default;if(d.queue==null||d.queue===!0)d.queue="fx";d.old=d.complete,d.complete=function(a){f.isFunction(d.old)&&d.old.call(this),d.queue?f.dequeue(this,d.queue):a!==!1&&f._unmark(this)};return d},easing:{linear:function(a,b,c,d){return c+d*a},swing:function(a,b,c,d){return(-Math.cos(a*Math.PI)/2+.5)*d+c}},timers:[],fx:function(a,b,c){this.options=b,this.elem=a,this.prop=c,b.orig=b.orig||{}}}),f.fx.prototype={update:function(){this.options.step&&this.options.step.call(this.elem,this.now,this),(f.fx.step[this.prop]||f.fx.step._default)(this)},cur:function(){if(this.elem[this.prop]!=null&&(!this.elem.style||this.elem.style[this.prop]==null))return this.elem[this.prop];var a,b=f.css(this.elem,this.prop);return isNaN(a=parseFloat(b))?!b||b==="auto"?0:b:a},custom:function(a,c,d){function h(a){return e.step(a)}var e=this,g=f.fx;this.startTime=ct||cu(),this.end=c,this.now=this.start=a,this.pos=this.state=0,this.unit=d||this.unit||(f.cssNumber[this.prop]?"":"px"),h.queue=this.options.queue,h.elem=this.elem,h.saveState=function(){e.options.hide&&f._data(e.elem,"fxshow"+e.prop)===b&&f._data(e.elem,"fxshow"+e.prop,e.start)},h()&&f.timers.push(h)&&!cr&&(cr=setInterval(g.tick,g.interval))},show:function(){var a=f._data(this.elem,"fxshow"+this.prop);this.options.orig[this.prop]=a||f.style(this.elem,this.prop),this.options.show=!0,a!==b?this.custom(this.cur(),a):this.custom(this.prop==="width"||this.prop==="height"?1:0,this.cur()),f(this.elem).show()},hide:function(){this.options.orig[this.prop]=f._data(this.elem,"fxshow"+this.prop)||f.style(this.elem,this.prop),this.options.hide=!0,this.custom(this.cur(),0)},step:function(a){var b,c,d,e=ct||cu(),g=!0,h=this.elem,i=this.options;if(a||e>=i.duration+this.startTime){this.now=this.end,this.pos=this.state=1,this.update(),i.animatedProperties[this.prop]=!0;for(b in i.animatedProperties)i.animatedProperties[b]!==!0&&(g=!1);if(g){i.overflow!=null&&!f.support.shrinkWrapBlocks&&f.each(["","X","Y"],function(a,b){h.style["overflow"+b]=i.overflow[a]}),i.hide&&f(h).hide();if(i.hide||i.show)for(b in i.animatedProperties)f.style(h,b,i.orig[b]),f.removeData(h,"fxshow"+b,!0),f.removeData(h,"toggle"+b,!0);d=i.complete,d&&(i.complete=!1,d.call(h))}return!1}i.duration==Infinity?this.now=e:(c=e-this.startTime,this.state=c/i.duration,this.pos=f.easing[i.animatedProperties[this.prop]](this.state,c,0,1,i.duration),this.now=this.start+(this.end-this.start)*this.pos),this.update();return!0}},f.extend(f.fx,{tick:function(){var a,b=f.timers,c=0;for(;c<b.length;c++)a=b[c],!a()&&b[c]===a&&b.splice(c--,1);b.length||f.fx.stop()},interval:13,stop:function(){clearInterval(cr),cr=null},speeds:{slow:600,fast:200,_default:400},step:{opacity:function(a){f.style(a.elem,"opacity",a.now)},_default:function(a){a.elem.style&&a.elem.style[a.prop]!=null?a.elem.style[a.prop]=a.now+a.unit:a.elem[a.prop]=a.now}}}),f.each(["width","height"],function(a,b){f.fx.step[b]=function(a){f.style(a.elem,b,Math.max(0,a.now))}}),f.expr&&f.expr.filters&&(f.expr.filters.animated=function(a){return f.grep(f.timers,function(b){return a===b.elem}).length});var cy=/^t(?:able|d|h)$/i,cz=/^(?:body|html)$/i;"getBoundingClientRect"in c.documentElement?f.fn.offset=function(a){var b=this[0],c;if(a)return this.each(function(b){f.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return f.offset.bodyOffset(b);try{c=b.getBoundingClientRect()}catch(d){}var e=b.ownerDocument,g=e.documentElement;if(!c||!f.contains(g,b))return c?{top:c.top,left:c.left}:{top:0,left:0};var h=e.body,i=cA(e),j=g.clientTop||h.clientTop||0,k=g.clientLeft||h.clientLeft||0,l=i.pageYOffset||f.support.boxModel&&g.scrollTop||h.scrollTop,m=i.pageXOffset||f.support.boxModel&&g.scrollLeft||h.scrollLeft,n=c.top+l-j,o=c.left+m-k;return{top:n,left:o}}:f.fn.offset=function(a){var b=this[0];if(a)return this.each(function(b){f.offset.setOffset(this,a,b)});if(!b||!b.ownerDocument)return null;if(b===b.ownerDocument.body)return f.offset.bodyOffset(b);var c,d=b.offsetParent,e=b,g=b.ownerDocument,h=g.documentElement,i=g.body,j=g.defaultView,k=j?j.getComputedStyle(b,null):b.currentStyle,l=b.offsetTop,m=b.offsetLeft;while((b=b.parentNode)&&b!==i&&b!==h){if(f.support.fixedPosition&&k.position==="fixed")break;c=j?j.getComputedStyle(b,null):b.currentStyle,l-=b.scrollTop,m-=b.scrollLeft,b===d&&(l+=b.offsetTop,m+=b.offsetLeft,f.support.doesNotAddBorder&&(!f.support.doesAddBorderForTableAndCells||!cy.test(b.nodeName))&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),e=d,d=b.offsetParent),f.support.subtractsBorderForOverflowNotVisible&&c.overflow!=="visible"&&(l+=parseFloat(c.borderTopWidth)||0,m+=parseFloat(c.borderLeftWidth)||0),k=c}if(k.position==="relative"||k.position==="static")l+=i.offsetTop,m+=i.offsetLeft;f.support.fixedPosition&&k.position==="fixed"&&(l+=Math.max(h.scrollTop,i.scrollTop),m+=Math.max(h.scrollLeft,i.scrollLeft));return{top:l,left:m}},f.offset={bodyOffset:function(a){var b=a.offsetTop,c=a.offsetLeft;f.support.doesNotIncludeMarginInBodyOffset&&(b+=parseFloat(f.css(a,"marginTop"))||0,c+=parseFloat(f.css(a,"marginLeft"))||0);return{top:b,left:c}},setOffset:function(a,b,c){var d=f.css(a,"position");d==="static"&&(a.style.position="relative");var e=f(a),g=e.offset(),h=f.css(a,"top"),i=f.css(a,"left"),j=(d==="absolute"||d==="fixed")&&f.inArray("auto",[h,i])>-1,k={},l={},m,n;j?(l=e.position(),m=l.top,n=l.left):(m=parseFloat(h)||0,n=parseFloat(i)||0),f.isFunction(b)&&(b=b.call(a,c,g)),b.top!=null&&(k.top=b.top-g.top+m),b.left!=null&&(k.left=b.left-g.left+n),"using"in b?b.using.call(a,k):e.css(k)}},f.fn.extend({position:function(){if(!this[0])return null;var a=this[0],b=this.offsetParent(),c=this.offset(),d=cz.test(b[0].nodeName)?{top:0,left:0}:b.offset();c.top-=parseFloat(f.css(a,"marginTop"))||0,c.left-=parseFloat(f.css(a,"marginLeft"))||0,d.top+=parseFloat(f.css(b[0],"borderTopWidth"))||0,d.left+=parseFloat(f.css(b[0],"borderLeftWidth"))||0;return{top:c.top-d.top,left:c.left-d.left}},offsetParent:function(){return this.map(function(){var a=this.offsetParent||c.body;while(a&&!cz.test(a.nodeName)&&f.css(a,"position")==="static")a=a.offsetParent;return a})}}),f.each(["Left","Top"],function(a,c){var d="scroll"+c;f.fn[d]=function(c){var e,g;if(c===b){e=this[0];if(!e)return null;g=cA(e);return g?"pageXOffset"in g?g[a?"pageYOffset":"pageXOffset"]:f.support.boxModel&&g.document.documentElement[d]||g.document.body[d]:e[d]}return this.each(function(){g=cA(this),g?g.scrollTo(a?f(g).scrollLeft():c,a?c:f(g).scrollTop()):this[d]=c})}}),f.each(["Height","Width"],function(a,c){var d=c.toLowerCase();f.fn["inner"+c]=function(){var a=this[0];return a?a.style?parseFloat(f.css(a,d,"padding")):this[d]():null},f.fn["outer"+c]=function(a){var b=this[0];return b?b.style?parseFloat(f.css(b,d,a?"margin":"border")):this[d]():null},f.fn[d]=function(a){var e=this[0];if(!e)return a==null?null:this;if(f.isFunction(a))return this.each(function(b){var c=f(this);c[d](a.call(this,b,c[d]()))});if(f.isWindow(e)){var g=e.document.documentElement["client"+c],h=e.document.body;return e.document.compatMode==="CSS1Compat"&&g||h&&h["client"+c]||g}if(e.nodeType===9)return Math.max(e.documentElement["client"+c],e.body["scroll"+c],e.documentElement["scroll"+c],e.body["offset"+c],e.documentElement["offset"+c]);if(a===b){var i=f.css(e,d),j=parseFloat(i);return f.isNumeric(j)?j:i}return this.css(d,typeof a=="string"?a:a+"px")}}),a.jQuery=a.$=f})(window); |
src/routes/error/ErrorPage.js | devcharleneg/twitter-react-app | /**
* 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/forerunnerdb/1.3.412/fdb-legacy.js | menuka94/cdnjs | (function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){
var Core = _dereq_('../lib/Core'),
CollectionGroup = _dereq_('../lib/CollectionGroup'),
View = _dereq_('../lib/View'),
Highchart = _dereq_('../lib/Highchart'),
Persist = _dereq_('../lib/Persist'),
Document = _dereq_('../lib/Document'),
Overview = _dereq_('../lib/Overview'),
OldView = _dereq_('../lib/OldView'),
OldViewBind = _dereq_('../lib/OldView.Bind'),
Grid = _dereq_('../lib/Grid');
if (typeof window !== 'undefined') {
window.ForerunnerDB = Core;
}
module.exports = Core;
},{"../lib/CollectionGroup":5,"../lib/Core":6,"../lib/Document":9,"../lib/Grid":10,"../lib/Highchart":11,"../lib/OldView":27,"../lib/OldView.Bind":26,"../lib/Overview":30,"../lib/Persist":32,"../lib/View":38}],2:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Creates an always-sorted multi-key bucket that allows ForerunnerDB to
* know the index that a document will occupy in an array with minimal
* processing, speeding up things like sorted views.
* @param {object} orderBy An order object.
* @constructor
*/
var ActiveBucket = function (orderBy) {
var sortKey;
this._primaryKey = '_id';
this._keyArr = [];
this._data = [];
this._objLookup = {};
this._count = 0;
for (sortKey in orderBy) {
if (orderBy.hasOwnProperty(sortKey)) {
this._keyArr.push({
key: sortKey,
dir: orderBy[sortKey]
});
}
}
};
Shared.addModule('ActiveBucket', ActiveBucket);
Shared.mixin(ActiveBucket.prototype, 'Mixin.Sorting');
/**
* Gets / sets the primary key used by the active bucket.
* @returns {String} The current primary key.
*/
Shared.synthesize(ActiveBucket.prototype, 'primaryKey');
/**
* Quicksorts a single document into the passed array and
* returns the index that the document should occupy.
* @param {object} obj The document to calculate index for.
* @param {array} arr The array the document index will be
* calculated for.
* @param {string} item The string key representation of the
* document whose index is being calculated.
* @param {function} fn The comparison function that is used
* to determine if a document is sorted below or above the
* document we are calculating the index for.
* @returns {number} The index the document should occupy.
*/
ActiveBucket.prototype.qs = function (obj, arr, item, fn) {
// If the array is empty then return index zero
if (!arr.length) {
return 0;
}
var lastMidwayIndex = -1,
midwayIndex,
lookupItem,
result,
start = 0,
end = arr.length - 1;
// Loop the data until our range overlaps
while (end >= start) {
// Calculate the midway point (divide and conquer)
midwayIndex = Math.floor((start + end) / 2);
if (lastMidwayIndex === midwayIndex) {
// No more items to scan
break;
}
// Get the item to compare against
lookupItem = arr[midwayIndex];
if (lookupItem !== undefined) {
// Compare items
result = fn(this, obj, item, lookupItem);
if (result > 0) {
start = midwayIndex + 1;
}
if (result < 0) {
end = midwayIndex - 1;
}
}
lastMidwayIndex = midwayIndex;
}
if (result > 0) {
return midwayIndex + 1;
} else {
return midwayIndex;
}
};
/**
* Calculates the sort position of an item against another item.
* @param {object} sorter An object or instance that contains
* sortAsc and sortDesc methods.
* @param {object} obj The document to compare.
* @param {string} a The first key to compare.
* @param {string} b The second key to compare.
* @returns {number} Either 1 for sort a after b or -1 to sort
* a before b.
* @private
*/
ActiveBucket.prototype._sortFunc = function (sorter, obj, a, b) {
var aVals = a.split('.:.'),
bVals = b.split('.:.'),
arr = sorter._keyArr,
count = arr.length,
index,
sortType,
castType;
for (index = 0; index < count; index++) {
sortType = arr[index];
castType = typeof obj[sortType.key];
if (castType === 'number') {
aVals[index] = Number(aVals[index]);
bVals[index] = Number(bVals[index]);
}
// Check for non-equal items
if (aVals[index] !== bVals[index]) {
// Return the sorted items
if (sortType.dir === 1) {
return sorter.sortAsc(aVals[index], bVals[index]);
}
if (sortType.dir === -1) {
return sorter.sortDesc(aVals[index], bVals[index]);
}
}
}
};
/**
* Inserts a document into the active bucket.
* @param {object} obj The document to insert.
* @returns {number} The index the document now occupies.
*/
ActiveBucket.prototype.insert = function (obj) {
var key,
keyIndex;
key = this.documentKey(obj);
keyIndex = this._data.indexOf(key);
if (keyIndex === -1) {
// Insert key
keyIndex = this.qs(obj, this._data, key, this._sortFunc);
this._data.splice(keyIndex, 0, key);
} else {
this._data.splice(keyIndex, 0, key);
}
this._objLookup[obj[this._primaryKey]] = key;
this._count++;
return keyIndex;
};
/**
* Removes a document from the active bucket.
* @param {object} obj The document to remove.
* @returns {boolean} True if the document was removed
* successfully or false if it wasn't found in the active
* bucket.
*/
ActiveBucket.prototype.remove = function (obj) {
var key,
keyIndex;
key = this._objLookup[obj[this._primaryKey]];
if (key) {
keyIndex = this._data.indexOf(key);
if (keyIndex > -1) {
this._data.splice(keyIndex, 1);
delete this._objLookup[obj[this._primaryKey]];
this._count--;
return true;
} else {
return false;
}
}
return false;
};
/**
* Get the index that the passed document currently occupies
* or the index it will occupy if added to the active bucket.
* @param {object} obj The document to get the index for.
* @returns {number} The index.
*/
ActiveBucket.prototype.index = function (obj) {
var key,
keyIndex;
key = this.documentKey(obj);
keyIndex = this._data.indexOf(key);
if (keyIndex === -1) {
// Get key index
keyIndex = this.qs(obj, this._data, key, this._sortFunc);
}
return keyIndex;
};
/**
* The key that represents the passed document.
* @param {object} obj The document to get the key for.
* @returns {string} The document key.
*/
ActiveBucket.prototype.documentKey = function (obj) {
var key = '',
arr = this._keyArr,
count = arr.length,
index,
sortType;
for (index = 0; index < count; index++) {
sortType = arr[index];
if (key) {
key += '.:.';
}
key += obj[sortType.key];
}
// Add the unique identifier on the end of the key
key += '.:.' + obj[this._primaryKey];
return key;
};
/**
* Get the number of documents currently indexed in the active
* bucket instance.
* @returns {number} The number of documents.
*/
ActiveBucket.prototype.count = function () {
return this._count;
};
Shared.finishModule('ActiveBucket');
module.exports = ActiveBucket;
},{"./Shared":37}],3:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
var BinaryTree = function (data, compareFunc, hashFunc) {
this.init.apply(this, arguments);
};
BinaryTree.prototype.init = function (data, index, compareFunc, hashFunc) {
this._store = [];
this._keys = [];
if (index !== undefined) { this.index(index); }
if (compareFunc !== undefined) { this.compareFunc(compareFunc); }
if (hashFunc !== undefined) { this.hashFunc(hashFunc); }
if (data !== undefined) { this.data(data); }
};
Shared.addModule('BinaryTree', BinaryTree);
Shared.mixin(BinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(BinaryTree.prototype, 'Mixin.Sorting');
Shared.mixin(BinaryTree.prototype, 'Mixin.Common');
Shared.synthesize(BinaryTree.prototype, 'compareFunc');
Shared.synthesize(BinaryTree.prototype, 'hashFunc');
Shared.synthesize(BinaryTree.prototype, 'indexDir');
Shared.synthesize(BinaryTree.prototype, 'keys');
Shared.synthesize(BinaryTree.prototype, 'index', function (index) {
if (index !== undefined) {
// Convert the index object to an array of key val objects
this.keys(this.extractKeys(index));
}
return this.$super.call(this, index);
});
BinaryTree.prototype.extractKeys = function (obj) {
var i,
keys = [];
for (i in obj) {
if (obj.hasOwnProperty(i)) {
keys.push({
key: i,
val: obj[i]
});
}
}
return keys;
};
BinaryTree.prototype.data = function (val) {
if (val !== undefined) {
this._data = val;
if (this._hashFunc) { this._hash = this._hashFunc(val); }
return this;
}
return this._data;
};
/**
* Pushes an item to the binary tree node's store array.
* @param {*} val The item to add to the store.
* @returns {*}
*/
BinaryTree.prototype.push = function (val) {
if (val !== undefined) {
this._store.push(val);
return this;
}
return false;
};
/**
* Pulls an item from the binary tree node's store array.
* @param {*} val The item to remove from the store.
* @returns {*}
*/
BinaryTree.prototype.pull = function (val) {
if (val !== undefined) {
var index = this._store.indexOf(val);
if (index > -1) {
this._store.splice(index, 1);
return this;
}
}
return false;
};
/**
* Default compare method. Can be overridden.
* @param a
* @param b
* @returns {number}
* @private
*/
BinaryTree.prototype._compareFunc = function (a, b) {
// Loop the index array
var i,
indexData,
result = 0;
for (i = 0; i < this._keys.length; i++) {
indexData = this._keys[i];
if (indexData.val === 1) {
result = this.sortAsc(a[indexData.key], b[indexData.key]);
} else if (indexData.val === -1) {
result = this.sortDesc(a[indexData.key], b[indexData.key]);
}
if (result !== 0) {
return result;
}
}
return result;
};
/**
* Default hash function. Can be overridden.
* @param obj
* @private
*/
BinaryTree.prototype._hashFunc = function (obj) {
/*var i,
indexData,
hash = '';
for (i = 0; i < this._keys.length; i++) {
indexData = this._keys[i];
if (hash) { hash += '_'; }
hash += obj[indexData.key];
}
return hash;*/
return obj[this._keys[0].key];
};
BinaryTree.prototype.insert = function (data) {
var result,
inserted,
failed,
i;
if (data instanceof Array) {
// Insert array of data
inserted = [];
failed = [];
for (i = 0; i < data.length; i++) {
if (this.insert(data[i])) {
inserted.push(data[i]);
} else {
failed.push(data[i]);
}
}
return {
inserted: inserted,
failed: failed
};
}
if (!this._data) {
// Insert into this node (overwrite) as there is no data
this.data(data);
//this.push(data);
return true;
}
result = this._compareFunc(this._data, data);
if (result === 0) {
this.push(data);
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._compareFunc, this._hashFunc);
}
return true;
}
if (result === -1) {
// Greater than this node
if (this._right) {
// Propagate down the right branch
this._right.insert(data);
} else {
// Assign to right branch
this._right = new BinaryTree(data, this._index, this._compareFunc, this._hashFunc);
}
return true;
}
if (result === 1) {
// Less than this node
if (this._left) {
// Propagate down the left branch
this._left.insert(data);
} else {
// Assign to left branch
this._left = new BinaryTree(data, this._index, this._compareFunc, this._hashFunc);
}
return true;
}
return false;
};
BinaryTree.prototype.lookup = function (data, resultArr) {
var result = this._compareFunc(this._data, data);
resultArr = resultArr || [];
if (result === 0) {
if (this._left) { this._left.lookup(data, resultArr); }
resultArr.push(this._data);
if (this._right) { this._right.lookup(data, resultArr); }
}
if (result === -1) {
if (this._right) { this._right.lookup(data, resultArr); }
}
if (result === 1) {
if (this._left) { this._left.lookup(data, resultArr); }
}
return resultArr;
};
BinaryTree.prototype.inOrder = function (type, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.inOrder(type, resultArr);
}
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
if (this._right) {
this._right.inOrder(type, resultArr);
}
return resultArr;
};
/*BinaryTree.prototype.find = function (type, search, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.find(type, search, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.find(type, search, resultArr);
}
return resultArr;
};*/
/**
*
* @param {String} type
* @param {String} key The data key / path to range search against.
* @param {Number} from Range search from this value (inclusive)
* @param {Number} to Range search to this value (inclusive)
* @param {Array=} resultArr Leave undefined when calling (internal use),
* passes the result array between recursive calls to be returned when
* the recursion chain completes.
* @param {Path=} pathResolver Leave undefined when calling (internal use),
* caches the path resolver instance for performance.
* @returns {Array} Array of matching document objects
*/
BinaryTree.prototype.findRange = function (type, key, from, to, resultArr, pathResolver) {
resultArr = resultArr || [];
pathResolver = pathResolver || new Path(key);
if (this._left) {
this._left.findRange(type, key, from, to, resultArr, pathResolver);
}
// Check if this node's data is greater or less than the from value
var pathVal = pathResolver.value(this._data),
fromResult = this.sortAsc(pathVal, from),
toResult = this.sortAsc(pathVal, to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.findRange(type, key, from, to, resultArr, pathResolver);
}
return resultArr;
};
/*BinaryTree.prototype.findRegExp = function (type, key, pattern, resultArr) {
resultArr = resultArr || [];
if (this._left) {
this._left.findRegExp(type, key, pattern, resultArr);
}
// Check if this node's data is greater or less than the from value
var fromResult = this.sortAsc(this._data[key], from),
toResult = this.sortAsc(this._data[key], to);
if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) {
// This data node is greater than or equal to the from value,
// and less than or equal to the to value so include it
switch (type) {
case 'hash':
resultArr.push(this._hash);
break;
case 'data':
resultArr.push(this._data);
break;
default:
resultArr.push({
key: this._data,
arr: this._store
});
break;
}
}
if (this._right) {
this._right.findRegExp(type, key, pattern, resultArr);
}
return resultArr;
};*/
BinaryTree.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path(),
indexKeyArr,
queryArr,
matchedKeys = [],
matchedKeyCount = 0,
i;
indexKeyArr = pathSolver.parseArr(this._index, {
verbose: true
});
queryArr = pathSolver.parseArr(query, {
ignore:/\$/,
verbose: true
});
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
Shared.finishModule('BinaryTree');
module.exports = BinaryTree;
},{"./Path":31,"./Shared":37}],4:[function(_dereq_,module,exports){
"use strict";
var Shared,
Db,
Metrics,
KeyValueStore,
Path,
IndexHashMap,
IndexBinaryTree,
Crc,
Overload,
ReactorIO;
Shared = _dereq_('./Shared');
/**
* Creates a new collection. Collections store multiple documents and
* handle CRUD against those documents.
* @constructor
*/
var Collection = function (name) {
this.init.apply(this, arguments);
};
Collection.prototype.init = function (name, options) {
this._primaryKey = '_id';
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._name = name;
this._data = [];
this._metrics = new Metrics();
this._options = options || {
changeTimestamp: false
};
// Create an object to store internal protected data
this._metaData = {};
this._deferQueue = {
insert: [],
update: [],
remove: [],
upsert: []
};
this._deferThreshold = {
insert: 100,
update: 100,
remove: 100,
upsert: 100
};
this._deferTime = {
insert: 1,
update: 1,
remove: 1,
upsert: 1
};
// Set the subset to itself since it is the root collection
this.subsetOf(this);
};
Shared.addModule('Collection', Collection);
Shared.mixin(Collection.prototype, 'Mixin.Common');
Shared.mixin(Collection.prototype, 'Mixin.Events');
Shared.mixin(Collection.prototype, 'Mixin.ChainReactor');
Shared.mixin(Collection.prototype, 'Mixin.CRUD');
Shared.mixin(Collection.prototype, 'Mixin.Constants');
Shared.mixin(Collection.prototype, 'Mixin.Triggers');
Shared.mixin(Collection.prototype, 'Mixin.Sorting');
Shared.mixin(Collection.prototype, 'Mixin.Matching');
Shared.mixin(Collection.prototype, 'Mixin.Updating');
Shared.mixin(Collection.prototype, 'Mixin.Tags');
Metrics = _dereq_('./Metrics');
KeyValueStore = _dereq_('./KeyValueStore');
Path = _dereq_('./Path');
IndexHashMap = _dereq_('./IndexHashMap');
IndexBinaryTree = _dereq_('./IndexBinaryTree');
Crc = _dereq_('./Crc');
Db = Shared.modules.Db;
Overload = _dereq_('./Overload');
ReactorIO = _dereq_('./ReactorIO');
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Collection.prototype.crc = Crc;
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'state');
/**
* Gets / sets the name of the collection.
* @param {String=} val The name of the collection to set.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'name');
/**
* Gets / sets the metadata stored in the collection.
*/
Shared.synthesize(Collection.prototype, 'metaData');
/**
* Get the data array that represents the collection's data.
* This data is returned by reference and should not be altered outside
* of the provided CRUD functionality of the collection as doing so
* may cause unstable index behaviour within the collection.
* @returns {Array}
*/
Collection.prototype.data = function () {
return this._data;
};
/**
* Drops a collection and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
Collection.prototype.drop = function (callback) {
var key;
if (!this.isDropped()) {
if (this._db && this._db._collection && this._name) {
if (this.debug()) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
this.emit('drop', this);
delete this._db._collection[this._name];
// Remove any reactor IO chain links
if (this._collate) {
for (key in this._collate) {
if (this._collate.hasOwnProperty(key)) {
this.collateRemove(key);
}
}
}
delete this._primaryKey;
delete this._primaryIndex;
delete this._primaryCrc;
delete this._crcLookup;
delete this._name;
delete this._data;
delete this._metrics;
if (callback) { callback(false, true); }
return true;
}
} else {
if (callback) { callback(false, true); }
return true;
}
if (callback) { callback(false, true); }
return false;
};
/**
* Gets / sets the primary key for this collection.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
Collection.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
if (this._primaryKey !== keyName) {
var oldKey = this._primaryKey;
this._primaryKey = keyName;
// Set the primary key index primary key
this._primaryIndex.primaryKey(keyName);
// Rebuild the primary key index
this.rebuildPrimaryKeyIndex();
// Propagate change down the chain
this.chainSend('primaryKey', keyName, {oldData: oldKey});
}
return this;
}
return this._primaryKey;
};
/**
* Handles insert events and routes changes to binds and views as required.
* @param {Array} inserted An array of inserted documents.
* @param {Array} failed An array of documents that failed to insert.
* @private
*/
Collection.prototype._onInsert = function (inserted, failed) {
this.emit('insert', inserted, failed);
};
/**
* Handles update events and routes changes to binds and views as required.
* @param {Array} items An array of updated documents.
* @private
*/
Collection.prototype._onUpdate = function (items) {
this.emit('update', items);
};
/**
* Handles remove events and routes changes to binds and views as required.
* @param {Array} items An array of removed documents.
* @private
*/
Collection.prototype._onRemove = function (items) {
this.emit('remove', items);
};
/**
* Handles any change to the collection.
* @private
*/
Collection.prototype._onChange = function () {
if (this._options.changeTimestamp) {
// Record the last change timestamp
this._metaData.lastChange = new Date();
}
};
/**
* Gets / sets the db instance this class instance belongs to.
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'db', function (db) {
if (db) {
if (this.primaryKey() === '_id') {
// Set primary key to the db's key by default
this.primaryKey(db.primaryKey());
// Apply the same debug settings
this.debug(db.debug());
}
}
return this.$super.apply(this, arguments);
});
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Collection.prototype, 'mongoEmulation');
/**
* Sets the collection's data to the array / documents passed. If any
* data already exists in the collection it will be removed before the
* new data is set.
* @param {Array|Object} data The array of documents or a single document
* that will be set as the collections data.
* @param options Optional options object.
* @param callback Optional callback function.
*/
Collection.prototype.setData = function (data, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (data) {
var op = this._metrics.create('setData');
op.start();
options = this.options(options);
this.preSetData(data, options, callback);
if (options.$decouple) {
data = this.decouple(data);
}
if (!(data instanceof Array)) {
data = [data];
}
op.time('transformIn');
data = this.transformIn(data);
op.time('transformIn');
var oldData = [].concat(this._data);
this._dataReplace(data);
// Update the primary key index
op.time('Rebuild Primary Key Index');
this.rebuildPrimaryKeyIndex(options);
op.time('Rebuild Primary Key Index');
// Rebuild all other indexes
op.time('Rebuild All Other Indexes');
this._rebuildIndexes();
op.time('Rebuild All Other Indexes');
op.time('Resolve chains');
this.chainSend('setData', data, {oldData: oldData});
op.time('Resolve chains');
op.stop();
this._onChange();
this.emit('setData', this._data, oldData);
}
if (callback) { callback(false); }
return this;
};
/**
* Drops and rebuilds the primary key index for all documents in the collection.
* @param {Object=} options An optional options object.
* @private
*/
Collection.prototype.rebuildPrimaryKeyIndex = function (options) {
options = options || {
$ensureKeys: undefined,
$violationCheck: undefined
};
var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true,
violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true,
arr,
arrCount,
arrItem,
pIndex = this._primaryIndex,
crcIndex = this._primaryCrc,
crcLookup = this._crcLookup,
pKey = this._primaryKey,
jString;
// Drop the existing primary index
pIndex.truncate();
crcIndex.truncate();
crcLookup.truncate();
// Loop the data and check for a primary key in each object
arr = this._data;
arrCount = arr.length;
while (arrCount--) {
arrItem = arr[arrCount];
if (ensureKeys) {
// Make sure the item has a primary key
this.ensurePrimaryKey(arrItem);
}
if (violationCheck) {
// Check for primary key violation
if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) {
// Primary key violation
throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]);
}
} else {
pIndex.set(arrItem[pKey], arrItem);
}
// Generate a CRC string
jString = this.jStringify(arrItem);
crcIndex.set(arrItem[pKey], jString);
crcLookup.set(jString, arrItem);
}
};
/**
* Checks for a primary key on the document and assigns one if none
* currently exists.
* @param {Object} obj The object to check a primary key against.
* @private
*/
Collection.prototype.ensurePrimaryKey = function (obj) {
if (obj[this._primaryKey] === undefined) {
// Assign a primary key automatically
obj[this._primaryKey] = this.objectId();
}
};
/**
* Clears all data from the collection.
* @returns {Collection}
*/
Collection.prototype.truncate = function () {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
this.emit('truncate', this._data);
// Clear all the data from the collection
this._data.length = 0;
// Re-create the primary index data
this._primaryIndex = new KeyValueStore('primary');
this._primaryCrc = new KeyValueStore('primaryCrc');
this._crcLookup = new KeyValueStore('crcLookup');
this._onChange();
this.deferEmit('change', {type: 'truncate'});
return this;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} obj The document object to upsert or an array containing
* documents to upsert.
*
* If the document contains a primary key field (based on the collections's primary
* key) then the database will search for an existing document with a matching id.
* If a matching document is found, the document will be updated. Any keys that
* match keys on the existing document will be overwritten with new data. Any keys
* that do not currently exist on the document will be added to the document.
*
* If the document does not contain an id or the id passed does not match an existing
* document, an insert is performed instead. If no id is present a new primary key
* id is provided for the item.
*
* @param {Function=} callback Optional callback method.
* @returns {Object} An object containing two keys, "op" contains either "insert" or
* "update" depending on the type of operation that was performed and "result"
* contains the return data from the operation used.
*/
Collection.prototype.upsert = function (obj, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (obj) {
var queue = this._deferQueue.upsert,
deferThreshold = this._deferThreshold.upsert;
var returnData = {},
query,
i;
// Determine if the object passed is an array or not
if (obj instanceof Array) {
if (obj.length > deferThreshold) {
// Break up upsert into blocks
this._deferQueue.upsert = queue.concat(obj);
// Fire off the insert queue handler
this.processQueue('upsert', callback);
return {};
} else {
// Loop the array and upsert each item
returnData = [];
for (i = 0; i < obj.length; i++) {
returnData.push(this.upsert(obj[i]));
}
if (callback) { callback(); }
return returnData;
}
}
// Determine if the operation is an insert or an update
if (obj[this._primaryKey]) {
// Check if an object with this primary key already exists
query = {};
query[this._primaryKey] = obj[this._primaryKey];
if (this._primaryIndex.lookup(query)[0]) {
// The document already exists with this id, this operation is an update
returnData.op = 'update';
} else {
// No document with this id exists, this operation is an insert
returnData.op = 'insert';
}
} else {
// The document passed does not contain an id, this operation is an insert
returnData.op = 'insert';
}
switch (returnData.op) {
case 'insert':
returnData.result = this.insert(obj);
break;
case 'update':
returnData.result = this.update(query, obj);
break;
default:
break;
}
return returnData;
} else {
if (callback) { callback(); }
}
return {};
};
/**
* Executes a method against each document that matches query and returns an
* array of documents that may have been modified by the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the results.
* @param {Object=} options Optional options object.
* @returns {Array}
*/
Collection.prototype.filter = function (query, func, options) {
return (this.find(query, options)).filter(func);
};
/**
* Executes a method against each document that matches query and then executes
* an update based on the return data of the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the update.
* @param {Object=} options Optional options object passed to the initial find call.
* @returns {Array}
*/
Collection.prototype.filterUpdate = function (query, func, options) {
var items = this.find(query, options),
results = [],
singleItem,
singleQuery,
singleUpdate,
pk = this.primaryKey(),
i;
for (i = 0; i < items.length; i++) {
singleItem = items[i];
singleUpdate = func(singleItem);
if (singleUpdate) {
singleQuery = {};
singleQuery[pk] = singleItem[pk];
results.push(this.update(singleQuery, singleUpdate));
}
}
return results;
};
/**
* Modifies an existing document or documents in a collection. This will update
* all matches for 'query' with the data held in 'update'. It will not overwrite
* the matched documents with the update document.
*
* @param {Object} query The query that must be matched for a document to be
* operated on.
* @param {Object} update The object containing updated key/values. Any keys that
* match keys on the existing document will be overwritten with this data. Any
* keys that do not currently exist on the document will be added to the document.
* @param {Object=} options An options object.
* @returns {Array} The items that were updated.
*/
Collection.prototype.update = function (query, update, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// Decouple the update data
update = this.decouple(update);
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
this.convertToFdb(update);
}
// Handle transform
update = this.transformIn(update);
if (this.debug()) {
console.log(this.logIdentifier() + ' Updating some data');
}
var self = this,
op = this._metrics.create('update'),
dataSet,
updated,
updateCall = function (referencedDoc) {
var oldDoc = self.decouple(referencedDoc),
newDoc,
triggerOperation,
result;
if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) {
newDoc = self.decouple(referencedDoc);
triggerOperation = {
type: 'update',
query: self.decouple(query),
update: self.decouple(update),
options: self.decouple(options),
op: op
};
// Update newDoc with the update criteria so we know what the data will look
// like AFTER the update is processed
result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, '');
if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, '');
// NOTE: If for some reason we would only like to fire this event if changes are actually going
// to occur on the object from the proposed update then we can add "result &&" to the if
self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc);
} else {
// Trigger cancelled operation so tell result that it was not updated
result = false;
}
} else {
// No triggers complained so let's execute the replacement of the existing
// object with the new one
result = self.updateObject(referencedDoc, update, query, options, '');
}
// Inform indexes of the change
self._updateIndexes(oldDoc, referencedDoc);
return result;
};
op.start();
op.time('Retrieve documents to update');
dataSet = this.find(query, {$decouple: false});
op.time('Retrieve documents to update');
if (dataSet.length) {
op.time('Update documents');
updated = dataSet.filter(updateCall);
op.time('Update documents');
if (updated.length) {
op.time('Resolve chains');
this.chainSend('update', {
query: query,
update: update,
dataSet: dataSet
}, options);
op.time('Resolve chains');
this._onUpdate(updated);
this._onChange();
this.deferEmit('change', {type: 'update', data: updated});
}
}
op.stop();
// TODO: Should we decouple the updated array before return by default?
return updated || [];
};
/**
* Replaces an existing object with data from the new object without
* breaking data references.
* @param {Object} currentObj The object to alter.
* @param {Object} newObj The new object to overwrite the existing one with.
* @returns {*} Chain.
* @private
*/
Collection.prototype._replaceObj = function (currentObj, newObj) {
var i;
// Check if the new document has a different primary key value from the existing one
// Remove item from indexes
this._removeFromIndexes(currentObj);
// Remove existing keys from current object
for (i in currentObj) {
if (currentObj.hasOwnProperty(i)) {
delete currentObj[i];
}
}
// Add new keys to current object
for (i in newObj) {
if (newObj.hasOwnProperty(i)) {
currentObj[i] = newObj[i];
}
}
// Update the item in the primary index
if (!this._insertIntoIndexes(currentObj)) {
throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]);
}
// Update the object in the collection data
//this._data.splice(this._data.indexOf(currentObj), 1, newObj);
return this;
};
/**
* Helper method to update a document from it's id.
* @param {String} id The id of the document.
* @param {Object} update The object containing the key/values to update to.
* @returns {Array} The items that were updated.
*/
Collection.prototype.updateById = function (id, update) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.update(searchObj, update);
};
/**
* Internal method for document updating.
* @param {Object} doc The document to update.
* @param {Object} update The object with key/value pairs to update the document with.
* @param {Object} query The query object that we need to match to perform an update.
* @param {Object} options An options object.
* @param {String} path The current recursive path.
* @param {String} opType The type of update operation to perform, if none is specified
* default is to set new data against matching fields.
* @returns {Boolean} True if the document was updated with new / changed data or
* false if it was not updated because the data was the same.
* @private
*/
Collection.prototype.updateObject = function (doc, update, query, options, path, opType) {
// TODO: This method is long, try to break it into smaller pieces
update = this.decouple(update);
// Clear leading dots from path
path = path || '';
if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); }
//var oldDoc = this.decouple(doc),
var updated = false,
recurseUpdated = false,
operation,
tmpArray,
tmpIndex,
tmpCount,
tempIndex,
pathInstance,
sourceIsArray,
updateIsArray,
i;
// Loop each key in the update object
for (i in update) {
if (update.hasOwnProperty(i)) {
// Reset operation flag
operation = false;
// Check if the property starts with a dollar (function)
if (i.substr(0, 1) === '$') {
// Check for commands
switch (i) {
case '$key':
case '$index':
case '$data':
case '$min':
case '$max':
// Ignore some operators
operation = true;
break;
case '$each':
operation = true;
// Loop over the array of updates and run each one
tmpCount = update.$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path);
if (recurseUpdated) {
updated = true;
}
}
updated = updated || recurseUpdated;
break;
default:
operation = true;
// Now run the operation
recurseUpdated = this.updateObject(doc, update[i], query, options, path, i);
updated = updated || recurseUpdated;
break;
}
}
// Check if the key has a .$ at the end, denoting an array lookup
if (this._isPositionalKey(i)) {
operation = true;
// Modify i to be the name of the field
i = i.substr(0, i.length - 2);
pathInstance = new Path(path + '.' + i);
// Check if the key is an array and has items
if (doc[i] && doc[i] instanceof Array && doc[i].length) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) {
tmpArray.push(tmpIndex);
}
}
// Loop the items that matched and update them
for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
}
}
if (!operation) {
if (!opType && typeof(update[i]) === 'object') {
if (doc[i] !== null && typeof(doc[i]) === 'object') {
// Check if we are dealing with arrays
sourceIsArray = doc[i] instanceof Array;
updateIsArray = update[i] instanceof Array;
if (sourceIsArray || updateIsArray) {
// Check if the update is an object and the doc is an array
if (!updateIsArray && sourceIsArray) {
// Update is an object, source is an array so match the array items
// with our query object to find the one to update inside this array
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
// Either both source and update are arrays or the update is
// an array and the source is not, so set source to update
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
// The doc key is an object so traverse the
// update further
recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType);
updated = updated || recurseUpdated;
}
} else {
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
}
} else {
switch (opType) {
case '$inc':
var doUpdate = true;
// Check for a $min / $max operator
if (update[i] > 0) {
if (update.$max) {
// Check current value
if (doc[i] >= update.$max) {
// Don't update
doUpdate = false;
}
}
} else if (update[i] < 0) {
if (update.$min) {
// Check current value
if (doc[i] <= update.$min) {
// Don't update
doUpdate = false;
}
}
}
if (doUpdate) {
this._updateIncrement(doc, i, update[i]);
updated = true;
}
break;
case '$cast':
// Casts a property to the type specified if it is not already
// that type. If the cast is an array or an object and the property
// is not already that type a new array or object is created and
// set to the property, overwriting the previous value
switch (update[i]) {
case 'array':
if (!(doc[i] instanceof Array)) {
// Cast to an array
this._updateProperty(doc, i, update.$data || []);
updated = true;
}
break;
case 'object':
if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) {
// Cast to an object
this._updateProperty(doc, i, update.$data || {});
updated = true;
}
break;
case 'number':
if (typeof doc[i] !== 'number') {
// Cast to a number
this._updateProperty(doc, i, Number(doc[i]));
updated = true;
}
break;
case 'string':
if (typeof doc[i] !== 'string') {
// Cast to a string
this._updateProperty(doc, i, String(doc[i]));
updated = true;
}
break;
default:
throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]);
}
break;
case '$push':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Check for a $position modifier with an $each
if (update[i].$position !== undefined && update[i].$each instanceof Array) {
// Grab the position to insert at
tempIndex = update[i].$position;
// Loop the each array and push each item
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]);
}
} else if (update[i].$each instanceof Array) {
// Do a loop over the each to push multiple items
tmpCount = update[i].$each.length;
for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) {
this._updatePush(doc[i], update[i].$each[tmpIndex]);
}
} else {
// Do a standard push
this._updatePush(doc[i], update[i]);
}
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')');
}
break;
case '$pull':
if (doc[i] instanceof Array) {
tmpArray = [];
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], options, '', {})) {
tmpArray.push(tmpIndex);
}
}
tmpCount = tmpArray.length;
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
this._updatePull(doc[i], tmpArray[tmpCount]);
updated = true;
}
}
break;
case '$pullAll':
if (doc[i] instanceof Array) {
if (update[i] instanceof Array) {
tmpArray = doc[i];
tmpCount = tmpArray.length;
if (tmpCount > 0) {
// Now loop the pull array and remove items to be pulled
while (tmpCount--) {
for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) {
if (tmpArray[tmpCount] === update[i][tempIndex]) {
this._updatePull(doc[i], tmpCount);
tmpCount--;
updated = true;
}
}
if (tmpCount < 0) {
break;
}
}
}
} else {
throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')');
}
}
break;
case '$addToSet':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
// Loop the target array and check for existence of item
var targetArr = doc[i],
targetArrIndex,
targetArrCount = targetArr.length,
objHash,
addObj = true,
optionObj = (options && options.$addToSet),
hashMode,
pathSolver;
// Check if we have an options object for our operation
if (update[i].$key) {
hashMode = false;
pathSolver = new Path(update[i].$key);
objHash = pathSolver.value(update[i])[0];
// Remove the key from the object before we add it
delete update[i].$key;
} else if (optionObj && optionObj.key) {
hashMode = false;
pathSolver = new Path(optionObj.key);
objHash = pathSolver.value(update[i])[0];
} else {
objHash = this.jStringify(update[i]);
hashMode = true;
}
for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) {
if (hashMode) {
// Check if objects match via a string hash (JSON)
if (this.jStringify(targetArr[targetArrIndex]) === objHash) {
// The object already exists, don't add it
addObj = false;
break;
}
} else {
// Check if objects match based on the path
if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) {
// The object already exists, don't add it
addObj = false;
break;
}
}
}
if (addObj) {
this._updatePush(doc[i], update[i]);
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')');
}
break;
case '$splicePush':
// Check if the target key is undefined and if so, create an array
if (doc[i] === undefined) {
// Initialise a new array
this._updateProperty(doc, i, []);
}
// Check that the target key is an array
if (doc[i] instanceof Array) {
tempIndex = update.$index;
if (tempIndex !== undefined) {
delete update.$index;
// Check for out of bounds index
if (tempIndex > doc[i].length) {
tempIndex = doc[i].length;
}
this._updateSplicePush(doc[i], tempIndex, update[i]);
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!');
}
} else {
throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')');
}
break;
case '$move':
if (doc[i] instanceof Array) {
// Loop the array and find matches to our search
for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) {
if (this._match(doc[i][tmpIndex], update[i], options, '', {})) {
var moveToIndex = update.$index;
if (moveToIndex !== undefined) {
delete update.$index;
this._updateSpliceMove(doc[i], tmpIndex, moveToIndex);
updated = true;
} else {
throw(this.logIdentifier() + ' Cannot move without a $index integer value!');
}
break;
}
}
} else {
throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')');
}
break;
case '$mul':
this._updateMultiply(doc, i, update[i]);
updated = true;
break;
case '$rename':
this._updateRename(doc, i, update[i]);
updated = true;
break;
case '$overwrite':
this._updateOverwrite(doc, i, update[i]);
updated = true;
break;
case '$unset':
this._updateUnset(doc, i);
updated = true;
break;
case '$clear':
this._updateClear(doc, i);
updated = true;
break;
case '$pop':
if (doc[i] instanceof Array) {
if (this._updatePop(doc[i], update[i])) {
updated = true;
}
} else {
throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')');
}
break;
case '$toggle':
// Toggle the boolean property between true and false
this._updateProperty(doc, i, !doc[i]);
updated = true;
break;
default:
if (doc[i] !== update[i]) {
this._updateProperty(doc, i, update[i]);
updated = true;
}
break;
}
}
}
}
}
return updated;
};
/**
* Determines if the passed key has an array positional mark (a dollar at the end
* of its name).
* @param {String} key The key to check.
* @returns {Boolean} True if it is a positional or false if not.
* @private
*/
Collection.prototype._isPositionalKey = function (key) {
return key.substr(key.length - 2, 2) === '.$';
};
/**
* Removes any documents from the collection that match the search query
* key/values.
* @param {Object} query The query object.
* @param {Object=} options An options object.
* @param {Function=} callback A callback method.
* @returns {Array} An array of the documents that were removed.
*/
Collection.prototype.remove = function (query, options, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var self = this,
dataSet,
index,
arrIndex,
returnArr,
removeMethod,
triggerOperation,
doc,
newDoc;
if (typeof(options) === 'function') {
callback = options;
options = {};
}
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (query instanceof Array) {
returnArr = [];
for (arrIndex = 0; arrIndex < query.length; arrIndex++) {
returnArr.push(this.remove(query[arrIndex], {noEmit: true}));
}
if (!options || (options && !options.noEmit)) {
this._onRemove(returnArr);
}
if (callback) { callback(false, returnArr); }
return returnArr;
} else {
dataSet = this.find(query, {$decouple: false});
if (dataSet.length) {
removeMethod = function (dataItem) {
// Remove the item from the collection's indexes
self._removeFromIndexes(dataItem);
// Remove data from internal stores
index = self._data.indexOf(dataItem);
self._dataRemoveAtIndex(index);
};
// Remove the data from the collection
for (var i = 0; i < dataSet.length; i++) {
doc = dataSet[i];
if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) {
triggerOperation = {
type: 'remove'
};
newDoc = self.decouple(doc);
if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) {
// The trigger didn't ask to cancel so execute the removal method
removeMethod(doc);
self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc);
}
} else {
// No triggers to execute
removeMethod(doc);
}
}
//op.time('Resolve chains');
this.chainSend('remove', {
query: query,
dataSet: dataSet
}, options);
//op.time('Resolve chains');
if (!options || (options && !options.noEmit)) {
this._onRemove(dataSet);
}
this._onChange();
this.deferEmit('change', {type: 'remove', data: dataSet});
}
if (callback) { callback(false, dataSet); }
return dataSet;
}
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
* @returns {Array} An array of documents that were removed.
*/
Collection.prototype.removeById = function (id) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.remove(searchObj);
};
/**
* Processes a deferred action queue.
* @param {String} type The queue name to process.
* @param {Function} callback A method to call when the queue has processed.
* @param {Object=} resultObj A temp object to hold results in.
*/
Collection.prototype.processQueue = function (type, callback, resultObj) {
var self = this,
queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type],
dataArr,
result;
resultObj = resultObj || {
deferred: true
};
if (queue.length) {
// Process items up to the threshold
if (queue.length) {
if (queue.length > deferThreshold) {
// Grab items up to the threshold value
dataArr = queue.splice(0, deferThreshold);
} else {
// Grab all the remaining items
dataArr = queue.splice(0, queue.length);
}
result = self[type](dataArr);
switch (type) {
case 'insert':
resultObj.inserted = resultObj.inserted || [];
resultObj.failed = resultObj.failed || [];
resultObj.inserted = resultObj.inserted.concat(result.inserted);
resultObj.failed = resultObj.failed.concat(result.failed);
break;
}
}
// Queue another process
setTimeout(function () {
self.processQueue.call(self, type, callback, resultObj);
}, deferTime);
} else {
if (callback) { callback(resultObj); }
}
// Check if all queues are complete
if (!this.isProcessingQueue()) {
this.emit('queuesComplete');
}
};
/**
* Checks if any CRUD operations have been deferred and are still waiting to
* be processed.
* @returns {Boolean} True if there are still deferred CRUD operations to process
* or false if all queues are clear.
*/
Collection.prototype.isProcessingQueue = function () {
var i;
for (i in this._deferQueue) {
if (this._deferQueue.hasOwnProperty(i)) {
if (this._deferQueue[i].length) {
return true;
}
}
}
return false;
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype.insert = function (data, index, callback) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
if (typeof(index) === 'function') {
callback = index;
index = this._data.length;
} else if (index === undefined) {
index = this._data.length;
}
data = this.transformIn(data);
return this._insertHandle(data, index, callback);
};
/**
* Inserts a document or array of documents into the collection.
* @param {Object|Array} data Either a document object or array of document
* @param {Number=} index Optional index to insert the record at.
* @param {Function=} callback Optional callback called once action is complete.
* objects to insert into the collection.
*/
Collection.prototype._insertHandle = function (data, index, callback) {
var //self = this,
queue = this._deferQueue.insert,
deferThreshold = this._deferThreshold.insert,
//deferTime = this._deferTime.insert,
inserted = [],
failed = [],
insertResult,
resultObj,
i;
if (data instanceof Array) {
// Check if there are more insert items than the insert defer
// threshold, if so, break up inserts so we don't tie up the
// ui or thread
if (data.length > deferThreshold) {
// Break up insert into blocks
this._deferQueue.insert = queue.concat(data);
// Fire off the insert queue handler
this.processQueue('insert', callback);
return;
} else {
// Loop the array and add items
for (i = 0; i < data.length; i++) {
insertResult = this._insert(data[i], index + i);
if (insertResult === true) {
inserted.push(data[i]);
} else {
failed.push({
doc: data[i],
reason: insertResult
});
}
}
}
} else {
// Store the data item
insertResult = this._insert(data, index);
if (insertResult === true) {
inserted.push(data);
} else {
failed.push({
doc: data,
reason: insertResult
});
}
}
//op.time('Resolve chains');
this.chainSend('insert', data, {index: index});
//op.time('Resolve chains');
resultObj = {
deferred: false,
inserted: inserted,
failed: failed
};
this._onInsert(inserted, failed);
if (callback) { callback(resultObj); }
this._onChange();
this.deferEmit('change', {type: 'insert', data: inserted});
return resultObj;
};
/**
* Internal method to insert a document into the collection. Will
* check for index violations before allowing the document to be inserted.
* @param {Object} doc The document to insert after passing index violation
* tests.
* @param {Number=} index Optional index to insert the document at.
* @returns {Boolean|Object} True on success, false if no document passed,
* or an object containing details about an index violation if one occurred.
* @private
*/
Collection.prototype._insert = function (doc, index) {
if (doc) {
var self = this,
indexViolation,
triggerOperation,
insertMethod,
newDoc;
this.ensurePrimaryKey(doc);
// Check indexes are not going to be broken by the document
indexViolation = this.insertIndexViolation(doc);
insertMethod = function (doc) {
// Add the item to the collection's indexes
self._insertIntoIndexes(doc);
// Check index overflow
if (index > self._data.length) {
index = self._data.length;
}
// Insert the document
self._dataInsertAtIndex(index, doc);
};
if (!indexViolation) {
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
triggerOperation = {
type: 'insert'
};
if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) {
insertMethod(doc);
if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) {
// Clone the doc so that the programmer cannot update the internal document
// on the "after" phase trigger
newDoc = self.decouple(doc);
self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc);
}
} else {
// The trigger just wants to cancel the operation
return false;
}
} else {
// No triggers to execute
insertMethod(doc);
}
return true;
} else {
return 'Index violation in index: ' + indexViolation;
}
}
return 'No document passed to insert';
};
/**
* Inserts a document into the internal collection data array at
* Inserts a document into the internal collection data array at
* the specified index.
* @param {number} index The index to insert at.
* @param {object} doc The document to insert.
* @private
*/
Collection.prototype._dataInsertAtIndex = function (index, doc) {
this._data.splice(index, 0, doc);
};
/**
* Removes a document from the internal collection data array at
* the specified index.
* @param {number} index The index to remove from.
* @private
*/
Collection.prototype._dataRemoveAtIndex = function (index) {
this._data.splice(index, 1);
};
/**
* Replaces all data in the collection's internal data array with
* the passed array of data.
* @param {array} data The array of data to replace existing data with.
* @private
*/
Collection.prototype._dataReplace = function (data) {
// Clear the array - using a while loop with pop is by far the
// fastest way to clear an array currently
while (this._data.length) {
this._data.pop();
}
// Append new items to the array
this._data = this._data.concat(data);
};
/**
* Inserts a document into the collection indexes.
* @param {Object} doc The document to insert.
* @private
*/
Collection.prototype._insertIntoIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
violated,
jString = this.jStringify(doc);
// Insert to primary key index
violated = this._primaryIndex.uniqueSet(doc[this._primaryKey], doc);
this._primaryCrc.uniqueSet(doc[this._primaryKey], jString);
this._crcLookup.uniqueSet(jString, doc);
// Insert into other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].insert(doc);
}
}
return violated;
};
/**
* Removes a document from the collection indexes.
* @param {Object} doc The document to remove.
* @private
*/
Collection.prototype._removeFromIndexes = function (doc) {
var arr = this._indexByName,
arrIndex,
jString = this.jStringify(doc);
// Remove from primary key index
this._primaryIndex.unSet(doc[this._primaryKey]);
this._primaryCrc.unSet(doc[this._primaryKey]);
this._crcLookup.unSet(jString);
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].remove(doc);
}
}
};
/**
* Updates collection index data for the passed document.
* @param {Object} oldDoc The old document as it was before the update.
* @param {Object} newDoc The document as it now is after the update.
* @private
*/
Collection.prototype._updateIndexes = function (oldDoc, newDoc) {
this._removeFromIndexes(oldDoc);
this._insertIntoIndexes(newDoc);
};
/**
* Rebuild collection indexes.
* @private
*/
Collection.prototype._rebuildIndexes = function () {
var arr = this._indexByName,
arrIndex;
// Remove from other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arr[arrIndex].rebuild();
}
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param {Object} query The query object to generate the subset with.
* @param {Object=} options An options object.
* @returns {*}
*/
Collection.prototype.subset = function (query, options) {
var result = this.find(query, options);
return new Collection()
.subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
};
/**
* Gets / sets the collection that this collection is a subset of.
* @param {Collection=} collection The collection to set as the parent of this subset.
* @returns {Collection}
*/
Shared.synthesize(Collection.prototype, 'subsetOf');
/**
* Checks if the collection is a subset of the passed collection.
* @param {Collection} collection The collection to test against.
* @returns {Boolean} True if the passed collection is the parent of
* the current collection.
*/
Collection.prototype.isSubsetOf = function (collection) {
return this._subsetOf === collection;
};
/**
* Find the distinct values for a specified field across a single collection and
* returns the results in an array.
* @param {String} key The field path to return distinct values for e.g. "person.name".
* @param {Object=} query The query to use to filter the documents used to return values from.
* @param {Object=} options The query options to use when running the query.
* @returns {Array}
*/
Collection.prototype.distinct = function (key, query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
var data = this.find(query, options),
pathSolver = new Path(key),
valueUsed = {},
distinctValues = [],
value,
i;
// Loop the data and build array of distinct values
for (i = 0; i < data.length; i++) {
value = pathSolver.value(data[i])[0];
if (value && !valueUsed[value]) {
valueUsed[value] = true;
distinctValues.push(value);
}
}
return distinctValues;
};
/**
* Helper method to find a document by it's id.
* @param {String} id The id of the document.
* @param {Object=} options The options object, allowed keys are sort and limit.
* @returns {Array} The items that were updated.
*/
Collection.prototype.findById = function (id, options) {
var searchObj = {};
searchObj[this._primaryKey] = id;
return this.find(searchObj, options)[0];
};
/**
* Finds all documents that contain the passed string or search object
* regardless of where the string might occur within the document. This
* will match strings from the start, middle or end of the document's
* string (partial match).
* @param search The string to search for. Case sensitive.
* @param options A standard find() options object.
* @returns {Array} An array of documents that matched the search string.
*/
Collection.prototype.peek = function (search, options) {
// Loop all items
var arr = this._data,
arrCount = arr.length,
arrIndex,
arrItem,
tempColl = new Collection(),
typeOfSearch = typeof search;
if (typeOfSearch === 'string') {
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Get json representation of object
arrItem = this.jStringify(arr[arrIndex]);
// Check if string exists in object json
if (arrItem.indexOf(search) > -1) {
// Add this item to the temp collection
tempColl.insert(arr[arrIndex]);
}
}
return tempColl.find({}, options);
} else {
return this.find(search, options);
}
};
/**
* Provides a query plan / operations log for a query.
* @param {Object} query The query to execute.
* @param {Object=} options Optional options object.
* @returns {Object} The query plan.
*/
Collection.prototype.explain = function (query, options) {
var result = this.find(query, options);
return result.__fdbOp._data;
};
/**
* Generates an options object with default values or adds default
* values to a passed object if those values are not currently set
* to anything.
* @param {object=} obj Optional options object to modify.
* @returns {object} The options object.
*/
Collection.prototype.options = function (obj) {
obj = obj || {};
obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true;
obj.$explain = obj.$explain !== undefined ? obj.$explain : false;
return obj;
};
/**
* Queries the collection based on the query object passed.
* @param {Object} query The query key/values that a document must match in
* order for it to be returned in the result array.
* @param {Object=} options An optional options object.
* @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !!
* Optional callback. If specified the find process
* will not return a value and will assume that you wish to operate under an
* async mode. This will break up large find requests into smaller chunks and
* process them in a non-blocking fashion allowing large datasets to be queried
* without causing the browser UI to pause. Results from this type of operation
* will be passed back to the callback once completed.
*
* @returns {Array} The results array from the find operation, containing all
* documents that matched the query.
*/
Collection.prototype.find = function (query, options, callback) {
// Convert queries from mongo dot notation to forerunner queries
if (this.mongoEmulation()) {
this.convertToFdb(query);
}
if (callback) {
// Check the size of the collection's data array
// Split operation into smaller tasks and callback when complete
callback('Callbacks for the find() operation are not yet implemented!', []);
return [];
}
return this._find.apply(this, arguments);
};
Collection.prototype._find = function (query, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
// TODO: This method is quite long, break into smaller pieces
query = query || {};
options = this.options(options);
var op = this._metrics.create('find'),
pk = this.primaryKey(),
self = this,
analysis,
scanLength,
requiresTableScan = true,
resultArr,
joinCollectionIndex,
joinIndex,
joinCollection = {},
joinQuery,
joinPath,
joinCollectionName,
joinCollectionInstance,
joinMatch,
joinMatchIndex,
joinSearchQuery,
joinSearchOptions,
joinMulti,
joinRequire,
joinFindResults,
joinFindResult,
joinItem,
joinPrefix,
resultCollectionName,
resultIndex,
resultRemove = [],
index,
i, j, k, l,
fieldListOn = [],
fieldListOff = [],
elemMatchPathSolver,
elemMatchSubArr,
elemMatchSpliceArr,
matcherTmpOptions = {},
result,
cursor = {},
//renameFieldMethod,
//renameFieldPath,
matcher = function (doc) {
return self._match(doc, query, options, 'and', matcherTmpOptions);
};
op.start();
if (query) {
// Get query analysis to execute best optimised code path
op.time('analyseQuery');
analysis = this._analyseQuery(self.decouple(query), options, op);
op.time('analyseQuery');
op.data('analysis', analysis);
if (analysis.hasJoin && analysis.queriesJoin) {
// The query has a join and tries to limit by it's joined data
// Get an instance reference to the join collections
op.time('joinReferences');
for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) {
joinCollectionName = analysis.joinsOn[joinIndex];
joinPath = new Path(analysis.joinQueries[joinCollectionName]);
joinQuery = joinPath.value(query)[0];
joinCollection[analysis.joinsOn[joinIndex]] = this._db.collection(analysis.joinsOn[joinIndex]).subset(joinQuery);
// Remove join clause from main query
delete query[analysis.joinQueries[joinCollectionName]];
}
op.time('joinReferences');
}
// Check if an index lookup can be used to return this result
if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) {
op.data('index.potential', analysis.indexMatch);
op.data('index.used', analysis.indexMatch[0].index);
// Get the data from the index
op.time('indexLookup');
resultArr = analysis.indexMatch[0].lookup || [];
op.time('indexLookup');
// Check if the index coverage is all keys, if not we still need to table scan it
if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) {
// Don't require a table scan to find relevant documents
requiresTableScan = false;
}
} else {
op.flag('usedIndex', false);
}
if (requiresTableScan) {
if (resultArr && resultArr.length) {
scanLength = resultArr.length;
op.time('tableScan: ' + scanLength);
// Filter the source data and return the result
resultArr = resultArr.filter(matcher);
} else {
// Filter the source data and return the result
scanLength = this._data.length;
op.time('tableScan: ' + scanLength);
resultArr = this._data.filter(matcher);
}
op.time('tableScan: ' + scanLength);
}
// Order the array if we were passed a sort clause
if (options.$orderBy) {
op.time('sort');
resultArr = this.sort(options.$orderBy, resultArr);
op.time('sort');
}
if (options.$page !== undefined && options.$limit !== undefined) {
// Record paging data
cursor.page = options.$page;
cursor.pages = Math.ceil(resultArr.length / options.$limit);
cursor.records = resultArr.length;
// Check if we actually need to apply the paging logic
if (options.$page && options.$limit > 0) {
op.data('cursor', cursor);
// Skip to the page specified based on limit
resultArr.splice(0, options.$page * options.$limit);
}
}
if (options.$skip) {
cursor.skip = options.$skip;
// Skip past the number of records specified
resultArr.splice(0, options.$skip);
op.data('skip', options.$skip);
}
if (options.$limit && resultArr && resultArr.length > options.$limit) {
cursor.limit = options.$limit;
resultArr.length = options.$limit;
op.data('limit', options.$limit);
}
if (options.$decouple) {
// Now decouple the data from the original objects
op.time('decouple');
resultArr = this.decouple(resultArr);
op.time('decouple');
op.data('flag.decouple', true);
}
// Now process any joins on the final data
if (options.$join) {
for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) {
for (joinCollectionName in options.$join[joinCollectionIndex]) {
if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) {
// Set the key to store the join result in to the collection name by default
resultCollectionName = joinCollectionName;
// Get the join collection instance from the DB
if (joinCollection[joinCollectionName]) {
joinCollectionInstance = joinCollection[joinCollectionName];
} else {
joinCollectionInstance = this._db.collection(joinCollectionName);
}
// Get the match data for the join
joinMatch = options.$join[joinCollectionIndex][joinCollectionName];
// Loop our result data array
for (resultIndex = 0; resultIndex < resultArr.length; resultIndex++) {
// Loop the join conditions and build a search object from them
joinSearchQuery = {};
joinMulti = false;
joinRequire = false;
joinPrefix = '';
for (joinMatchIndex in joinMatch) {
if (joinMatch.hasOwnProperty(joinMatchIndex)) {
// Check the join condition name for a special command operator
if (joinMatchIndex.substr(0, 1) === '$') {
// Special command
switch (joinMatchIndex) {
case '$where':
if (joinMatch[joinMatchIndex].query) { joinSearchQuery = joinMatch[joinMatchIndex].query; }
if (joinMatch[joinMatchIndex].options) { joinSearchOptions = joinMatch[joinMatchIndex].options; }
break;
case '$as':
// Rename the collection when stored in the result document
resultCollectionName = joinMatch[joinMatchIndex];
break;
case '$multi':
// Return an array of documents instead of a single matching document
joinMulti = joinMatch[joinMatchIndex];
break;
case '$require':
// Remove the result item if no matching join data is found
joinRequire = joinMatch[joinMatchIndex];
break;
case '$prefix':
// Add a prefix to properties mixed in
joinPrefix = joinMatch[joinMatchIndex];
break;
default:
break;
}
} else {
// Get the data to match against and store in the search object
// Resolve complex referenced query
joinSearchQuery[joinMatchIndex] = self._resolveDynamicQuery(joinMatch[joinMatchIndex], resultArr[resultIndex]);
}
}
}
// Do a find on the target collection against the match data
joinFindResults = joinCollectionInstance.find(joinSearchQuery, joinSearchOptions);
// Check if we require a joined row to allow the result item
if (!joinRequire || (joinRequire && joinFindResults[0])) {
// Join is not required or condition is met
if (resultCollectionName === '$root') {
// The property name to store the join results in is $root
// which means we need to mixin the results but this only
// works if joinMulti is disabled
if (joinMulti !== false) {
// Throw an exception here as this join is not physically possible!
throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$joinMulti: true] in $join clause!');
}
// Mixin the result
joinFindResult = joinFindResults[0];
joinItem = resultArr[resultIndex];
for (l in joinFindResult) {
if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) {
// Properties are only mixed in if they do not already exist
// in the target item (are undefined). Using a prefix denoted via
// $prefix is a good way to prevent property name conflicts
joinItem[joinPrefix + l] = joinFindResult[l];
}
}
} else {
resultArr[resultIndex][resultCollectionName] = joinMulti === false ? joinFindResults[0] : joinFindResults;
}
} else {
// Join required but condition not met, add item to removal queue
resultRemove.push(resultArr[resultIndex]);
}
}
}
}
}
op.data('flag.join', true);
}
// Process removal queue
if (resultRemove.length) {
op.time('removalQueue');
for (i = 0; i < resultRemove.length; i++) {
index = resultArr.indexOf(resultRemove[i]);
if (index > -1) {
resultArr.splice(index, 1);
}
}
op.time('removalQueue');
}
if (options.$transform) {
op.time('transform');
for (i = 0; i < resultArr.length; i++) {
resultArr.splice(i, 1, options.$transform(resultArr[i]));
}
op.time('transform');
op.data('flag.transform', true);
}
// Process transforms
if (this._transformEnabled && this._transformOut) {
op.time('transformOut');
resultArr = this.transformOut(resultArr);
op.time('transformOut');
}
op.data('results', resultArr.length);
} else {
resultArr = [];
}
// Check for an $as operator in the options object and if it exists
// iterate over the fields and generate a rename function that will
// operate over the entire returned data array and rename each object's
// fields to their new names
// TODO: Enable $as in collection find to allow renaming fields
/*if (options.$as) {
renameFieldPath = new Path();
renameFieldMethod = function (obj, oldFieldPath, newFieldName) {
renameFieldPath.path(oldFieldPath);
renameFieldPath.rename(newFieldName);
};
for (i in options.$as) {
if (options.$as.hasOwnProperty(i)) {
}
}
}*/
// Generate a list of fields to limit data by
// Each property starts off being enabled by default (= 1) then
// if any property is explicitly specified as 1 then all switch to
// zero except _id.
//
// Any that are explicitly set to zero are switched off.
op.time('scanFields');
for (i in options) {
if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) {
if (options[i] === 1) {
fieldListOn.push(i);
} else if (options[i] === 0) {
fieldListOff.push(i);
}
}
}
op.time('scanFields');
// Limit returned fields by the options data
if (fieldListOn.length || fieldListOff.length) {
op.data('flag.limitFields', true);
op.data('limitFields.on', fieldListOn);
op.data('limitFields.off', fieldListOff);
op.time('limitFields');
// We have explicit fields switched on or off
for (i = 0; i < resultArr.length; i++) {
result = resultArr[i];
for (j in result) {
if (result.hasOwnProperty(j)) {
if (fieldListOn.length) {
// We have explicit fields switched on so remove all fields
// that are not explicitly switched on
// Check if the field name is not the primary key
if (j !== pk) {
if (fieldListOn.indexOf(j) === -1) {
// This field is not in the on list, remove it
delete result[j];
}
}
}
if (fieldListOff.length) {
// We have explicit fields switched off so remove fields
// that are explicitly switched off
if (fieldListOff.indexOf(j) > -1) {
// This field is in the off list, remove it
delete result[j];
}
}
}
}
}
op.time('limitFields');
}
// Now run any projections on the data required
if (options.$elemMatch) {
op.data('flag.elemMatch', true);
op.time('projection-elemMatch');
for (i in options.$elemMatch) {
if (options.$elemMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) {
// The item matches the projection query so set the sub-array
// to an array that ONLY contains the matching item and then
// exit the loop since we only want to match the first item
elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]);
break;
}
}
}
}
}
}
op.time('projection-elemMatch');
}
if (options.$elemsMatch) {
op.data('flag.elemsMatch', true);
op.time('projection-elemsMatch');
for (i in options.$elemsMatch) {
if (options.$elemsMatch.hasOwnProperty(i)) {
elemMatchPathSolver = new Path(i);
// Loop the results array
for (j = 0; j < resultArr.length; j++) {
elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0];
// Check we have a sub-array to loop
if (elemMatchSubArr && elemMatchSubArr.length) {
elemMatchSpliceArr = [];
// Loop the sub-array and check for projection query matches
for (k = 0; k < elemMatchSubArr.length; k++) {
// Check if the current item in the sub-array matches the projection query
if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) {
// The item matches the projection query so add it to the final array
elemMatchSpliceArr.push(elemMatchSubArr[k]);
}
}
// Now set the final sub-array to the matched items
elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr);
}
}
}
}
op.time('projection-elemsMatch');
}
op.stop();
resultArr.__fdbOp = op;
resultArr.$cursor = cursor;
return resultArr;
};
Collection.prototype._resolveDynamicQuery = function (query, item) {
var self = this,
newQuery,
propType,
propVal,
i;
if (typeof query === 'string') {
// Check if the property name starts with a back-reference
if (query.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
return new Path(query.substr(3, query.length - 3)).value(item)[0];
}
return new Path(query).value(item)[0];
}
newQuery = {};
for (i in query) {
if (query.hasOwnProperty(i)) {
propType = typeof query[i];
propVal = query[i];
switch (propType) {
case 'string':
// Check if the property name starts with a back-reference
if (propVal.substr(0, 3) === '$$.') {
// Fill the query with a back-referenced value
newQuery[i] = new Path(propVal.substr(3, propVal.length - 3)).value(item)[0];
} else {
newQuery[i] = propVal;
}
break;
case 'object':
newQuery[i] = self._resolveDynamicQuery(propVal, item);
break;
default:
newQuery[i] = propVal;
break;
}
}
}
return newQuery;
};
/**
* Returns one document that satisfies the specified query criteria. If multiple
* documents satisfy the query, this method returns the first document to match
* the query.
* @returns {*}
*/
Collection.prototype.findOne = function () {
return (this.find.apply(this, arguments))[0];
};
/**
* Gets the index in the collection data array of the first item matched by
* the passed query object.
* @param {Object} query The query to run to find the item to return the index of.
* @param {Object=} options An options object.
* @returns {Number}
*/
Collection.prototype.indexOf = function (query, options) {
var item = this.find(query, {$decouple: false})[0],
sortedData;
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup from order of insert
return this._data.indexOf(item);
} else {
// Trying to locate index based on query with sort order
options.$decouple = false;
sortedData = this.find(query, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Returns the index of the document identified by the passed item's primary key.
* @param {*} itemLookup The document whose primary key should be used to lookup
* or the id to lookup.
* @param {Object=} options An options object.
* @returns {Number} The index the item with the matching primary key is occupying.
*/
Collection.prototype.indexOfDocById = function (itemLookup, options) {
var item,
sortedData;
if (typeof itemLookup !== 'object') {
item = this._primaryIndex.get(itemLookup);
} else {
item = this._primaryIndex.get(itemLookup[this._primaryKey]);
}
if (item) {
if (!options || options && !options.$orderBy) {
// Basic lookup
return this._data.indexOf(item);
} else {
// Sorted lookup
options.$decouple = false;
sortedData = this.find({}, options);
return sortedData.indexOf(item);
}
}
return -1;
};
/**
* Removes a document from the collection by it's index in the collection's
* data array.
* @param {Number} index The index of the document to remove.
* @returns {Object} The document that has been removed or false if none was
* removed.
*/
Collection.prototype.removeByIndex = function (index) {
var doc,
docId;
doc = this._data[index];
if (doc !== undefined) {
doc = this.decouple(doc);
docId = doc[this.primaryKey()];
return this.removeById(docId);
}
return false;
};
/**
* Gets / sets the collection transform options.
* @param {Object} obj A collection transform options object.
* @returns {*}
*/
Collection.prototype.transform = function (obj) {
if (obj !== undefined) {
if (typeof obj === "object") {
if (obj.enabled !== undefined) {
this._transformEnabled = obj.enabled;
}
if (obj.dataIn !== undefined) {
this._transformIn = obj.dataIn;
}
if (obj.dataOut !== undefined) {
this._transformOut = obj.dataOut;
}
} else {
this._transformEnabled = obj !== false;
}
return this;
}
return {
enabled: this._transformEnabled,
dataIn: this._transformIn,
dataOut: this._transformOut
};
};
/**
* Transforms data using the set transformIn method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformIn = function (data) {
if (this._transformEnabled && this._transformIn) {
if (data instanceof Array) {
var finalArr = [], i;
for (i = 0; i < data.length; i++) {
finalArr[i] = this._transformIn(data[i]);
}
return finalArr;
} else {
return this._transformIn(data);
}
}
return data;
};
/**
* Transforms data using the set transformOut method.
* @param {Object} data The data to transform.
* @returns {*}
*/
Collection.prototype.transformOut = function (data) {
if (this._transformEnabled && this._transformOut) {
if (data instanceof Array) {
var finalArr = [], i;
for (i = 0; i < data.length; i++) {
finalArr[i] = this._transformOut(data[i]);
}
return finalArr;
} else {
return this._transformOut(data);
}
}
return data;
};
/**
* Sorts an array of documents by the given sort path.
* @param {*} sortObj The keys and orders the array objects should be sorted by.
* @param {Array} arr The array of documents to sort.
* @returns {Array}
*/
Collection.prototype.sort = function (sortObj, arr) {
// Make sure we have an array object
arr = arr || [];
var sortArr = [],
sortKey,
sortSingleObj;
for (sortKey in sortObj) {
if (sortObj.hasOwnProperty(sortKey)) {
sortSingleObj = {};
sortSingleObj[sortKey] = sortObj[sortKey];
sortSingleObj.___fdbKey = String(sortKey);
sortArr.push(sortSingleObj);
}
}
if (sortArr.length < 2) {
// There is only one sort criteria, do a simple sort and return it
return this._sort(sortObj, arr);
} else {
return this._bucketSort(sortArr, arr);
}
};
/**
* Takes array of sort paths and sorts them into buckets before returning final
* array fully sorted by multi-keys.
* @param keyArr
* @param arr
* @returns {*}
* @private
*/
Collection.prototype._bucketSort = function (keyArr, arr) {
var keyObj = keyArr.shift(),
arrCopy,
bucketData,
bucketOrder,
bucketKey,
buckets,
i,
finalArr = [];
if (keyArr.length > 0) {
// Sort array by bucket key
arr = this._sort(keyObj, arr);
// Split items into buckets
bucketData = this.bucket(keyObj.___fdbKey, arr);
bucketOrder = bucketData.order;
buckets = bucketData.buckets;
// Loop buckets and sort contents
for (i = 0; i < bucketOrder.length; i++) {
bucketKey = bucketOrder[i];
arrCopy = [].concat(keyArr);
finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey]));
}
return finalArr;
} else {
return this._sort(keyObj, arr);
}
};
/**
* Sorts array by individual sort path.
* @param key
* @param arr
* @returns {Array|*}
* @private
*/
Collection.prototype._sort = function (key, arr) {
var self = this,
sorterMethod,
pathSolver = new Path(),
dataPath = pathSolver.parse(key, true)[0];
pathSolver.path(dataPath.path);
if (dataPath.value === 1) {
// Sort ascending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortAsc(valA, valB);
};
} else if (dataPath.value === -1) {
// Sort descending
sorterMethod = function (a, b) {
var valA = pathSolver.value(a)[0],
valB = pathSolver.value(b)[0];
return self.sortDesc(valA, valB);
};
} else {
throw(this.logIdentifier() + ' $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!');
}
return arr.sort(sorterMethod);
};
/**
* Takes an array of objects and returns a new object with the array items
* split into buckets by the passed key.
* @param {String} key The key to split the array into buckets by.
* @param {Array} arr An array of objects.
* @returns {Object}
*/
Collection.prototype.bucket = function (key, arr) {
var i,
oldField,
field,
fieldArr = [],
buckets = {};
for (i = 0; i < arr.length; i++) {
field = String(arr[i][key]);
if (oldField !== field) {
fieldArr.push(field);
oldField = field;
}
buckets[field] = buckets[field] || [];
buckets[field].push(arr[i]);
}
return {
buckets: buckets,
order: fieldArr
};
};
/**
* Internal method that takes a search query and options and returns an object
* containing details about the query which can be used to optimise the search.
*
* @param query
* @param options
* @param op
* @returns {Object}
* @private
*/
Collection.prototype._analyseQuery = function (query, options, op) {
var analysis = {
queriesOn: [this._name],
indexMatch: [],
hasJoin: false,
queriesJoin: false,
joinQueries: {},
query: query,
options: options
},
joinCollectionIndex,
joinCollectionName,
joinCollections = [],
joinCollectionReferences = [],
queryPath,
index,
indexMatchData,
indexRef,
indexRefName,
indexLookup,
pathSolver,
queryKeyCount,
i;
// Check if the query is a primary key lookup
op.time('checkIndexes');
pathSolver = new Path();
queryKeyCount = pathSolver.countKeys(query);
if (queryKeyCount) {
if (query[this._primaryKey] !== undefined) {
// Return item via primary key possible
op.time('checkIndexMatch: Primary Key');
analysis.indexMatch.push({
lookup: this._primaryIndex.lookup(query, options),
keyData: {
matchedKeys: [this._primaryKey],
totalKeyCount: queryKeyCount,
score: 1
},
index: this._primaryIndex
});
op.time('checkIndexMatch: Primary Key');
}
// Check if an index can speed up the query
for (i in this._indexById) {
if (this._indexById.hasOwnProperty(i)) {
indexRef = this._indexById[i];
indexRefName = indexRef.name();
op.time('checkIndexMatch: ' + indexRefName);
indexMatchData = indexRef.match(query, options);
if (indexMatchData.score > 0) {
// This index can be used, store it
indexLookup = indexRef.lookup(query, options);
analysis.indexMatch.push({
lookup: indexLookup,
keyData: indexMatchData,
index: indexRef
});
}
op.time('checkIndexMatch: ' + indexRefName);
if (indexMatchData.score === queryKeyCount) {
// Found an optimal index, do not check for any more
break;
}
}
}
op.time('checkIndexes');
// Sort array descending on index key count (effectively a measure of relevance to the query)
if (analysis.indexMatch.length > 1) {
op.time('findOptimalIndex');
analysis.indexMatch.sort(function (a, b) {
if (a.keyData.score > b.keyData.score) {
// This index has a higher score than the other
return -1;
}
if (a.keyData.score < b.keyData.score) {
// This index has a lower score than the other
return 1;
}
// The indexes have the same score but can still be compared by the number of records
// they return from the query. The fewer records they return the better so order by
// record count
if (a.keyData.score === b.keyData.score) {
return a.lookup.length - b.lookup.length;
}
});
op.time('findOptimalIndex');
}
}
// Check for join data
if (options.$join) {
analysis.hasJoin = true;
// Loop all join operations
for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) {
// Loop the join collections and keep a reference to them
for (joinCollectionName in options.$join[joinCollectionIndex]) {
if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) {
joinCollections.push(joinCollectionName);
// Check if the join uses an $as operator
if ('$as' in options.$join[joinCollectionIndex][joinCollectionName]) {
joinCollectionReferences.push(options.$join[joinCollectionIndex][joinCollectionName].$as);
} else {
joinCollectionReferences.push(joinCollectionName);
}
}
}
}
// Loop the join collection references and determine if the query references
// any of the collections that are used in the join. If there no queries against
// joined collections the find method can use a code path optimised for this.
// Queries against joined collections requires the joined collections to be filtered
// first and then joined so requires a little more work.
for (index = 0; index < joinCollectionReferences.length; index++) {
// Check if the query references any collection data that the join will create
queryPath = this._queryReferencesCollection(query, joinCollectionReferences[index], '');
if (queryPath) {
analysis.joinQueries[joinCollections[index]] = queryPath;
analysis.queriesJoin = true;
}
}
analysis.joinsOn = joinCollections;
analysis.queriesOn = analysis.queriesOn.concat(joinCollections);
}
return analysis;
};
/**
* Checks if the passed query references this collection.
* @param query
* @param collection
* @param path
* @returns {*}
* @private
*/
Collection.prototype._queryReferencesCollection = function (query, collection, path) {
var i;
for (i in query) {
if (query.hasOwnProperty(i)) {
// Check if this key is a reference match
if (i === collection) {
if (path) { path += '.'; }
return path + i;
} else {
if (typeof(query[i]) === 'object') {
// Recurse
if (path) { path += '.'; }
path += i;
return this._queryReferencesCollection(query[i], collection, path);
}
}
}
}
return false;
};
/**
* Returns the number of documents currently in the collection.
* @returns {Number}
*/
Collection.prototype.count = function (query, options) {
if (!query) {
return this._data.length;
} else {
// Run query and return count
return this.find(query, options).length;
}
};
/**
* Finds sub-documents from the collection's documents.
* @param {Object} match The query object to use when matching parent documents
* from which the sub-documents are queried.
* @param {String} path The path string used to identify the key in which
* sub-documents are stored in parent documents.
* @param {Object=} subDocQuery The query to use when matching which sub-documents
* to return.
* @param {Object=} subDocOptions The options object to use when querying for
* sub-documents.
* @returns {*}
*/
Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) {
var pathHandler = new Path(path),
docArr = this.find(match),
docCount = docArr.length,
docIndex,
subDocArr,
subDocCollection = this._db.collection('__FDB_temp_' + this.objectId()),
subDocResults,
resultObj = {
parents: docCount,
subDocTotal: 0,
subDocs: [],
pathFound: false,
err: ''
};
subDocOptions = subDocOptions || {};
for (docIndex = 0; docIndex < docCount; docIndex++) {
subDocArr = pathHandler.value(docArr[docIndex])[0];
if (subDocArr) {
subDocCollection.setData(subDocArr);
subDocResults = subDocCollection.find(subDocQuery, subDocOptions);
if (subDocOptions.returnFirst && subDocResults.length) {
return subDocResults[0];
}
if (subDocOptions.$split) {
resultObj.subDocs.push(subDocResults);
} else {
resultObj.subDocs = resultObj.subDocs.concat(subDocResults);
}
resultObj.subDocTotal += subDocResults.length;
resultObj.pathFound = true;
}
}
// Drop the sub-document collection
subDocCollection.drop();
// Check if the call should not return stats, if so return only subDocs array
if (subDocOptions.$stats) {
return resultObj;
} else {
return resultObj.subDocs;
}
if (!resultObj.pathFound) {
resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path;
}
return resultObj;
};
/**
* Checks that the passed document will not violate any index rules if
* inserted into the collection.
* @param {Object} doc The document to check indexes against.
* @returns {Boolean} Either false (no violation occurred) or true if
* a violation was detected.
*/
Collection.prototype.insertIndexViolation = function (doc) {
var indexViolated,
arr = this._indexByName,
arrIndex,
arrItem;
// Check the item's primary key is not already in use
if (this._primaryIndex.get(doc[this._primaryKey])) {
indexViolated = this._primaryIndex;
} else {
// Check violations of other indexes
for (arrIndex in arr) {
if (arr.hasOwnProperty(arrIndex)) {
arrItem = arr[arrIndex];
if (arrItem.unique()) {
if (arrItem.violation(doc)) {
indexViolated = arrItem;
break;
}
}
}
}
}
return indexViolated ? indexViolated.name() : false;
};
/**
* Creates an index on the specified keys.
* @param {Object} keys The object containing keys to index.
* @param {Object} options An options object.
* @returns {*}
*/
Collection.prototype.ensureIndex = function (keys, options) {
if (this.isDropped()) {
throw(this.logIdentifier() + ' Cannot operate in a dropped state!');
}
this._indexByName = this._indexByName || {};
this._indexById = this._indexById || {};
var index,
time = {
start: new Date().getTime()
};
if (options) {
switch (options.type) {
case 'hashed':
index = new IndexHashMap(keys, options, this);
break;
case 'btree':
index = new IndexBinaryTree(keys, options, this);
break;
default:
// Default
index = new IndexHashMap(keys, options, this);
break;
}
} else {
// Default
index = new IndexHashMap(keys, options, this);
}
// Check the index does not already exist
if (this._indexByName[index.name()]) {
// Index already exists
return {
err: 'Index with that name already exists'
};
}
if (this._indexById[index.id()]) {
// Index already exists
return {
err: 'Index with those keys already exists'
};
}
// Create the index
index.rebuild();
// Add the index
this._indexByName[index.name()] = index;
this._indexById[index.id()] = index;
time.end = new Date().getTime();
time.total = time.end - time.start;
this._lastOp = {
type: 'ensureIndex',
stats: {
time: time
}
};
return {
index: index,
id: index.id(),
name: index.name(),
state: index.state()
};
};
/**
* Gets an index by it's name.
* @param {String} name The name of the index to retreive.
* @returns {*}
*/
Collection.prototype.index = function (name) {
if (this._indexByName) {
return this._indexByName[name];
}
};
/**
* Gets the last reporting operation's details such as run time.
* @returns {Object}
*/
Collection.prototype.lastOp = function () {
return this._metrics.list();
};
/**
* Generates a difference object that contains insert, update and remove arrays
* representing the operations to execute to make this collection have the same
* data as the one passed.
* @param {Collection} collection The collection to diff against.
* @returns {{}}
*/
Collection.prototype.diff = function (collection) {
var diff = {
insert: [],
update: [],
remove: []
};
var pm = this.primaryKey(),
arr,
arrIndex,
arrItem,
arrCount;
// Check if the primary key index of each collection can be utilised
if (pm !== collection.primaryKey()) {
throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!');
}
// Use the collection primary key index to do the diff (super-fast)
arr = collection._data;
// Check if we have an array or another collection
while (arr && !(arr instanceof Array)) {
// We don't have an array, assign collection and get data
collection = arr;
arr = collection._data;
}
arrCount = arr.length;
// Loop the collection's data array and check for matching items
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
// Check for a matching item in this collection
if (this._primaryIndex.get(arrItem[pm])) {
// Matching item exists, check if the data is the same
if (this._primaryCrc.get(arrItem[pm]) !== collection._primaryCrc.get(arrItem[pm])) {
// The documents exist in both collections but data differs, update required
diff.update.push(arrItem);
}
} else {
// The document is missing from this collection, insert required
diff.insert.push(arrItem);
}
}
// Now loop this collection's data and check for matching items
arr = this._data;
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = arr[arrIndex];
if (!collection._primaryIndex.get(arrItem[pm])) {
// The document does not exist in the other collection, remove required
diff.remove.push(arrItem);
}
}
return diff;
};
Collection.prototype.collateAdd = new Overload({
/**
* Adds a data source to collate data from and specifies the
* key name to collate data to.
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {String=} keyName Optional name of the key to collate data to.
* If none is provided the record CRUD is operated on the root collection
* data.
*/
'object, string': function (collection, keyName) {
var self = this;
self.collateAdd(collection, function (packet) {
var obj1,
obj2;
switch (packet.type) {
case 'insert':
if (keyName) {
obj1 = {
$push: {}
};
obj1.$push[keyName] = self.decouple(packet.data);
self.update({}, obj1);
} else {
self.insert(packet.data);
}
break;
case 'update':
if (keyName) {
obj1 = {};
obj2 = {};
obj1[keyName] = packet.data.query;
obj2[keyName + '.$'] = packet.data.update;
self.update(obj1, obj2);
} else {
self.update(packet.data.query, packet.data.update);
}
break;
case 'remove':
if (keyName) {
obj1 = {
$pull: {}
};
obj1.$pull[keyName] = {};
obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()];
self.update({}, obj1);
} else {
self.remove(packet.data);
}
break;
default:
}
});
},
/**
* Adds a data source to collate data from and specifies a process
* method that will handle the collation functionality (for custom
* collation).
* @func collateAdd
* @memberof Collection
* @param {Collection} collection The collection to collate data from.
* @param {Function} process The process method.
*/
'object, function': function (collection, process) {
if (typeof collection === 'string') {
// The collection passed is a name, not a reference so get
// the reference from the name
collection = this._db.collection(collection, {
autoCreate: false,
throwError: false
});
}
if (collection) {
this._collate = this._collate || {};
this._collate[collection.name()] = new ReactorIO(collection, this, process);
return this;
} else {
throw('Cannot collate from a non-existent collection!');
}
}
});
Collection.prototype.collateRemove = function (collection) {
if (typeof collection === 'object') {
// We need to have the name of the collection to remove it
collection = collection.name();
}
if (collection) {
// Drop the reactor IO chain node
this._collate[collection].drop();
// Remove the collection data from the collate object
delete this._collate[collection];
return this;
} else {
throw('No collection name passed to collateRemove() or collection not found!');
}
};
Db.prototype.collection = new Overload({
/**
* Get a collection with no name (generates a random name). If the
* collection does not already exist then one is created for that
* name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @returns {Collection}
*/
'': function () {
return this.$main.call(this, {
name: this.objectId()
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {Object} data An options object or a collection instance.
* @returns {Collection}
*/
'object': function (data) {
// Handle being passed an instance
if (data instanceof Collection) {
if (data.state() !== 'droppped') {
return data;
} else {
return this.$main.call(this, {
name: data.name()
});
}
}
return this.$main.call(this, data);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @returns {Collection}
*/
'string': function (collectionName) {
return this.$main.call(this, {
name: collectionName
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @returns {Collection}
*/
'string, string': function (collectionName, primaryKey) {
return this.$main.call(this, {
name: collectionName,
primaryKey: primaryKey
});
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, object': function (collectionName, options) {
options.name = collectionName;
return this.$main.call(this, options);
},
/**
* Get a collection by name. If the collection does not already exist
* then one is created for that name automatically.
* @func collection
* @memberof Db
* @param {String} collectionName The name of the collection.
* @param {String} primaryKey Optional primary key to specify the primary key field on the collection
* objects. Defaults to "_id".
* @param {Object} options An options object.
* @returns {Collection}
*/
'string, string, object': function (collectionName, primaryKey, options) {
options.name = collectionName;
options.primaryKey = primaryKey;
return this.$main.call(this, options);
},
/**
* The main handler method. This gets called by all the other variants and
* handles the actual logic of the overloaded method.
* @func collection
* @memberof Db
* @param {Object} options An options object.
* @returns {*}
*/
'$main': function (options) {
var name = options.name;
if (name) {
if (!this._collection[name]) {
if (options && options.autoCreate === false) {
if (options && options.throwError !== false) {
throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!');
}
}
if (this.debug()) {
console.log(this.logIdentifier() + ' Creating collection ' + name);
}
}
this._collection[name] = this._collection[name] || new Collection(name, options).db(this);
this._collection[name].mongoEmulation(this.mongoEmulation());
if (options.primaryKey !== undefined) {
this._collection[name].primaryKey(options.primaryKey);
}
return this._collection[name];
} else {
if (!options || (options && options.throwError !== false)) {
throw(this.logIdentifier() + ' Cannot get collection with undefined name!');
}
}
}
});
/**
* Determine if a collection with the passed name already exists.
* @memberof Db
* @param {String} viewName The name of the collection to check for.
* @returns {boolean}
*/
Db.prototype.collectionExists = function (viewName) {
return Boolean(this._collection[viewName]);
};
/**
* Returns an array of collections the DB currently has.
* @memberof Db
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each collection
* the database is currently managing.
*/
Db.prototype.collections = function (search) {
var arr = [],
collections = this._collection,
collection,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in collections) {
if (collections.hasOwnProperty(i)) {
collection = collections[i];
if (search) {
if (search.exec(i)) {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
} else {
arr.push({
name: i,
count: collection.count(),
linked: collection.isLinked !== undefined ? collection.isLinked() : false
});
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Collection');
module.exports = Collection;
},{"./Crc":7,"./IndexBinaryTree":12,"./IndexHashMap":13,"./KeyValueStore":14,"./Metrics":15,"./Overload":29,"./Path":31,"./ReactorIO":35,"./Shared":37}],5:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
DbInit,
Collection;
Shared = _dereq_('./Shared');
/**
* Creates a new collection group. Collection groups allow single operations to be
* propagated to multiple collections at once. CRUD operations against a collection
* group are in fed to the group's collections. Useful when separating out slightly
* different data into multiple collections but querying as one collection.
* @constructor
*/
var CollectionGroup = function () {
this.init.apply(this, arguments);
};
CollectionGroup.prototype.init = function (name) {
var self = this;
self._name = name;
self._data = new Collection('__FDB__cg_data_' + self._name);
self._collections = [];
self._view = [];
};
Shared.addModule('CollectionGroup', CollectionGroup);
Shared.mixin(CollectionGroup.prototype, 'Mixin.Common');
Shared.mixin(CollectionGroup.prototype, 'Mixin.ChainReactor');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Constants');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Triggers');
Shared.mixin(CollectionGroup.prototype, 'Mixin.Tags');
Collection = _dereq_('./Collection');
Db = Shared.modules.Db;
DbInit = Shared.modules.Db.prototype.init;
CollectionGroup.prototype.on = function () {
this._data.on.apply(this._data, arguments);
};
CollectionGroup.prototype.off = function () {
this._data.off.apply(this._data, arguments);
};
CollectionGroup.prototype.emit = function () {
this._data.emit.apply(this._data, arguments);
};
/**
* Gets / sets the primary key for this collection group.
* @param {String=} keyName The name of the primary key.
* @returns {*}
*/
CollectionGroup.prototype.primaryKey = function (keyName) {
if (keyName !== undefined) {
this._primaryKey = keyName;
return this;
}
return this._primaryKey;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'state');
/**
* Gets / sets the db instance the collection group belongs to.
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'db');
/**
* Gets / sets the instance name.
* @param {Name=} name The new name to set.
* @returns {*}
*/
Shared.synthesize(CollectionGroup.prototype, 'name');
CollectionGroup.prototype.addCollection = function (collection) {
if (collection) {
if (this._collections.indexOf(collection) === -1) {
//var self = this;
// Check for compatible primary keys
if (this._collections.length) {
if (this._primaryKey !== collection.primaryKey()) {
throw(this.logIdentifier() + ' All collections in a collection group must have the same primary key!');
}
} else {
// Set the primary key to the first collection added
this.primaryKey(collection.primaryKey());
}
// Add the collection
this._collections.push(collection);
collection._groups = collection._groups || [];
collection._groups.push(this);
collection.chain(this);
// Hook the collection's drop event to destroy group data
collection.on('drop', function () {
// Remove collection from any group associations
if (collection._groups && collection._groups.length) {
var groupArr = [],
i;
// Copy the group array because if we call removeCollection on a group
// it will alter the groups array of this collection mid-loop!
for (i = 0; i < collection._groups.length; i++) {
groupArr.push(collection._groups[i]);
}
// Loop any groups we are part of and remove ourselves from them
for (i = 0; i < groupArr.length; i++) {
collection._groups[i].removeCollection(collection);
}
}
delete collection._groups;
});
// Add collection's data
this._data.insert(collection.find());
}
}
return this;
};
CollectionGroup.prototype.removeCollection = function (collection) {
if (collection) {
var collectionIndex = this._collections.indexOf(collection),
groupIndex;
if (collectionIndex !== -1) {
collection.unChain(this);
this._collections.splice(collectionIndex, 1);
collection._groups = collection._groups || [];
groupIndex = collection._groups.indexOf(this);
if (groupIndex !== -1) {
collection._groups.splice(groupIndex, 1);
}
collection.off('drop');
}
if (this._collections.length === 0) {
// Wipe the primary key
delete this._primaryKey;
}
}
return this;
};
CollectionGroup.prototype._chainHandler = function (chainPacket) {
//sender = chainPacket.sender;
switch (chainPacket.type) {
case 'setData':
// Decouple the data to ensure we are working with our own copy
chainPacket.data = this.decouple(chainPacket.data);
// Remove old data
this._data.remove(chainPacket.options.oldData);
// Add new data
this._data.insert(chainPacket.data);
break;
case 'insert':
// Decouple the data to ensure we are working with our own copy
chainPacket.data = this.decouple(chainPacket.data);
// Add new data
this._data.insert(chainPacket.data);
break;
case 'update':
// Update data
this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options);
break;
case 'remove':
this._data.remove(chainPacket.data.query, chainPacket.options);
break;
default:
break;
}
};
CollectionGroup.prototype.insert = function () {
this._collectionsRun('insert', arguments);
};
CollectionGroup.prototype.update = function () {
this._collectionsRun('update', arguments);
};
CollectionGroup.prototype.updateById = function () {
this._collectionsRun('updateById', arguments);
};
CollectionGroup.prototype.remove = function () {
this._collectionsRun('remove', arguments);
};
CollectionGroup.prototype._collectionsRun = function (type, args) {
for (var i = 0; i < this._collections.length; i++) {
this._collections[i][type].apply(this._collections[i], args);
}
};
CollectionGroup.prototype.find = function (query, options) {
return this._data.find(query, options);
};
/**
* Helper method that removes a document that matches the given id.
* @param {String} id The id of the document to remove.
*/
CollectionGroup.prototype.removeById = function (id) {
// Loop the collections in this group and apply the remove
for (var i = 0; i < this._collections.length; i++) {
this._collections[i].removeById(id);
}
};
/**
* Uses the passed query to generate a new collection with results
* matching the query parameters.
*
* @param query
* @param options
* @returns {*}
*/
CollectionGroup.prototype.subset = function (query, options) {
var result = this.find(query, options);
return new Collection()
.subsetOf(this)
.primaryKey(this._primaryKey)
.setData(result);
};
/**
* Drops a collection group from the database.
* @returns {boolean} True on success, false on failure.
*/
CollectionGroup.prototype.drop = function (callback) {
if (!this.isDropped()) {
var i,
collArr,
viewArr;
if (this._debug) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
if (this._collections && this._collections.length) {
collArr = [].concat(this._collections);
for (i = 0; i < collArr.length; i++) {
this.removeCollection(collArr[i]);
}
}
if (this._view && this._view.length) {
viewArr = [].concat(this._view);
for (i = 0; i < viewArr.length; i++) {
this._removeView(viewArr[i]);
}
}
this.emit('drop', this);
if (callback) { callback(false, true); }
}
return true;
};
// Extend DB to include collection groups
Db.prototype.init = function () {
this._collectionGroup = {};
DbInit.apply(this, arguments);
};
Db.prototype.collectionGroup = function (collectionGroupName) {
if (collectionGroupName) {
// Handle being passed an instance
if (collectionGroupName instanceof CollectionGroup) {
return collectionGroupName;
}
this._collectionGroup[collectionGroupName] = this._collectionGroup[collectionGroupName] || new CollectionGroup(collectionGroupName).db(this);
return this._collectionGroup[collectionGroupName];
} else {
// Return an object of collection data
return this._collectionGroup;
}
};
/**
* Returns an array of collection groups the DB currently has.
* @returns {Array} An array of objects containing details of each collection group
* the database is currently managing.
*/
Db.prototype.collectionGroups = function () {
var arr = [],
i;
for (i in this._collectionGroup) {
if (this._collectionGroup.hasOwnProperty(i)) {
arr.push({
name: i
});
}
}
return arr;
};
module.exports = CollectionGroup;
},{"./Collection":4,"./Shared":37}],6:[function(_dereq_,module,exports){
/*
License
Copyright (c) 2015 Irrelon Software Limited
http://www.irrelon.com
http://www.forerunnerdb.com
Please visit the license page to see latest license information:
http://www.forerunnerdb.com/licensing.html
*/
"use strict";
var Shared,
Db,
Metrics,
Overload,
_instances = [];
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB instance. Core instances handle the lifecycle of
* multiple database instances.
* @constructor
*/
var Core = function (name) {
this.init.apply(this, arguments);
};
Core.prototype.init = function (name) {
this._db = {};
this._debug = {};
this._name = name || 'ForerunnerDB';
_instances.push(this);
};
/**
* Returns the number of instantiated ForerunnerDB objects.
* @returns {Number} The number of instantiated instances.
*/
Core.prototype.instantiatedCount = function () {
return _instances.length;
};
/**
* Get all instances as an array or a single ForerunnerDB instance
* by it's array index.
* @param {Number=} index Optional index of instance to get.
* @returns {Array|Object} Array of instances or a single instance.
*/
Core.prototype.instances = function (index) {
if (index !== undefined) {
return _instances[index];
}
return _instances;
};
/**
* Get all instances as an array of instance names or a single ForerunnerDB
* instance by it's name.
* @param {String=} name Optional name of instance to get.
* @returns {Array|Object} Array of instance names or a single instance.
*/
Core.prototype.namedInstances = function (name) {
var i,
instArr;
if (name !== undefined) {
for (i = 0; i < _instances.length; i++) {
if (_instances[i].name === name) {
return _instances[i];
}
}
return undefined;
}
instArr = [];
for (i = 0; i < _instances.length; i++) {
instArr.push(_instances[i].name);
}
return instArr;
};
Core.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
if (callback) { callback(); }
}
},
/**
* Checks if an array of named modules are loaded and if so
* calls the passed callback method.
* @func moduleLoaded
* @memberof Core
* @param {Array} moduleName The array of module names to check for.
* @param {Function} callback The callback method to call if modules are loaded.
*/
'array, function': function (moduleNameArr, callback) {
var moduleName,
i;
for (i = 0; i < moduleNameArr.length; i++) {
moduleName = moduleNameArr[i];
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
}
}
if (callback) { callback(); }
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Core
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Core.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded() method to non-instantiated object ForerunnerDB
Core.moduleLoaded = Core.prototype.moduleLoaded;
// Expose version() method to non-instantiated object ForerunnerDB
Core.version = Core.prototype.version;
// Expose instances() method to non-instantiated object ForerunnerDB
Core.instances = Core.prototype.instances;
// Expose instantiatedCount() method to non-instantiated object ForerunnerDB
Core.instantiatedCount = Core.prototype.instantiatedCount;
// Provide public access to the Shared object
Core.shared = Shared;
Core.prototype.shared = Shared;
Shared.addModule('Core', Core);
Shared.mixin(Core.prototype, 'Mixin.Common');
Shared.mixin(Core.prototype, 'Mixin.Constants');
Db = _dereq_('./Db.js');
Metrics = _dereq_('./Metrics.js');
/**
* Gets / sets the name of the instance. This is primarily used for
* name-spacing persistent storage.
* @param {String=} val The name of the instance to set.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Core.prototype, 'mongoEmulation');
// Set a flag to determine environment
Core.prototype._isServer = false;
/**
* Returns true if ForerunnerDB is running on a client browser.
* @returns {boolean}
*/
Core.prototype.isClient = function () {
return !this._isServer;
};
/**
* Returns true if ForerunnerDB is running on a server.
* @returns {boolean}
*/
Core.prototype.isServer = function () {
return this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Core.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Core.prototype.isServer = function () {
return this._isServer;
};
/**
* Added to provide an error message for users who have not seen
* the new instantiation breaking change warning and try to get
* a collection directly from the core instance.
*/
Core.prototype.collection = function () {
throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44");
};
module.exports = Core;
},{"./Db.js":8,"./Metrics.js":15,"./Overload":29,"./Shared":37}],7:[function(_dereq_,module,exports){
"use strict";
/**
* @mixin
*/
var crcTable = (function () {
var crcTable = [],
c, n, k;
for (n = 0; n < 256; n++) {
c = n;
for (k = 0; k < 8; k++) {
c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line
}
crcTable[n] = c;
}
return crcTable;
}());
module.exports = function(str) {
var crc = 0 ^ (-1), // jshint ignore:line
i;
for (i = 0; i < str.length; i++) {
crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line
}
return (crc ^ (-1)) >>> 0; // jshint ignore:line
};
},{}],8:[function(_dereq_,module,exports){
"use strict";
var Shared,
Core,
Collection,
Metrics,
Crc,
Overload;
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* Creates a new ForerunnerDB database instance.
* @constructor
*/
var Db = function (name, core) {
this.init.apply(this, arguments);
};
Db.prototype.init = function (name, core) {
this.core(core);
this._primaryKey = '_id';
this._name = name;
this._collection = {};
this._debug = {};
};
Shared.addModule('Db', Db);
Db.prototype.moduleLoaded = new Overload({
/**
* Checks if a module has been loaded into the database.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @returns {Boolean} True if the module is loaded, false if not.
*/
'string': function (moduleName) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
return true;
}
return false;
},
/**
* Checks if a module is loaded and if so calls the passed
* callback method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} callback The callback method to call if module is loaded.
*/
'string, function': function (moduleName, callback) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
return false;
}
}
if (callback) { callback(); }
}
},
/**
* Checks if a module is loaded and if so calls the passed
* success method, otherwise calls the failure method.
* @func moduleLoaded
* @memberof Db
* @param {String} moduleName The name of the module to check for.
* @param {Function} success The callback method to call if module is loaded.
* @param {Function} failure The callback method to call if module not loaded.
*/
'string, function, function': function (moduleName, success, failure) {
if (moduleName !== undefined) {
moduleName = moduleName.replace(/ /g, '');
var modules = moduleName.split(','),
index;
for (index = 0; index < modules.length; index++) {
if (!Shared.modules[modules[index]]) {
failure();
return false;
}
}
success();
}
}
});
/**
* Checks version against the string passed and if it matches (or partially matches)
* then the callback is called.
* @param {String} val The version to check against.
* @param {Function} callback The callback to call if match is true.
* @returns {Boolean}
*/
Db.prototype.version = function (val, callback) {
if (val !== undefined) {
if (Shared.version.indexOf(val) === 0) {
if (callback) { callback(); }
return true;
}
return false;
}
return Shared.version;
};
// Expose moduleLoaded method to non-instantiated object ForerunnerDB
Db.moduleLoaded = Db.prototype.moduleLoaded;
// Expose version method to non-instantiated object ForerunnerDB
Db.version = Db.prototype.version;
// Provide public access to the Shared object
Db.shared = Shared;
Db.prototype.shared = Shared;
Shared.addModule('Db', Db);
Shared.mixin(Db.prototype, 'Mixin.Common');
Shared.mixin(Db.prototype, 'Mixin.ChainReactor');
Shared.mixin(Db.prototype, 'Mixin.Constants');
Shared.mixin(Db.prototype, 'Mixin.Tags');
Core = Shared.modules.Core;
Collection = _dereq_('./Collection.js');
Metrics = _dereq_('./Metrics.js');
Crc = _dereq_('./Crc.js');
Db.prototype._isServer = false;
/**
* Gets / sets the core object this database belongs to.
*/
Shared.synthesize(Db.prototype, 'core');
/**
* Gets / sets the default primary key for new collections.
* @param {String=} val The name of the primary key to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'primaryKey');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'state');
/**
* Gets / sets the name of the database.
* @param {String=} val The name of the database to set.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'name');
/**
* Gets / sets mongodb emulation mode.
* @param {Boolean=} val True to enable, false to disable.
* @returns {*}
*/
Shared.synthesize(Db.prototype, 'mongoEmulation');
/**
* Returns true if ForerunnerDB is running on a client browser.
* @returns {boolean}
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Returns true if ForerunnerDB is running on a server.
* @returns {boolean}
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Returns a checksum of a string.
* @param {String} string The string to checksum.
* @return {String} The checksum generated.
*/
Db.prototype.crc = Crc;
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a browser.
*/
Db.prototype.isClient = function () {
return !this._isServer;
};
/**
* Checks if the database is running on a client (browser) or
* a server (node.js).
* @returns {Boolean} Returns true if running on a server.
*/
Db.prototype.isServer = function () {
return this._isServer;
};
/**
* Converts a normal javascript array of objects into a DB collection.
* @param {Array} arr An array of objects.
* @returns {Collection} A new collection instance with the data set to the
* array passed.
*/
Db.prototype.arrayToCollection = function (arr) {
return new Collection().setData(arr);
};
/**
* Registers an event listener against an event name.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The listener method to call when
* the event is fired.
* @returns {*}
*/
Db.prototype.on = function(event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || [];
this._listeners[event].push(listener);
return this;
};
/**
* De-registers an event listener from an event name.
* @param {String} event The name of the event to stop listening for.
* @param {Function} listener The listener method passed to on() when
* registering the event listener.
* @returns {*}
*/
Db.prototype.off = function(event, listener) {
if (event in this._listeners) {
var arr = this._listeners[event],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
return this;
};
/**
* Emits an event by name with the given data.
* @param {String} event The name of the event to emit.
* @param {*=} data The data to emit with the event.
* @returns {*}
*/
Db.prototype.emit = function(event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arr = this._listeners[event],
arrCount = arr.length,
arrIndex;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
return this;
};
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object.
* @param search String or search object.
* @returns {Array}
*/
Db.prototype.peek = function (search) {
var i,
coll,
arr = [],
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = arr.concat(coll.peek(search));
} else {
arr = arr.concat(coll.find(search));
}
}
}
return arr;
};
/**
* Find all documents across all collections in the database that match the passed
* string or search object and return them in an object where each key is the name
* of the collection that the document was matched in.
* @param search String or search object.
* @returns {object}
*/
Db.prototype.peekCat = function (search) {
var i,
coll,
cat = {},
arr,
typeOfSearch = typeof search;
// Loop collections
for (i in this._collection) {
if (this._collection.hasOwnProperty(i)) {
coll = this._collection[i];
if (typeOfSearch === 'string') {
arr = coll.peek(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
} else {
arr = coll.find(search);
if (arr && arr.length) {
cat[coll.name()] = arr;
}
}
}
}
return cat;
};
Db.prototype.drop = new Overload({
/**
* Drops the database.
* @func drop
* @memberof Db
*/
'': function () {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop();
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional callback method.
* @func drop
* @memberof Db
* @param {Function} callback Optional callback method.
*/
'function': function (callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database with optional persistent storage drop. Persistent
* storage is dropped by default if no preference is provided.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
*/
'boolean': function (removePersist) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex;
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._core._db[this._name];
}
return true;
},
/**
* Drops the database and optionally controls dropping persistent storage
* and callback method.
* @func drop
* @memberof Db
* @param {Boolean} removePersist Drop persistent storage for this database.
* @param {Function} callback Optional callback method.
*/
'boolean, function': function (removePersist, callback) {
if (!this.isDropped()) {
var arr = this.collections(),
arrCount = arr.length,
arrIndex,
finishCount = 0,
afterDrop = function () {
finishCount++;
if (finishCount === arrCount) {
if (callback) { callback(); }
}
};
this._state = 'dropped';
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
this.collection(arr[arrIndex].name).drop(removePersist, afterDrop);
delete this._collection[arr[arrIndex].name];
}
this.emit('drop', this);
delete this._core._db[this._name];
}
return true;
}
});
/**
* Gets a database instance by name.
* @memberof Core
* @param {String=} name Optional name of the database. If none is provided
* a random name is assigned.
* @returns {Db}
*/
Core.prototype.db = function (name) {
// Handle being passed an instance
if (name instanceof Db) {
return name;
}
if (!name) {
name = this.objectId();
}
this._db[name] = this._db[name] || new Db(name, this);
this._db[name].mongoEmulation(this.mongoEmulation());
return this._db[name];
};
/**
* Returns an array of databases that ForerunnerDB currently has.
* @memberof Core
* @param {String|RegExp=} search The optional search string or regular expression to use
* to match collection names against.
* @returns {Array} An array of objects containing details of each database
* that ForerunnerDB is currently managing and it's child entities.
*/
Core.prototype.databases = function (search) {
var arr = [],
tmpObj,
addDb,
i;
if (search) {
if (!(search instanceof RegExp)) {
// Turn the search into a regular expression
search = new RegExp(search);
}
}
for (i in this._db) {
if (this._db.hasOwnProperty(i)) {
addDb = true;
if (search) {
if (!search.exec(i)) {
addDb = false;
}
}
if (addDb) {
tmpObj = {
name: i,
children: []
};
if (this.shared.moduleExists('Collection')) {
tmpObj.children.push({
module: 'collection',
moduleName: 'Collections',
count: this._db[i].collections().length
});
}
if (this.shared.moduleExists('CollectionGroup')) {
tmpObj.children.push({
module: 'collectionGroup',
moduleName: 'Collection Groups',
count: this._db[i].collectionGroups().length
});
}
if (this.shared.moduleExists('Document')) {
tmpObj.children.push({
module: 'document',
moduleName: 'Documents',
count: this._db[i].documents().length
});
}
if (this.shared.moduleExists('Grid')) {
tmpObj.children.push({
module: 'grid',
moduleName: 'Grids',
count: this._db[i].grids().length
});
}
if (this.shared.moduleExists('Overview')) {
tmpObj.children.push({
module: 'overview',
moduleName: 'Overviews',
count: this._db[i].overviews().length
});
}
if (this.shared.moduleExists('View')) {
tmpObj.children.push({
module: 'view',
moduleName: 'Views',
count: this._db[i].views().length
});
}
arr.push(tmpObj);
}
}
}
arr.sort(function (a, b) {
return a.name.localeCompare(b.name);
});
return arr;
};
Shared.finishModule('Db');
module.exports = Db;
},{"./Collection.js":4,"./Crc.js":7,"./Metrics.js":15,"./Overload":29,"./Shared":37}],9:[function(_dereq_,module,exports){
"use strict";
// TODO: Remove the _update* methods because we are already mixing them
// TODO: in now via Mixin.Updating and update autobind to extend the _update*
// TODO: methods like we already do with collection
var Shared,
Collection,
Db;
Shared = _dereq_('./Shared');
/**
* Creates a new Document instance. Documents allow you to create individual
* objects that can have standard ForerunnerDB CRUD operations run against
* them, as well as data-binding if the AutoBind module is included in your
* project.
* @name Document
* @class Document
* @constructor
*/
var FdbDocument = function () {
this.init.apply(this, arguments);
};
FdbDocument.prototype.init = function (name) {
this._name = name;
this._data = {};
};
Shared.addModule('Document', FdbDocument);
Shared.mixin(FdbDocument.prototype, 'Mixin.Common');
Shared.mixin(FdbDocument.prototype, 'Mixin.Events');
Shared.mixin(FdbDocument.prototype, 'Mixin.ChainReactor');
Shared.mixin(FdbDocument.prototype, 'Mixin.Constants');
Shared.mixin(FdbDocument.prototype, 'Mixin.Triggers');
Shared.mixin(FdbDocument.prototype, 'Mixin.Matching');
Shared.mixin(FdbDocument.prototype, 'Mixin.Updating');
Shared.mixin(FdbDocument.prototype, 'Mixin.Tags');
Collection = _dereq_('./Collection');
Db = Shared.modules.Db;
/**
* Gets / sets the current state.
* @func state
* @memberof Document
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(FdbDocument.prototype, 'state');
/**
* Gets / sets the db instance this class instance belongs to.
* @func db
* @memberof Document
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(FdbDocument.prototype, 'db');
/**
* Gets / sets the document name.
* @func name
* @memberof Document
* @param {String=} val The name to assign
* @returns {*}
*/
Shared.synthesize(FdbDocument.prototype, 'name');
/**
* Sets the data for the document.
* @func setData
* @memberof Document
* @param data
* @param options
* @returns {Document}
*/
FdbDocument.prototype.setData = function (data, options) {
var i,
$unset;
if (data) {
options = options || {
$decouple: true
};
if (options && options.$decouple === true) {
data = this.decouple(data);
}
if (this._linked) {
$unset = {};
// Remove keys that don't exist in the new data from the current object
for (i in this._data) {
if (i.substr(0, 6) !== 'jQuery' && this._data.hasOwnProperty(i)) {
// Check if existing data has key
if (data[i] === undefined) {
// Add property name to those to unset
$unset[i] = 1;
}
}
}
data.$unset = $unset;
// Now update the object with new data
this.updateObject(this._data, data, {});
} else {
// Straight data assignment
this._data = data;
}
this.deferEmit('change', {type: 'setData', data: this.decouple(this._data)});
}
return this;
};
/**
* Gets the document's data returned as a single object.
* @func find
* @memberof Document
* @param {Object} query The query object - currently unused, just
* provide a blank object e.g. {}
* @param {Object=} options An options object.
* @returns {Object} The document's data object.
*/
FdbDocument.prototype.find = function (query, options) {
var result;
if (options && options.$decouple === false) {
result = this._data;
} else {
result = this.decouple(this._data);
}
return result;
};
/**
* Modifies the document. This will update the document with the data held in 'update'.
* @func update
* @memberof Document
* @param {Object} query The query that must be matched for a document to be
* operated on.
* @param {Object} update The object containing updated key/values. Any keys that
* match keys on the existing document will be overwritten with this data. Any
* keys that do not currently exist on the document will be added to the document.
* @param {Object=} options An options object.
* @returns {Array} The items that were updated.
*/
FdbDocument.prototype.update = function (query, update, options) {
var result = this.updateObject(this._data, update, query, options);
if (result) {
this.deferEmit('change', {type: 'update', data: this.decouple(this._data)});
}
};
/**
* Internal method for document updating.
* @func updateObject
* @memberof Document
* @param {Object} doc The document to update.
* @param {Object} update The object with key/value pairs to update the document with.
* @param {Object} query The query object that we need to match to perform an update.
* @param {Object} options An options object.
* @param {String} path The current recursive path.
* @param {String} opType The type of update operation to perform, if none is specified
* default is to set new data against matching fields.
* @returns {Boolean} True if the document was updated with new / changed data or
* false if it was not updated because the data was the same.
* @private
*/
FdbDocument.prototype.updateObject = Collection.prototype.updateObject;
/**
* Determines if the passed key has an array positional mark (a dollar at the end
* of its name).
* @func _isPositionalKey
* @memberof Document
* @param {String} key The key to check.
* @returns {Boolean} True if it is a positional or false if not.
* @private
*/
FdbDocument.prototype._isPositionalKey = function (key) {
return key.substr(key.length - 2, 2) === '.$';
};
/**
* Updates a property on an object depending on if the collection is
* currently running data-binding or not.
* @func _updateProperty
* @memberof Document
* @param {Object} doc The object whose property is to be updated.
* @param {String} prop The property to update.
* @param {*} val The new value of the property.
* @private
*/
FdbDocument.prototype._updateProperty = function (doc, prop, val) {
if (this._linked) {
window.jQuery.observable(doc).setProperty(prop, val);
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting data-bound document property "' + prop + '"');
}
} else {
doc[prop] = val;
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '"');
}
}
};
/**
* Increments a value for a property on a document by the passed number.
* @func _updateIncrement
* @memberof Document
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to increment by.
* @private
*/
FdbDocument.prototype._updateIncrement = function (doc, prop, val) {
if (this._linked) {
window.jQuery.observable(doc).setProperty(prop, doc[prop] + val);
} else {
doc[prop] += val;
}
};
/**
* Changes the index of an item in the passed array.
* @func _updateSpliceMove
* @memberof Document
* @param {Array} arr The array to modify.
* @param {Number} indexFrom The index to move the item from.
* @param {Number} indexTo The index to move the item to.
* @private
*/
FdbDocument.prototype._updateSpliceMove = function (arr, indexFrom, indexTo) {
if (this._linked) {
window.jQuery.observable(arr).move(indexFrom, indexTo);
if (this.debug()) {
console.log(this.logIdentifier() + ' Moving data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"');
}
} else {
arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]);
if (this.debug()) {
console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"');
}
}
};
/**
* Inserts an item into the passed array at the specified index.
* @func _updateSplicePush
* @memberof Document
* @param {Array} arr The array to insert into.
* @param {Number} index The index to insert at.
* @param {Object} doc The document to insert.
* @private
*/
FdbDocument.prototype._updateSplicePush = function (arr, index, doc) {
if (arr.length > index) {
if (this._linked) {
window.jQuery.observable(arr).insert(index, doc);
} else {
arr.splice(index, 0, doc);
}
} else {
if (this._linked) {
window.jQuery.observable(arr).insert(doc);
} else {
arr.push(doc);
}
}
};
/**
* Inserts an item at the end of an array.
* @func _updatePush
* @memberof Document
* @param {Array} arr The array to insert the item into.
* @param {Object} doc The document to insert.
* @private
*/
FdbDocument.prototype._updatePush = function (arr, doc) {
if (this._linked) {
window.jQuery.observable(arr).insert(doc);
} else {
arr.push(doc);
}
};
/**
* Removes an item from the passed array.
* @func _updatePull
* @memberof Document
* @param {Array} arr The array to modify.
* @param {Number} index The index of the item in the array to remove.
* @private
*/
FdbDocument.prototype._updatePull = function (arr, index) {
if (this._linked) {
window.jQuery.observable(arr).remove(index);
} else {
arr.splice(index, 1);
}
};
/**
* Multiplies a value for a property on a document by the passed number.
* @func _updateMultiply
* @memberof Document
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to multiply by.
* @private
*/
FdbDocument.prototype._updateMultiply = function (doc, prop, val) {
if (this._linked) {
window.jQuery.observable(doc).setProperty(prop, doc[prop] * val);
} else {
doc[prop] *= val;
}
};
/**
* Renames a property on a document to the passed property.
* @func _updateRename
* @memberof Document
* @param {Object} doc The document to modify.
* @param {String} prop The property to rename.
* @param {Number} val The new property name.
* @private
*/
FdbDocument.prototype._updateRename = function (doc, prop, val) {
var existingVal = doc[prop];
if (this._linked) {
window.jQuery.observable(doc).setProperty(val, existingVal);
window.jQuery.observable(doc).removeProperty(prop);
} else {
doc[val] = existingVal;
delete doc[prop];
}
};
/**
* Deletes a property on a document.
* @func _updateUnset
* @memberof Document
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @private
*/
FdbDocument.prototype._updateUnset = function (doc, prop) {
if (this._linked) {
window.jQuery.observable(doc).removeProperty(prop);
} else {
delete doc[prop];
}
};
/**
* Drops the document.
* @func drop
* @memberof Document
* @returns {boolean} True if successful, false if not.
*/
FdbDocument.prototype.drop = function (callback) {
if (!this.isDropped()) {
if (this._db && this._name) {
if (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);
if (callback) { callback(false, true); }
return true;
}
}
} else {
return true;
}
return false;
};
/**
* Creates a new document instance.
* @func document
* @memberof Db
* @param {String} documentName The name of the document to create.
* @returns {*}
*/
Db.prototype.document = function (documentName) {
if (documentName) {
// Handle being passed an instance
if (documentName instanceof FdbDocument) {
if (documentName.state() !== 'droppped') {
return documentName;
} else {
documentName = documentName.name();
}
}
this._document = this._document || {};
this._document[documentName] = this._document[documentName] || new FdbDocument(documentName).db(this);
return this._document[documentName];
} else {
// Return an object of document data
return this._document;
}
};
/**
* Returns an array of documents the DB currently has.
* @func documents
* @memberof Db
* @returns {Array} An array of objects containing details of each document
* the database is currently managing.
*/
Db.prototype.documents = function () {
var arr = [],
item,
i;
for (i in this._document) {
if (this._document.hasOwnProperty(i)) {
item = this._document[i];
arr.push({
name: i,
linked: item.isLinked !== undefined ? item.isLinked() : false
});
}
}
return arr;
};
Shared.finishModule('Document');
module.exports = FdbDocument;
},{"./Collection":4,"./Shared":37}],10:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
Collection,
CollectionGroup,
View,
CollectionInit,
DbInit,
ReactorIO;
//Shared = ForerunnerDB.shared;
Shared = _dereq_('./Shared');
/**
* Creates a new grid instance.
* @name Grid
* @class Grid
* @param {String} selector jQuery selector.
* @param {String} template The template selector.
* @param {Object=} options The options object to apply to the grid.
* @constructor
*/
var Grid = function (selector, template, options) {
this.init.apply(this, arguments);
};
Grid.prototype.init = function (selector, template, options) {
var self = this;
this._selector = selector;
this._template = template;
this._options = options || {};
this._debug = {};
this._id = this.objectId();
this._collectionDroppedWrap = function () {
self._collectionDropped.apply(self, arguments);
};
};
Shared.addModule('Grid', Grid);
Shared.mixin(Grid.prototype, 'Mixin.Common');
Shared.mixin(Grid.prototype, 'Mixin.ChainReactor');
Shared.mixin(Grid.prototype, 'Mixin.Constants');
Shared.mixin(Grid.prototype, 'Mixin.Triggers');
Shared.mixin(Grid.prototype, 'Mixin.Events');
Shared.mixin(Grid.prototype, 'Mixin.Tags');
Collection = _dereq_('./Collection');
CollectionGroup = _dereq_('./CollectionGroup');
View = _dereq_('./View');
ReactorIO = _dereq_('./ReactorIO');
CollectionInit = Collection.prototype.init;
Db = Shared.modules.Db;
DbInit = Db.prototype.init;
/**
* Gets / sets the current state.
* @func state
* @memberof Grid
* @param {String=} val The name of the state to set.
* @returns {Grid}
*/
Shared.synthesize(Grid.prototype, 'state');
/**
* Gets / sets the current name.
* @func name
* @memberof Grid
* @param {String=} val The name to set.
* @returns {Grid}
*/
Shared.synthesize(Grid.prototype, 'name');
/**
* Executes an insert against the grid's underlying data-source.
* @func insert
* @memberof Grid
*/
Grid.prototype.insert = function () {
this._from.insert.apply(this._from, arguments);
};
/**
* Executes an update against the grid's underlying data-source.
* @func update
* @memberof Grid
*/
Grid.prototype.update = function () {
this._from.update.apply(this._from, arguments);
};
/**
* Executes an updateById against the grid's underlying data-source.
* @func updateById
* @memberof Grid
*/
Grid.prototype.updateById = function () {
this._from.updateById.apply(this._from, arguments);
};
/**
* Executes a remove against the grid's underlying data-source.
* @func remove
* @memberof Grid
*/
Grid.prototype.remove = function () {
this._from.remove.apply(this._from, arguments);
};
/**
* Sets the collection from which the grid will assemble its data.
* @func from
* @memberof Grid
* @param {Collection} collection The collection to use to assemble grid data.
* @returns {Grid}
*/
Grid.prototype.from = function (collection) {
//var self = this;
if (collection !== undefined) {
// Check if we have an existing from
if (this._from) {
// Remove the listener to the drop event
this._from.off('drop', this._collectionDroppedWrap);
this._from._removeGrid(this);
}
if (typeof(collection) === 'string') {
collection = this._db.collection(collection);
}
this._from = collection;
this._from.on('drop', this._collectionDroppedWrap);
this.refresh();
}
return this;
};
/**
* Gets / sets the db instance this class instance belongs to.
* @func db
* @memberof Grid
* @param {Db=} db The db instance.
* @returns {*}
*/
Shared.synthesize(Grid.prototype, 'db', function (db) {
if (db) {
// Apply the same debug settings
this.debug(db.debug());
}
return this.$super.apply(this, arguments);
});
Grid.prototype._collectionDropped = function (collection) {
if (collection) {
// Collection was dropped, remove from grid
delete this._from;
}
};
/**
* Drops a grid and all it's stored data from the database.
* @func drop
* @memberof Grid
* @returns {boolean} True on success, false on failure.
*/
Grid.prototype.drop = function (callback) {
if (!this.isDropped()) {
if (this._from) {
// Remove data-binding
this._from.unlink(this._selector, this.template());
// Kill listeners and references
this._from.off('drop', this._collectionDroppedWrap);
this._from._removeGrid(this);
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Dropping grid ' + this._selector);
}
this._state = 'dropped';
if (this._db && this._selector) {
delete this._db._grid[this._selector];
}
this.emit('drop', this);
if (callback) { callback(false, true); }
delete this._selector;
delete this._template;
delete this._from;
delete this._db;
return true;
}
} else {
return true;
}
return false;
};
/**
* Gets / sets the grid's HTML template to use when rendering.
* @func template
* @memberof Grid
* @param {Selector} template The template's jQuery selector.
* @returns {*}
*/
Grid.prototype.template = function (template) {
if (template !== undefined) {
this._template = template;
return this;
}
return this._template;
};
Grid.prototype._sortGridClick = function (e) {
var elem = window.jQuery(e.currentTarget),
sortColText = elem.attr('data-grid-sort') || '',
sortColDir = parseInt((elem.attr('data-grid-dir') || "-1"), 10) === -1 ? 1 : -1,
sortCols = sortColText.split(','),
sortObj = {},
i;
// Remove all grid sort tags from the grid
window.jQuery(this._selector).find('[data-grid-dir]').removeAttr('data-grid-dir');
// Flip the sort direction
elem.attr('data-grid-dir', sortColDir);
for (i = 0; i < sortCols.length; i++) {
sortObj[sortCols] = sortColDir;
}
Shared.mixin(sortObj, this._options.$orderBy);
this._from.orderBy(sortObj);
this.emit('sort', sortObj);
};
/**
* Refreshes the grid data such as ordering etc.
* @func refresh
* @memberof Grid
*/
Grid.prototype.refresh = function () {
if (this._from) {
if (this._from.link) {
var self = this,
elem = window.jQuery(this._selector),
sortClickListener = function () {
self._sortGridClick.apply(self, arguments);
};
// Clear the container
elem.html('');
if (self._from.orderBy) {
// Remove listeners
elem.off('click', '[data-grid-sort]', sortClickListener);
}
if (self._from.query) {
// Remove listeners
elem.off('click', '[data-grid-filter]', sortClickListener );
}
// Set wrap name if none is provided
self._options.$wrap = self._options.$wrap || 'gridRow';
// Auto-bind the data to the grid template
self._from.link(self._selector, self.template(), self._options);
// Check if the data source (collection or view) has an
// orderBy method (usually only views) and if so activate
// the sorting system
if (self._from.orderBy) {
// Listen for sort requests
elem.on('click', '[data-grid-sort]', sortClickListener);
}
if (self._from.query) {
// Listen for filter requests
var queryObj = {};
elem.find('[data-grid-filter]').each(function (index, filterElem) {
filterElem = window.jQuery(filterElem);
var filterField = filterElem.attr('data-grid-filter'),
filterVarType = filterElem.attr('data-grid-vartype'),
filterSort = {},
title = filterElem.html(),
dropDownButton,
dropDownMenu,
template,
filterQuery,
filterView = self._db.view('tmpGridFilter_' + self._id + '_' + filterField);
filterSort[filterField] = 1;
filterQuery = {
$distinct: filterSort
};
filterView
.query(filterQuery)
.orderBy(filterSort)
.from(self._from._from);
template = [
'<div class="dropdown" id="' + self._id + '_' + filterField + '">',
'<button class="btn btn-default dropdown-toggle" type="button" id="' + self._id + '_' + filterField + '_dropdownButton" data-toggle="dropdown" aria-expanded="true">',
title + ' <span class="caret"></span>',
'</button>',
'</div>'
];
dropDownButton = window.jQuery(template.join(''));
dropDownMenu = window.jQuery('<ul class="dropdown-menu" role="menu" id="' + self._id + '_' + filterField + '_dropdownMenu"></ul>');
dropDownButton.append(dropDownMenu);
filterElem.html(dropDownButton);
// Data-link the underlying data to the grid filter drop-down
filterView.link(dropDownMenu, {
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{:' + filterField + '}">',
'<a role="menuitem" tabindex="-1">',
'<input type="checkbox"> {^{:' + filterField + '}}',
'</a>',
'</li>',
'{{/for}}'
].join('')
}, {
$wrap: 'options'
});
elem.on('keyup', '#' + self._id + '_' + filterField + '_dropdownMenu .gridFilterSearch', function (e) {
var elem = window.jQuery(this),
query = filterView.query(),
search = elem.val();
if (search) {
query[filterField] = new RegExp(search, 'gi');
} else {
delete query[filterField];
}
filterView.query(query);
});
elem.on('click', '#' + self._id + '_' + filterField + '_dropdownMenu .gridFilterClearSearch', function (e) {
// Clear search text box
window.jQuery(this).parents('li').find('.gridFilterSearch').val('');
// Clear view query
var query = filterView.query();
delete query[filterField];
filterView.query(query);
});
elem.on('click', '#' + self._id + '_' + filterField + '_dropdownMenu li', function (e) {
e.stopPropagation();
var fieldValue,
elem = $(this),
checkbox = elem.find('input[type="checkbox"]'),
checked,
addMode = true,
fieldInArr,
liElem,
i;
// If the checkbox is not the one clicked on
if (!window.jQuery(e.target).is('input')) {
// Set checkbox to opposite of current value
checkbox.prop('checked', !checkbox.prop('checked'));
checked = checkbox.is(':checked');
} else {
checkbox.prop('checked', checkbox.prop('checked'));
checked = checkbox.is(':checked');
}
liElem = window.jQuery(this);
fieldValue = liElem.attr('data-val');
// Check if the selection is the "all" option
if (fieldValue === '$all') {
// Remove the field from the query
delete queryObj[filterField];
// Clear all other checkboxes
liElem.parent().find('li[data-val!="$all"]').find('input[type="checkbox"]').prop('checked', false);
} else {
// Clear the "all" checkbox
liElem.parent().find('[data-val="$all"]').find('input[type="checkbox"]').prop('checked', false);
// Check if the type needs casting
switch (filterVarType) {
case 'integer':
fieldValue = parseInt(fieldValue, 10);
break;
case 'float':
fieldValue = parseFloat(fieldValue);
break;
default:
}
// Check if the item exists already
queryObj[filterField] = queryObj[filterField] || {
$in: []
};
fieldInArr = queryObj[filterField].$in;
for (i = 0; i < fieldInArr.length; i++) {
if (fieldInArr[i] === fieldValue) {
// Item already exists
if (checked === false) {
// Remove the item
fieldInArr.splice(i, 1);
}
addMode = false;
break;
}
}
if (addMode && checked) {
fieldInArr.push(fieldValue);
}
if (!fieldInArr.length) {
// Remove the field from the query
delete queryObj[filterField];
}
}
// Set the view query
self._from.queryData(queryObj);
if (self._from.pageFirst) {
self._from.pageFirst();
}
});
});
}
self.emit('refresh');
} else {
throw('Grid requires the AutoBind module in order to operate!');
}
}
return this;
};
/**
* Returns the number of documents currently in the grid.
* @func count
* @memberof Grid
* @returns {Number}
*/
Grid.prototype.count = function () {
return this._from.count();
};
/**
* Creates a grid and assigns the collection as its data source.
* @func grid
* @memberof Collection
* @param {String} selector jQuery selector of grid output target.
* @param {String} template The table template to use when rendering the grid.
* @param {Object=} options The options object to apply to the grid.
* @returns {*}
*/
Collection.prototype.grid = View.prototype.grid = function (selector, template, options) {
if (this._db && this._db._grid ) {
if (selector !== undefined) {
if (template !== undefined) {
if (!this._db._grid[selector]) {
var grid = new Grid(selector, template, options)
.db(this._db)
.from(this);
this._grid = this._grid || [];
this._grid.push(grid);
this._db._grid[selector] = grid;
return grid;
} else {
throw(this.logIdentifier() + ' Cannot create a grid because a grid with this name already exists: ' + selector);
}
}
return this._db._grid[selector];
}
return this._db._grid;
}
};
/**
* Removes a grid safely from the DOM. Must be called when grid is
* no longer required / is being removed from DOM otherwise references
* will stick around and cause memory leaks.
* @func unGrid
* @memberof Collection
* @param {String} selector jQuery selector of grid output target.
* @param {String} template The table template to use when rendering the grid.
* @param {Object=} options The options object to apply to the grid.
* @returns {*}
*/
Collection.prototype.unGrid = View.prototype.unGrid = function (selector, template, options) {
var i,
grid;
if (this._db && this._db._grid ) {
if (selector && template) {
if (this._db._grid[selector]) {
grid = this._db._grid[selector];
delete this._db._grid[selector];
return grid.drop();
} else {
throw(this.logIdentifier() + ' Cannot remove grid because a grid with this name does not exist: ' + name);
}
} else {
// No parameters passed, remove all grids from this module
for (i in this._db._grid) {
if (this._db._grid.hasOwnProperty(i)) {
grid = this._db._grid[i];
delete this._db._grid[i];
grid.drop();
if (this.debug()) {
console.log(this.logIdentifier() + ' Removed grid binding "' + i + '"');
}
}
}
this._db._grid = {};
}
}
};
/**
* Adds a grid to the internal grid lookup.
* @func _addGrid
* @memberof Collection
* @param {Grid} grid The grid to add.
* @returns {Collection}
* @private
*/
Collection.prototype._addGrid = CollectionGroup.prototype._addGrid = View.prototype._addGrid = function (grid) {
if (grid !== undefined) {
this._grid = this._grid || [];
this._grid.push(grid);
}
return this;
};
/**
* Removes a grid from the internal grid lookup.
* @func _removeGrid
* @memberof Collection
* @param {Grid} grid The grid to remove.
* @returns {Collection}
* @private
*/
Collection.prototype._removeGrid = CollectionGroup.prototype._removeGrid = View.prototype._removeGrid = function (grid) {
if (grid !== undefined && this._grid) {
var index = this._grid.indexOf(grid);
if (index > -1) {
this._grid.splice(index, 1);
}
}
return this;
};
// Extend DB with grids init
Db.prototype.init = function () {
this._grid = {};
DbInit.apply(this, arguments);
};
/**
* Determine if a grid with the passed name already exists.
* @func gridExists
* @memberof Db
* @param {String} selector The jQuery selector to bind the grid to.
* @returns {boolean}
*/
Db.prototype.gridExists = function (selector) {
return Boolean(this._grid[selector]);
};
/**
* Creates a grid based on the passed arguments.
* @func grid
* @memberof Db
* @param {String} selector The jQuery selector of the grid to retrieve.
* @param {String} template The table template to use when rendering the grid.
* @param {Object=} options The options object to apply to the grid.
* @returns {*}
*/
Db.prototype.grid = function (selector, template, options) {
if (!this._grid[selector]) {
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Creating grid ' + selector);
}
}
this._grid[selector] = this._grid[selector] || new Grid(selector, template, options).db(this);
return this._grid[selector];
};
/**
* Removes a grid based on the passed arguments.
* @func unGrid
* @memberof Db
* @param {String} selector The jQuery selector of the grid to retrieve.
* @param {String} template The table template to use when rendering the grid.
* @param {Object=} options The options object to apply to the grid.
* @returns {*}
*/
Db.prototype.unGrid = function (selector, template, options) {
if (!this._grid[selector]) {
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Creating grid ' + selector);
}
}
this._grid[selector] = this._grid[selector] || new Grid(selector, template, options).db(this);
return this._grid[selector];
};
/**
* Returns an array of grids the DB currently has.
* @func grids
* @memberof Db
* @returns {Array} An array of objects containing details of each grid
* the database is currently managing.
*/
Db.prototype.grids = function () {
var arr = [],
item,
i;
for (i in this._grid) {
if (this._grid.hasOwnProperty(i)) {
item = this._grid[i];
arr.push({
name: i,
count: item.count(),
linked: item.isLinked !== undefined ? item.isLinked() : false
});
}
}
return arr;
};
Shared.finishModule('Grid');
module.exports = Grid;
},{"./Collection":4,"./CollectionGroup":5,"./ReactorIO":35,"./Shared":37,"./View":38}],11:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Collection,
CollectionInit,
Overload;
Shared = _dereq_('./Shared');
Overload = _dereq_('./Overload');
/**
* The constructor.
*
* @constructor
*/
var Highchart = function (collection, options) {
this.init.apply(this, arguments);
};
Highchart.prototype.init = function (collection, options) {
this._options = options;
this._selector = window.jQuery(this._options.selector);
if (!this._selector[0]) {
throw(this.classIdentifier() + ' "' + collection.name() + '": Chart target element does not exist via selector: ' + this._options.selector);
}
this._listeners = {};
this._collection = collection;
// Setup the chart
this._options.series = [];
// Disable attribution on highcharts
options.chartOptions = options.chartOptions || {};
options.chartOptions.credits = false;
// Set the data for the chart
var data,
seriesObj,
chartData;
switch (this._options.type) {
case 'pie':
// Create chart from data
this._selector.highcharts(this._options.chartOptions);
this._chart = this._selector.highcharts();
// Generate graph data from collection data
data = this._collection.find();
seriesObj = {
allowPointSelect: true,
cursor: 'pointer',
dataLabels: {
enabled: true,
format: '<b>{point.name}</b>: {y} ({point.percentage:.0f}%)',
style: {
color: (window.Highcharts.theme && window.Highcharts.theme.contrastTextColor) || 'black'
}
}
};
chartData = this.pieDataFromCollectionData(data, this._options.keyField, this._options.valField);
window.jQuery.extend(seriesObj, this._options.seriesOptions);
window.jQuery.extend(seriesObj, {
name: this._options.seriesName,
data: chartData
});
this._chart.addSeries(seriesObj, true, true);
break;
case 'line':
case 'area':
case 'column':
case 'bar':
// Generate graph data from collection data
chartData = this.seriesDataFromCollectionData(
this._options.seriesField,
this._options.keyField,
this._options.valField,
this._options.orderBy
);
this._options.chartOptions.xAxis = chartData.xAxis;
this._options.chartOptions.series = chartData.series;
this._selector.highcharts(this._options.chartOptions);
this._chart = this._selector.highcharts();
break;
default:
throw(this.classIdentifier() + ' "' + collection.name() + '": Chart type specified is not currently supported by ForerunnerDB: ' + this._options.type);
}
// Hook the collection events to auto-update the chart
this._hookEvents();
};
Shared.addModule('Highchart', Highchart);
Collection = Shared.modules.Collection;
CollectionInit = Collection.prototype.init;
Shared.mixin(Highchart.prototype, 'Mixin.Common');
Shared.mixin(Highchart.prototype, 'Mixin.Events');
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Highchart.prototype, 'state');
/**
* Generate pie-chart series data from the given collection data array.
* @param data
* @param keyField
* @param valField
* @returns {Array}
*/
Highchart.prototype.pieDataFromCollectionData = function (data, keyField, valField) {
var graphData = [],
i;
for (i = 0; i < data.length; i++) {
graphData.push([data[i][keyField], data[i][valField]]);
}
return graphData;
};
/**
* Generate line-chart series data from the given collection data array.
* @param seriesField
* @param keyField
* @param valField
* @param orderBy
*/
Highchart.prototype.seriesDataFromCollectionData = function (seriesField, keyField, valField, orderBy) {
var data = this._collection.distinct(seriesField),
seriesData = [],
xAxis = {
categories: []
},
seriesName,
query,
dataSearch,
seriesValues,
i, k;
// What we WANT to output:
/*series: [{
name: 'Responses',
data: [7.0, 6.9, 9.5, 14.5, 18.2, 21.5, 25.2, 26.5, 23.3, 18.3, 13.9, 9.6]
}]*/
// Loop keys
for (i = 0; i < data.length; i++) {
seriesName = data[i];
query = {};
query[seriesField] = seriesName;
seriesValues = [];
dataSearch = this._collection.find(query, {
orderBy: orderBy
});
// Loop the keySearch data and grab the value for each item
for (k = 0; k < dataSearch.length; k++) {
xAxis.categories.push(dataSearch[k][keyField]);
seriesValues.push(dataSearch[k][valField]);
}
seriesData.push({
name: seriesName,
data: seriesValues
});
}
return {
xAxis: xAxis,
series: seriesData
};
};
/**
* Hook the events the chart needs to know about from the internal collection.
* @private
*/
Highchart.prototype._hookEvents = function () {
var self = this;
self._collection.on('change', function () { self._changeListener.apply(self, arguments); });
// If the collection is dropped, clean up after ourselves
self._collection.on('drop', function () { self.drop.apply(self); });
};
/**
* Handles changes to the collection data that the chart is reading from and then
* updates the data in the chart display.
* @private
*/
Highchart.prototype._changeListener = function () {
var self = this;
// Update the series data on the chart
if(typeof self._collection !== 'undefined' && self._chart) {
var data = self._collection.find(),
i;
switch (self._options.type) {
case 'pie':
self._chart.series[0].setData(
self.pieDataFromCollectionData(
data,
self._options.keyField,
self._options.valField
),
true,
true
);
break;
case 'bar':
case 'line':
case 'area':
case 'column':
var seriesData = self.seriesDataFromCollectionData(
self._options.seriesField,
self._options.keyField,
self._options.valField,
self._options.orderBy
);
self._chart.xAxis[0].setCategories(
seriesData.xAxis.categories
);
for (i = 0; i < seriesData.series.length; i++) {
if (self._chart.series[i]) {
// Series exists, set it's data
self._chart.series[i].setData(
seriesData.series[i].data,
true,
true
);
} else {
// Series data does not yet exist, add a new series
self._chart.addSeries(
seriesData.series[i],
true,
true
);
}
}
break;
default:
break;
}
}
};
/**
* Destroys the chart and all internal references.
* @returns {Boolean}
*/
Highchart.prototype.drop = function (callback) {
if (!this.isDropped()) {
this._state = 'dropped';
if (this._chart) {
this._chart.destroy();
}
if (this._collection) {
this._collection.off('change', this._changeListener);
this._collection.off('drop', this.drop);
if (this._collection._highcharts) {
delete this._collection._highcharts[this._options.selector];
}
}
delete this._chart;
delete this._options;
delete this._collection;
this.emit('drop', this);
if (callback) { callback(false, true); }
return true;
} else {
return true;
}
};
// Extend collection with highchart init
Collection.prototype.init = function () {
this._highcharts = {};
CollectionInit.apply(this, arguments);
};
/**
* Creates a pie chart from the collection.
* @type {Overload}
*/
Collection.prototype.pieChart = new Overload({
/**
* Chart via options object.
* @func pieChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'pie';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'pie';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func pieChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {String} seriesName The name of the series to display on the chart.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, keyField, valField, seriesName, options) {
options = options || {};
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
options.seriesName = seriesName;
// Call the main chart method
this.pieChart(options);
}
});
/**
* Creates a line chart from the collection.
* @type {Overload}
*/
Collection.prototype.lineChart = new Overload({
/**
* Chart via options object.
* @func lineChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'line';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'line';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func lineChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.lineChart(options);
}
});
/**
* Creates an area chart from the collection.
* @type {Overload}
*/
Collection.prototype.areaChart = new Overload({
/**
* Chart via options object.
* @func areaChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'area';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'area';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func areaChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.areaChart(options);
}
});
/**
* Creates a column chart from the collection.
* @type {Overload}
*/
Collection.prototype.columnChart = new Overload({
/**
* Chart via options object.
* @func columnChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'column';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'column';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func columnChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.columnChart(options);
}
});
/**
* Creates a bar chart from the collection.
* @type {Overload}
*/
Collection.prototype.barChart = new Overload({
/**
* Chart via options object.
* @func barChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'bar';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'bar';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func barChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.barChart(options);
}
});
/**
* Creates a stacked bar chart from the collection.
* @type {Overload}
*/
Collection.prototype.stackedBarChart = new Overload({
/**
* Chart via options object.
* @func stackedBarChart
* @memberof Highchart
* @param {Object} options The options object.
* @returns {*}
*/
'object': function (options) {
options.type = 'bar';
options.chartOptions = options.chartOptions || {};
options.chartOptions.chart = options.chartOptions.chart || {};
options.chartOptions.chart.type = 'bar';
options.plotOptions = options.plotOptions || {};
options.plotOptions.series = options.plotOptions.series || {};
options.plotOptions.series.stacking = options.plotOptions.series.stacking || 'normal';
if (!this._highcharts[options.selector]) {
// Store new chart in charts array
this._highcharts[options.selector] = new Highchart(this, options);
}
return this._highcharts[options.selector];
},
/**
* Chart via defined params and an options object.
* @func stackedBarChart
* @memberof Highchart
* @param {String|jQuery} selector The element to render the chart to.
* @param {String} seriesField The name of the series to plot.
* @param {String} keyField The field to use as the data key.
* @param {String} valField The field to use as the data value.
* @param {Object} options The options object.
*/
'*, string, string, string, ...': function (selector, seriesField, keyField, valField, options) {
options = options || {};
options.seriesField = seriesField;
options.selector = selector;
options.keyField = keyField;
options.valField = valField;
// Call the main chart method
this.stackedBarChart(options);
}
});
/**
* Removes a chart from the page by it's selector.
* @memberof Collection
* @param {String} selector The chart selector.
*/
Collection.prototype.dropChart = function (selector) {
if (this._highcharts && this._highcharts[selector]) {
this._highcharts[selector].drop();
}
};
Shared.finishModule('Highchart');
module.exports = Highchart;
},{"./Overload":29,"./Shared":37}],12:[function(_dereq_,module,exports){
"use strict";
/*
name
id
rebuild
state
match
lookup
*/
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path'),
BinaryTree = _dereq_('./BinaryTree'),
treeInstance = new BinaryTree(),
btree = function () {};
treeInstance.inOrder('hash');
/**
* The index class used to instantiate hash map indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexBinaryTree = function () {
this.init.apply(this, arguments);
};
IndexBinaryTree.prototype.init = function (keys, options, collection) {
this._btree = new (btree.create(2, this.sortAsc))();
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
}
this.name(options && options.name ? options.name : this._id);
};
Shared.addModule('IndexBinaryTree', IndexBinaryTree);
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor');
Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting');
IndexBinaryTree.prototype.id = function () {
return this._id;
};
IndexBinaryTree.prototype.state = function () {
return this._state;
};
IndexBinaryTree.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexBinaryTree.prototype, 'data');
Shared.synthesize(IndexBinaryTree.prototype, 'name');
Shared.synthesize(IndexBinaryTree.prototype, 'collection');
Shared.synthesize(IndexBinaryTree.prototype, 'type');
Shared.synthesize(IndexBinaryTree.prototype, 'unique');
IndexBinaryTree.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexBinaryTree.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._btree = new (btree.create(2, this.sortAsc))();
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexBinaryTree.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
dataItemHash = this._itemKeyHash(dataItem, this._keys),
keyArr;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// We store multiple items that match a key inside an array
// that is then stored against that key in the tree...
// Check if item exists for this key already
keyArr = this._btree.get(dataItemHash);
// Check if the array exists
if (keyArr === undefined) {
// Generate an array for this key first
keyArr = [];
// Put the new array into the tree under the key
this._btree.put(dataItemHash, keyArr);
}
// Push the item into the array
keyArr.push(dataItem);
this._size++;
};
IndexBinaryTree.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
dataItemHash = this._itemKeyHash(dataItem, this._keys),
keyArr,
itemIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
// Try and get the array for the item hash key
keyArr = this._btree.get(dataItemHash);
if (keyArr !== undefined) {
// The key array exits, remove the item from the key array
itemIndex = keyArr.indexOf(dataItem);
if (itemIndex > -1) {
// Check the length of the array
if (keyArr.length === 1) {
// This item is the last in the array, just kill the tree entry
this._btree.del(dataItemHash);
} else {
// Remove the item
keyArr.splice(itemIndex, 1);
}
this._size--;
}
}
};
IndexBinaryTree.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexBinaryTree.prototype.lookup = function (query) {
return this._data[this._itemHash(query, this._keys)] || [];
};
IndexBinaryTree.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path();
var indexKeyArr = pathSolver.parseArr(this._keys),
queryArr = pathSolver.parseArr(query),
matchedKeys = [],
matchedKeyCount = 0,
i;
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
} else {
// Query match failed - this is a hash map index so partial key match won't work
return {
matchedKeys: [],
totalKeyCount: queryArr.length,
score: 0
};
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
IndexBinaryTree.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexBinaryTree.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexBinaryTree.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('IndexBinaryTree');
module.exports = IndexBinaryTree;
},{"./BinaryTree":3,"./Path":31,"./Shared":37}],13:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The index class used to instantiate hash map indexes that the database can
* use to speed up queries on collections and views.
* @constructor
*/
var IndexHashMap = function () {
this.init.apply(this, arguments);
};
IndexHashMap.prototype.init = function (keys, options, collection) {
this._crossRef = {};
this._size = 0;
this._id = this._itemKeyHash(keys, keys);
this.data({});
this.unique(options && options.unique ? options.unique : false);
if (keys !== undefined) {
this.keys(keys);
}
if (collection !== undefined) {
this.collection(collection);
}
this.name(options && options.name ? options.name : this._id);
};
Shared.addModule('IndexHashMap', IndexHashMap);
Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor');
IndexHashMap.prototype.id = function () {
return this._id;
};
IndexHashMap.prototype.state = function () {
return this._state;
};
IndexHashMap.prototype.size = function () {
return this._size;
};
Shared.synthesize(IndexHashMap.prototype, 'data');
Shared.synthesize(IndexHashMap.prototype, 'name');
Shared.synthesize(IndexHashMap.prototype, 'collection');
Shared.synthesize(IndexHashMap.prototype, 'type');
Shared.synthesize(IndexHashMap.prototype, 'unique');
IndexHashMap.prototype.keys = function (val) {
if (val !== undefined) {
this._keys = val;
// Count the keys
this._keyCount = (new Path()).parse(this._keys).length;
return this;
}
return this._keys;
};
IndexHashMap.prototype.rebuild = function () {
// Do we have a collection?
if (this._collection) {
// Get sorted data
var collection = this._collection.subset({}, {
$decouple: false,
$orderBy: this._keys
}),
collectionData = collection.find(),
dataIndex,
dataCount = collectionData.length;
// Clear the index data for the index
this._data = {};
if (this._unique) {
this._uniqueLookup = {};
}
// Loop the collection data
for (dataIndex = 0; dataIndex < dataCount; dataIndex++) {
this.insert(collectionData[dataIndex]);
}
}
this._state = {
name: this._name,
keys: this._keys,
indexSize: this._size,
built: new Date(),
updated: new Date(),
ok: true
};
};
IndexHashMap.prototype.insert = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
this._uniqueLookup[uniqueHash] = dataItem;
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pushToPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.update = function (dataItem, options) {
// TODO: Write updates to work
// 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this)
// 2: Remove the uniqueHash as it currently stands
// 3: Generate a new uniqueHash for dataItem
// 4: Insert the new uniqueHash
};
IndexHashMap.prototype.remove = function (dataItem, options) {
var uniqueFlag = this._unique,
uniqueHash,
itemHashArr,
hashIndex;
if (uniqueFlag) {
uniqueHash = this._itemHash(dataItem, this._keys);
delete this._uniqueLookup[uniqueHash];
}
// Generate item hash
itemHashArr = this._itemHashArr(dataItem, this._keys);
// Get the path search results and store them
for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) {
this.pullFromPathValue(itemHashArr[hashIndex], dataItem);
}
};
IndexHashMap.prototype.violation = function (dataItem) {
// Generate item hash
var uniqueHash = this._itemHash(dataItem, this._keys);
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.hashViolation = function (uniqueHash) {
// Check if the item breaks the unique constraint
return Boolean(this._uniqueLookup[uniqueHash]);
};
IndexHashMap.prototype.pushToPathValue = function (hash, obj) {
var pathValArr = this._data[hash] = this._data[hash] || [];
// Make sure we have not already indexed this object at this path/value
if (pathValArr.indexOf(obj) === -1) {
// Index the object
pathValArr.push(obj);
// Record the reference to this object in our index size
this._size++;
// Cross-reference this association for later lookup
this.pushToCrossRef(obj, pathValArr);
}
};
IndexHashMap.prototype.pullFromPathValue = function (hash, obj) {
var pathValArr = this._data[hash],
indexOfObject;
// Make sure we have already indexed this object at this path/value
indexOfObject = pathValArr.indexOf(obj);
if (indexOfObject > -1) {
// Un-index the object
pathValArr.splice(indexOfObject, 1);
// Record the reference to this object in our index size
this._size--;
// Remove object cross-reference
this.pullFromCrossRef(obj, pathValArr);
}
// Check if we should remove the path value array
if (!pathValArr.length) {
// Remove the array
delete this._data[hash];
}
};
IndexHashMap.prototype.pull = function (obj) {
// Get all places the object has been used and remove them
var id = obj[this._collection.primaryKey()],
crossRefArr = this._crossRef[id],
arrIndex,
arrCount = crossRefArr.length,
arrItem;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
arrItem = crossRefArr[arrIndex];
// Remove item from this index lookup array
this._pullFromArray(arrItem, obj);
}
// Record the reference to this object in our index size
this._size--;
// Now remove the cross-reference entry for this object
delete this._crossRef[id];
};
IndexHashMap.prototype._pullFromArray = function (arr, obj) {
var arrCount = arr.length;
while (arrCount--) {
if (arr[arrCount] === obj) {
arr.splice(arrCount, 1);
}
}
};
IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()],
crObj;
this._crossRef[id] = this._crossRef[id] || [];
// Check if the cross-reference to the pathVal array already exists
crObj = this._crossRef[id];
if (crObj.indexOf(pathValArr) === -1) {
// Add the cross-reference
crObj.push(pathValArr);
}
};
IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) {
var id = obj[this._collection.primaryKey()];
delete this._crossRef[id];
};
IndexHashMap.prototype.lookup = function (query) {
return this._data[this._itemHash(query, this._keys)] || [];
};
IndexHashMap.prototype.match = function (query, options) {
// Check if the passed query has data in the keys our index
// operates on and if so, is the query sort matching our order
var pathSolver = new Path();
var indexKeyArr = pathSolver.parseArr(this._keys),
queryArr = pathSolver.parseArr(query),
matchedKeys = [],
matchedKeyCount = 0,
i;
// Loop the query array and check the order of keys against the
// index key array to see if this index can be used
for (i = 0; i < indexKeyArr.length; i++) {
if (queryArr[i] === indexKeyArr[i]) {
matchedKeyCount++;
matchedKeys.push(queryArr[i]);
} else {
// Query match failed - this is a hash map index so partial key match won't work
return {
matchedKeys: [],
totalKeyCount: queryArr.length,
score: 0
};
}
}
return {
matchedKeys: matchedKeys,
totalKeyCount: queryArr.length,
score: matchedKeyCount
};
//return pathSolver.countObjectPaths(this._keys, query);
};
IndexHashMap.prototype._itemHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.value(item, pathData[k].path).join(':');
}
return hash;
};
IndexHashMap.prototype._itemKeyHash = function (item, keys) {
var path = new Path(),
pathData,
hash = '',
k;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
if (hash) { hash += '_'; }
hash += path.keyValue(item, pathData[k].path);
}
return hash;
};
IndexHashMap.prototype._itemHashArr = function (item, keys) {
var path = new Path(),
pathData,
//hash = '',
hashArr = [],
valArr,
i, k, j;
pathData = path.parse(keys);
for (k = 0; k < pathData.length; k++) {
valArr = path.value(item, pathData[k].path);
for (i = 0; i < valArr.length; i++) {
if (k === 0) {
// Setup the initial hash array
hashArr.push(valArr[i]);
} else {
// Loop the hash array and concat the value to it
for (j = 0; j < hashArr.length; j++) {
hashArr[j] = hashArr[j] + '_' + valArr[i];
}
}
}
}
return hashArr;
};
Shared.finishModule('IndexHashMap');
module.exports = IndexHashMap;
},{"./Path":31,"./Shared":37}],14:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* The key value store class used when storing basic in-memory KV data,
* and can be queried for quick retrieval. Mostly used for collection
* primary key indexes and lookups.
* @param {String=} name Optional KV store name.
* @constructor
*/
var KeyValueStore = function (name) {
this.init.apply(this, arguments);
};
KeyValueStore.prototype.init = function (name) {
this._name = name;
this._data = {};
this._primaryKey = '_id';
};
Shared.addModule('KeyValueStore', KeyValueStore);
Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor');
/**
* Get / set the name of the key/value store.
* @param {String} val The name to set.
* @returns {*}
*/
Shared.synthesize(KeyValueStore.prototype, 'name');
/**
* Get / set the primary key.
* @param {String} key The key to set.
* @returns {*}
*/
KeyValueStore.prototype.primaryKey = function (key) {
if (key !== undefined) {
this._primaryKey = key;
return this;
}
return this._primaryKey;
};
/**
* Removes all data from the store.
* @returns {*}
*/
KeyValueStore.prototype.truncate = function () {
this._data = {};
return this;
};
/**
* Sets data against a key in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {*}
*/
KeyValueStore.prototype.set = function (key, value) {
this._data[key] = value ? value : true;
return this;
};
/**
* Gets data stored for the passed key.
* @param {String} key The key to get data for.
* @returns {*}
*/
KeyValueStore.prototype.get = function (key) {
return this._data[key];
};
/**
* Get / set the primary key.
* @param {*} obj A lookup query, can be a string key, an array of string keys,
* an object with further query clauses or a regular expression that should be
* run against all keys.
* @returns {*}
*/
KeyValueStore.prototype.lookup = function (obj) {
var pKeyVal = obj[this._primaryKey],
arrIndex,
arrCount,
lookupItem,
result;
if (pKeyVal instanceof Array) {
// An array of primary keys, find all matches
arrCount = pKeyVal.length;
result = [];
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
lookupItem = this._data[pKeyVal[arrIndex]];
if (lookupItem) {
result.push(lookupItem);
}
}
return result;
} else if (pKeyVal instanceof RegExp) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (pKeyVal.test(arrIndex)) {
result.push(this._data[arrIndex]);
}
}
}
return result;
} else if (typeof pKeyVal === 'object') {
// The primary key clause is an object, now we have to do some
// more extensive searching
if (pKeyVal.$ne) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (arrIndex !== pKeyVal.$ne) {
result.push(this._data[arrIndex]);
}
}
}
return result;
}
if (pKeyVal.$in && (pKeyVal.$in instanceof Array)) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (pKeyVal.$in.indexOf(arrIndex) > -1) {
result.push(this._data[arrIndex]);
}
}
}
return result;
}
if (pKeyVal.$nin && (pKeyVal.$nin instanceof Array)) {
// Create new data
result = [];
for (arrIndex in this._data) {
if (this._data.hasOwnProperty(arrIndex)) {
if (pKeyVal.$nin.indexOf(arrIndex) === -1) {
result.push(this._data[arrIndex]);
}
}
}
return result;
}
if (pKeyVal.$or && (pKeyVal.$or instanceof Array)) {
// Create new data
result = [];
for (arrIndex = 0; arrIndex < pKeyVal.$or.length; arrIndex++) {
result = result.concat(this.lookup(pKeyVal.$or[arrIndex]));
}
return result;
}
} else {
// Key is a basic lookup from string
lookupItem = this._data[pKeyVal];
if (lookupItem !== undefined) {
return [lookupItem];
} else {
return [];
}
}
};
/**
* Removes data for the given key from the store.
* @param {String} key The key to un-set.
* @returns {*}
*/
KeyValueStore.prototype.unSet = function (key) {
delete this._data[key];
return this;
};
/**
* Sets data for the give key in the store only where the given key
* does not already have a value in the store.
* @param {String} key The key to set data for.
* @param {*} value The value to assign to the key.
* @returns {Boolean} True if data was set or false if data already
* exists for the key.
*/
KeyValueStore.prototype.uniqueSet = function (key, value) {
if (this._data[key] === undefined) {
this._data[key] = value;
return true;
}
return false;
};
Shared.finishModule('KeyValueStore');
module.exports = KeyValueStore;
},{"./Shared":37}],15:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Operation = _dereq_('./Operation');
/**
* The metrics class used to store details about operations.
* @constructor
*/
var Metrics = function () {
this.init.apply(this, arguments);
};
Metrics.prototype.init = function () {
this._data = [];
};
Shared.addModule('Metrics', Metrics);
Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor');
/**
* Creates an operation within the metrics instance and if metrics
* are currently enabled (by calling the start() method) the operation
* is also stored in the metrics log.
* @param {String} name The name of the operation.
* @returns {Operation}
*/
Metrics.prototype.create = function (name) {
var op = new Operation(name);
if (this._enabled) {
this._data.push(op);
}
return op;
};
/**
* Starts logging operations.
* @returns {Metrics}
*/
Metrics.prototype.start = function () {
this._enabled = true;
return this;
};
/**
* Stops logging operations.
* @returns {Metrics}
*/
Metrics.prototype.stop = function () {
this._enabled = false;
return this;
};
/**
* Clears all logged operations.
* @returns {Metrics}
*/
Metrics.prototype.clear = function () {
this._data = [];
return this;
};
/**
* Returns an array of all logged operations.
* @returns {Array}
*/
Metrics.prototype.list = function () {
return this._data;
};
Shared.finishModule('Metrics');
module.exports = Metrics;
},{"./Operation":28,"./Shared":37}],16:[function(_dereq_,module,exports){
"use strict";
var CRUD = {
preSetData: function () {
},
postSetData: function () {
}
};
module.exports = CRUD;
},{}],17:[function(_dereq_,module,exports){
"use strict";
/**
* The chain reactor mixin, provides methods to the target object that allow chain
* reaction events to propagate to the target and be handled, processed and passed
* on down the chain.
* @mixin
*/
var ChainReactor = {
/**
*
* @param obj
*/
chain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list');
}
}
this._chain = this._chain || [];
var index = this._chain.indexOf(obj);
if (index === -1) {
this._chain.push(obj);
}
},
unChain: function (obj) {
if (this.debug && this.debug()) {
if (obj._reactorIn && obj._reactorOut) {
console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list');
} else {
console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list');
}
}
if (this._chain) {
var index = this._chain.indexOf(obj);
if (index > -1) {
this._chain.splice(index, 1);
}
}
},
chainSend: function (type, data, options) {
if (this._chain) {
var arr = this._chain,
arrItem,
count = arr.length,
index;
for (index = 0; index < count; index++) {
arrItem = arr[index];
if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) {
if (this.debug && this.debug()) {
if (arrItem._reactorIn && arrItem._reactorOut) {
console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"');
} else {
console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"');
}
}
arrItem.chainReceive(this, type, data, options);
} else {
console.log('Reactor Data:', type, data, options);
console.log('Reactor Node:', arrItem);
throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!');
}
}
}
},
chainReceive: function (sender, type, data, options) {
var chainPacket = {
sender: sender,
type: type,
data: data,
options: options
};
if (this.debug && this.debug()) {
console.log(this.logIdentifier() + 'Received data from parent reactor node');
}
// Fire our internal handler
if (!this._chainHandler || (this._chainHandler && !this._chainHandler(chainPacket))) {
// Propagate the message down the chain
this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options);
}
}
};
module.exports = ChainReactor;
},{}],18:[function(_dereq_,module,exports){
"use strict";
var idCounter = 0,
Overload = _dereq_('./Overload'),
Serialiser = _dereq_('./Serialiser'),
Common,
serialiser = new Serialiser();
/**
* Provides commonly used methods to most classes in ForerunnerDB.
* @mixin
*/
Common = {
// Expose the serialiser object so it can be extended with new data handlers.
serialiser: serialiser,
/**
* Gets / sets data in the item store. The store can be used to set and
* retrieve data against a key. Useful for adding arbitrary key/value data
* to a collection / view etc and retrieving it later.
* @param {String|*} key The key under which to store the passed value or
* retrieve the existing stored value.
* @param {*=} val Optional value. If passed will overwrite the existing value
* stored against the specified key if one currently exists.
* @returns {*}
*/
store: function (key, val) {
if (key !== undefined) {
if (val !== undefined) {
// Store the data
this._store = this._store || {};
this._store[key] = val;
return this;
}
if (this._store) {
return this._store[key];
}
}
return undefined;
},
/**
* Removes a previously stored key/value pair from the item store, set previously
* by using the store() method.
* @param {String|*} key The key of the key/value pair to remove;
* @returns {Common} Returns this for chaining.
*/
unStore: function (key) {
if (key !== undefined) {
delete this._store[key];
}
return this;
},
/**
* Returns a non-referenced version of the passed object / array.
* @param {Object} data The object or array to return as a non-referenced version.
* @param {Number=} copies Optional number of copies to produce. If specified, the return
* value will be an array of decoupled objects, each distinct from the other.
* @returns {*}
*/
decouple: function (data, copies) {
if (data !== undefined) {
if (!copies) {
return this.jParse(this.jStringify(data));
} else {
var i,
json = this.jStringify(data),
copyArr = [];
for (i = 0; i < copies; i++) {
copyArr.push(this.jParse(json));
}
return copyArr;
}
}
return undefined;
},
/**
* Parses and returns data from stringified version.
* @param {String} data The stringified version of data to parse.
* @returns {Object} The parsed JSON object from the data.
*/
jParse: function (data) {
return serialiser.parse(data);
//return JSON.parse(data);
},
/**
* Converts a JSON object into a stringified version.
* @param {Object} data The data to stringify.
* @returns {String} The stringified data.
*/
jStringify: function (data) {
return serialiser.stringify(data);
//return JSON.stringify(data);
},
/**
* Generates a new 16-character hexadecimal unique ID or
* generates a new 16-character hexadecimal ID based on
* the passed string. Will always generate the same ID
* for the same string.
* @param {String=} str A string to generate the ID from.
* @return {String}
*/
objectId: function (str) {
var id,
pow = Math.pow(10, 17);
if (!str) {
idCounter++;
id = (idCounter + (
Math.random() * pow +
Math.random() * pow +
Math.random() * pow +
Math.random() * pow
)).toString(16);
} else {
var val = 0,
count = str.length,
i;
for (i = 0; i < count; i++) {
val += str.charCodeAt(i) * pow;
}
id = val.toString(16);
}
return id;
},
/**
* Gets / sets debug flag that can enable debug message output to the
* console if required.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
/**
* Sets debug flag for a particular type that can enable debug message
* output to the console if required.
* @param {String} type The name of the debug type to set flag for.
* @param {Boolean} val The value to set debug flag to.
* @return {Boolean} True if enabled, false otherwise.
*/
debug: new Overload([
function () {
return this._debug && this._debug.all;
},
function (val) {
if (val !== undefined) {
if (typeof val === 'boolean') {
this._debug = this._debug || {};
this._debug.all = val;
this.chainSend('debug', this._debug);
return this;
} else {
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all);
}
}
return this._debug && this._debug.all;
},
function (type, val) {
if (type !== undefined) {
if (val !== undefined) {
this._debug = this._debug || {};
this._debug[type] = val;
this.chainSend('debug', this._debug);
return this;
}
return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]);
}
return this._debug && this._debug.all;
}
]),
/**
* Returns a string describing the class this instance is derived from.
* @returns {string}
*/
classIdentifier: function () {
return 'ForerunnerDB.' + this.className;
},
/**
* Returns a string describing the instance by it's class name and instance
* object name.
* @returns {String} The instance identifier.
*/
instanceIdentifier: function () {
return '[' + this.className + ']' + this.name();
},
/**
* Returns a string used to denote a console log against this instance,
* consisting of the class identifier and instance identifier.
* @returns {string} The log identifier.
*/
logIdentifier: function () {
return this.classIdentifier() + ': ' + this.instanceIdentifier();
},
/**
* Converts a query object with MongoDB dot notation syntax
* to Forerunner's object notation syntax.
* @param {Object} obj The object to convert.
*/
convertToFdb: function (obj) {
var varName,
splitArr,
objCopy,
i;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
objCopy = obj;
if (i.indexOf('.') > -1) {
// Replace .$ with a placeholder before splitting by . char
i = i.replace('.$', '[|$|]');
splitArr = i.split('.');
while ((varName = splitArr.shift())) {
// Replace placeholder back to original .$
varName = varName.replace('[|$|]', '.$');
if (splitArr.length) {
objCopy[varName] = {};
} else {
objCopy[varName] = obj[i];
}
objCopy = objCopy[varName];
}
delete obj[i];
}
}
}
},
/**
* Checks if the state is dropped.
* @returns {boolean} True when dropped, false otherwise.
*/
isDropped: function () {
return this._state === 'dropped';
}
};
module.exports = Common;
},{"./Overload":29,"./Serialiser":36}],19:[function(_dereq_,module,exports){
"use strict";
/**
* Provides some database constants.
* @mixin
*/
var Constants = {
TYPE_INSERT: 0,
TYPE_UPDATE: 1,
TYPE_REMOVE: 2,
PHASE_BEFORE: 0,
PHASE_AFTER: 1
};
module.exports = Constants;
},{}],20:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* Provides event emitter functionality including the methods: on, off, once, emit, deferEmit.
* @mixin
*/
var Events = {
on: new Overload({
/**
* Attach an event listener to the passed event.
* @param {String} event The name of the event to listen for.
* @param {Function} listener The method to call when the event is fired.
*/
'string, function': function (event, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event]['*'] = this._listeners[event]['*'] || [];
this._listeners[event]['*'].push(listener);
return this;
},
/**
* Attach an event listener to the passed event only if the passed
* id matches the document id for the event being fired.
* @param {String} event The name of the event to listen for.
* @param {*} id The document id to match against.
* @param {Function} listener The method to call when the event is fired.
*/
'string, *, function': function (event, id, listener) {
this._listeners = this._listeners || {};
this._listeners[event] = this._listeners[event] || {};
this._listeners[event][id] = this._listeners[event][id] || [];
this._listeners[event][id].push(listener);
return this;
}
}),
once: new Overload({
'string, function': function (eventName, callback) {
var self = this,
internalCallback = function () {
self.off(eventName, internalCallback);
callback.apply(self, arguments);
};
return this.on(eventName, internalCallback);
},
'string, *, function': function (eventName, id, callback) {
var self = this,
internalCallback = function () {
self.off(eventName, id, internalCallback);
callback.apply(self, arguments);
};
return this.on(eventName, id, internalCallback);
}
}),
off: new Overload({
'string': function (event) {
if (this._listeners && this._listeners[event] && event in this._listeners) {
delete this._listeners[event];
}
return this;
},
'string, function': function (event, listener) {
var arr,
index;
if (typeof(listener) === 'string') {
if (this._listeners && this._listeners[event] && this._listeners[event][listener]) {
delete this._listeners[event][listener];
}
} else {
if (this._listeners && event in this._listeners) {
arr = this._listeners[event]['*'];
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
}
return this;
},
'string, *, function': function (event, id, listener) {
if (this._listeners && event in this._listeners && id in this.listeners[event]) {
var arr = this._listeners[event][id],
index = arr.indexOf(listener);
if (index > -1) {
arr.splice(index, 1);
}
}
},
'string, *': function (event, id) {
if (this._listeners && event in this._listeners && id in this._listeners[event]) {
// Kill all listeners for this event id
delete this._listeners[event][id];
}
}
}),
emit: function (event, data) {
this._listeners = this._listeners || {};
if (event in this._listeners) {
var arrIndex,
arrCount,
tmpFunc,
arr,
listenerIdArr,
listenerIdCount,
listenerIdIndex;
// Handle global emit
if (this._listeners[event]['*']) {
arr = this._listeners[event]['*'];
arrCount = arr.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
// Check we have a function to execute
tmpFunc = arr[arrIndex];
if (typeof tmpFunc === 'function') {
tmpFunc.apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
// Handle individual emit
if (data instanceof Array) {
// Check if the array is an array of objects in the collection
if (data[0] && data[0][this._primaryKey]) {
// Loop the array and check for listeners against the primary key
listenerIdArr = this._listeners[event];
arrCount = data.length;
for (arrIndex = 0; arrIndex < arrCount; arrIndex++) {
if (listenerIdArr[data[arrIndex][this._primaryKey]]) {
// Emit for this id
listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length;
for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) {
tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex];
if (typeof tmpFunc === 'function') {
listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1));
}
}
}
}
}
}
}
return this;
},
/**
* Queues an event to be fired. This has automatic de-bouncing so that any
* events of the same type that occur within 100 milliseconds of a previous
* one will all be wrapped into a single emit rather than emitting tons of
* events for lots of chained inserts etc. Only the data from the last
* de-bounced event will be emitted.
* @param {String} eventName The name of the event to emit.
* @param {*=} data Optional data to emit with the event.
*/
deferEmit: function (eventName, data) {
var self = this,
args;
if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) {
args = arguments;
// Check for an existing timeout
this._deferTimeout = this._deferTimeout || {};
if (this._deferTimeout[eventName]) {
clearTimeout(this._deferTimeout[eventName]);
}
// Set a timeout
this._deferTimeout[eventName] = setTimeout(function () {
if (self.debug()) {
console.log(self.logIdentifier() + ' Emitting ' + args[0]);
}
self.emit.apply(self, args);
}, 1);
} else {
this.emit.apply(this, arguments);
}
return this;
}
};
module.exports = Events;
},{"./Overload":29}],21:[function(_dereq_,module,exports){
"use strict";
/**
* Provides object matching algorithm methods.
* @mixin
*/
var Matching = {
/**
* Internal method that checks a document against a test object.
* @param {*} source The source object or value to test against.
* @param {*} test The test object or value to test with.
* @param {Object} queryOptions The options the query was passed with.
* @param {String=} opToApply The special operation to apply to the test such
* as 'and' or an 'or' operator.
* @param {Object=} options An object containing options to apply to the
* operation such as limiting the fields returned etc.
* @returns {Boolean} True if the test was positive, false on negative.
* @private
*/
_match: function (source, test, queryOptions, opToApply, options) {
// TODO: This method is quite long, break into smaller pieces
var operation,
applyOp = opToApply,
recurseVal,
tmpIndex,
sourceType = typeof source,
testType = typeof test,
matchedAll = true,
opResult,
substringCache,
i;
options = options || {};
queryOptions = queryOptions || {};
// Check if options currently holds a root query object
if (!options.$rootQuery) {
// Root query not assigned, hold the root query
options.$rootQuery = test;
}
options.$rootData = options.$rootData || {};
// Check if the comparison data are both strings or numbers
if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) {
// The source and test data are flat types that do not require recursive searches,
// so just compare them and return the result
if (sourceType === 'number') {
// Number comparison
if (source !== test) {
matchedAll = false;
}
} else {
// String comparison
// TODO: We can probably use a queryOptions.$locale as a second parameter here
// TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35
if (source.localeCompare(test)) {
matchedAll = false;
}
}
} else {
for (i in test) {
if (test.hasOwnProperty(i)) {
// Reset operation flag
operation = false;
substringCache = i.substr(0, 2);
// Check if the property is a comment (ignorable)
if (substringCache === '//') {
// Skip this property
continue;
}
// Check if the property starts with a dollar (function)
if (substringCache.indexOf('$') === 0) {
// Ask the _matchOp method to handle the operation
opResult = this._matchOp(i, source, test[i], queryOptions, options);
// Check the result of the matchOp operation
// If the result is -1 then no operation took place, otherwise the result
// will be a boolean denoting a match (true) or no match (false)
if (opResult > -1) {
if (opResult) {
if (opToApply === 'or') {
return true;
}
} else {
// Set the matchedAll flag to the result of the operation
// because the operation did not return true
matchedAll = opResult;
}
// Record that an operation was handled
operation = true;
}
}
// Check for regex
if (!operation && test[i] instanceof RegExp) {
operation = true;
if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
if (!operation) {
// Check if our query is an object
if (typeof(test[i]) === 'object') {
// Because test[i] is an object, source must also be an object
// Check if our source data we are checking the test query against
// is an object or an array
if (source[i] !== undefined) {
if (source[i] instanceof Array && !(test[i] instanceof Array)) {
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (!(source[i] instanceof Array) && test[i] instanceof Array) {
// The test key data is an array and the source key data is not so check
// each item in the test key data to see if the source item matches one
// of them. This is effectively an $in search.
recurseVal = false;
for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) {
recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else if (typeof(source) === 'object') {
// Recurse down the object tree
recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
}
} else {
// First check if the test match is an $exists
if (test[i] && test[i].$exists !== undefined) {
// Push the item through another match recurse
recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options);
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
} else {
// Check if the prop matches our test value
if (source && source[i] === test[i]) {
if (opToApply === 'or') {
return true;
}
} else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") {
// We are looking for a value inside an array
// The source data is an array, so check each item until a
// match is found
recurseVal = false;
for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) {
recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options);
if (recurseVal) {
// One of the array items matched the query so we can
// include this item in the results, so break now
break;
}
}
if (recurseVal) {
if (opToApply === 'or') {
return true;
}
} else {
matchedAll = false;
}
} else {
matchedAll = false;
}
}
}
if (opToApply === 'and' && !matchedAll) {
return false;
}
}
}
}
return matchedAll;
},
/**
* Internal method, performs a matching process against a query operator such as $gt or $nin.
* @param {String} key The property name in the test that matches the operator to perform
* matching against.
* @param {*} source The source data to match the query against.
* @param {*} test The query to match the source against.
* @param {Object=} options An options object.
* @returns {*}
* @private
*/
_matchOp: function (key, source, test, queryOptions, options) {
// Check for commands
switch (key) {
case '$gt':
// Greater than
return source > test;
case '$gte':
// Greater than or equal
return source >= test;
case '$lt':
// Less than
return source < test;
case '$lte':
// Less than or equal
return source <= test;
case '$exists':
// Property exists
return (source === undefined) !== test;
case '$ne': // Not equals
return source != test; // jshint ignore:line
case '$nee': // Not equals equals
return source !== test;
case '$or':
// Match true on ANY check to pass
for (var orIndex = 0; orIndex < test.length; orIndex++) {
if (this._match(source, test[orIndex], queryOptions, 'and', options)) {
return true;
}
}
return false;
case '$and':
// Match true on ALL checks to pass
for (var andIndex = 0; andIndex < test.length; andIndex++) {
if (!this._match(source, test[andIndex], queryOptions, 'and', options)) {
return false;
}
}
return true;
case '$in': // In
// Check that the in test is an array
if (test instanceof Array) {
var inArr = test,
inArrCount = inArr.length,
inArrIndex;
for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) {
if (inArr[inArrIndex] instanceof RegExp && inArr[inArrIndex].test(source)) {
return true;
} else if (inArr[inArrIndex] === source) {
return true;
}
}
return false;
} else {
throw(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key);
}
break;
case '$nin': // Not in
// Check that the not-in test is an array
if (test instanceof Array) {
var notInArr = test,
notInArrCount = notInArr.length,
notInArrIndex;
for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) {
if (notInArr[notInArrIndex] === source) {
return false;
}
}
return true;
} else {
throw(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key);
}
break;
case '$distinct':
// Ensure options holds a distinct lookup
options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {};
for (var distinctProp in test) {
if (test.hasOwnProperty(distinctProp)) {
options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {};
// Check if the options distinct lookup has this field's value
if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) {
// Value is already in use
return false;
} else {
// Set the value in the lookup
options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true;
// Allow the item in the results
return true;
}
}
}
break;
case '$count':
var countKey,
countArr,
countVal;
// Iterate the count object's keys
for (countKey in test) {
if (test.hasOwnProperty(countKey)) {
// Check the property exists and is an array. If the property being counted is not
// an array (or doesn't exist) then use a value of zero in any further count logic
countArr = source[countKey];
if (typeof countArr === 'object' && countArr instanceof Array) {
countVal = countArr.length;
} else {
countVal = 0;
}
// Now recurse down the query chain further to satisfy the query for this key (countKey)
if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) {
return false;
}
}
}
// Allow the item in the results
return true;
}
return -1;
}
};
module.exports = Matching;
},{}],22:[function(_dereq_,module,exports){
"use strict";
/**
* Provides sorting methods.
* @mixin
*/
var Sorting = {
/**
* Sorts the passed value a against the passed value b ascending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortAsc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return a.localeCompare(b);
} else {
if (a > b) {
return 1;
} else if (a < b) {
return -1;
}
}
return 0;
},
/**
* Sorts the passed value a against the passed value b descending.
* @param {*} a The first value to compare.
* @param {*} b The second value to compare.
* @returns {*} 1 if a is sorted after b, -1 if a is sorted before b.
*/
sortDesc: function (a, b) {
if (typeof(a) === 'string' && typeof(b) === 'string') {
return b.localeCompare(a);
} else {
if (a > b) {
return -1;
} else if (a < b) {
return 1;
}
}
return 0;
}
};
module.exports = Sorting;
},{}],23:[function(_dereq_,module,exports){
"use strict";
var Tags,
tagMap = {};
/**
* Provides class instance tagging and tag operation methods.
* @mixin
*/
Tags = {
/**
* Tags a class instance for later lookup.
* @param {String} name The tag to add.
* @returns {boolean}
*/
tagAdd: function (name) {
var i,
self = this,
mapArr = tagMap[name] = tagMap[name] || [];
for (i = 0; i < mapArr.length; i++) {
if (mapArr[i] === self) {
return true;
}
}
mapArr.push(self);
// Hook the drop event for this so we can react
if (self.on) {
self.on('drop', function () {
// We've been dropped so remove ourselves from the tag map
self.tagRemove(name);
});
}
return true;
},
/**
* Removes a tag from a class instance.
* @param {String} name The tag to remove.
* @returns {boolean}
*/
tagRemove: function (name) {
var i,
mapArr = tagMap[name];
if (mapArr) {
for (i = 0; i < mapArr.length; i++) {
if (mapArr[i] === this) {
mapArr.splice(i, 1);
return true;
}
}
}
return false;
},
/**
* Gets an array of all instances tagged with the passed tag name.
* @param {String} name The tag to lookup.
* @returns {Array} The array of instances that have the passed tag.
*/
tagLookup: function (name) {
return tagMap[name] || [];
},
/**
* Drops all instances that are tagged with the passed tag name.
* @param {String} name The tag to lookup.
* @param {Function} callback Callback once dropping has completed
* for all instances that match the passed tag name.
* @returns {boolean}
*/
tagDrop: function (name, callback) {
var arr = this.tagLookup(name),
dropCb,
dropCount,
i;
dropCb = function () {
dropCount--;
if (callback && dropCount === 0) {
callback(false);
}
};
if (arr.length) {
dropCount = arr.length;
// Loop the array and drop all items
for (i = arr.length - 1; i >= 0; i--) {
arr[i].drop(dropCb);
}
}
return true;
}
};
module.exports = Tags;
},{}],24:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* Provides trigger functionality methods.
* @mixin
*/
var Triggers = {
/**
* Add a trigger by id.
* @param {String} id The id of the trigger. This must be unique to the type and
* phase of the trigger. Only one trigger may be added with this id per type and
* phase.
* @param {Number} type The type of operation to apply the trigger to. See
* Mixin.Constants for constants to use.
* @param {Number} phase The phase of an operation to fire the trigger on. See
* Mixin.Constants for constants to use.
* @param {Function} method The method to call when the trigger is fired.
* @returns {boolean} True if the trigger was added successfully, false if not.
*/
addTrigger: function (id, type, phase, method) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex === -1) {
// The trigger does not exist, create it
self._trigger = self._trigger || {};
self._trigger[type] = self._trigger[type] || {};
self._trigger[type][phase] = self._trigger[type][phase] || [];
self._trigger[type][phase].push({
id: id,
method: method,
enabled: true
});
return true;
}
return false;
},
/**
*
* @param {String} id The id of the trigger to remove.
* @param {Number} type The type of operation to remove the trigger from. See
* Mixin.Constants for constants to use.
* @param {Number} phase The phase of the operation to remove the trigger from.
* See Mixin.Constants for constants to use.
* @returns {boolean} True if removed successfully, false if not.
*/
removeTrigger: function (id, type, phase) {
var self = this,
triggerIndex;
// Check if the trigger already exists
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// The trigger exists, remove it
self._trigger[type][phase].splice(triggerIndex, 1);
}
return false;
},
enableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = true;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to enabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = true;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = true;
return true;
}
return false;
}
}),
disableTrigger: new Overload({
'string': function (id) {
// Alter all triggers of this type
var self = this,
types = self._trigger,
phases,
triggers,
result = false,
i, k, j;
if (types) {
for (j in types) {
if (types.hasOwnProperty(j)) {
phases = types[j];
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set enabled flag
for (k = 0; k < triggers.length; k++) {
if (triggers[k].id === id) {
triggers[k].enabled = false;
result = true;
}
}
}
}
}
}
}
}
return result;
},
'number': function (type) {
// Alter all triggers of this type
var self = this,
phases = self._trigger[type],
triggers,
result = false,
i, k;
if (phases) {
for (i in phases) {
if (phases.hasOwnProperty(i)) {
triggers = phases[i];
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
}
return result;
},
'number, number': function (type, phase) {
// Alter all triggers of this type and phase
var self = this,
phases = self._trigger[type],
triggers,
result = false,
k;
if (phases) {
triggers = phases[phase];
if (triggers) {
// Loop triggers and set to disabled
for (k = 0; k < triggers.length; k++) {
triggers[k].enabled = false;
result = true;
}
}
}
return result;
},
'string, number, number': function (id, type, phase) {
// Check if the trigger already exists
var self = this,
triggerIndex = self._triggerIndexOf(id, type, phase);
if (triggerIndex > -1) {
// Update the trigger
self._trigger[type][phase][triggerIndex].enabled = false;
return true;
}
return false;
}
}),
/**
* Checks if a trigger will fire based on the type and phase provided.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {Boolean} True if the trigger will fire, false otherwise.
*/
willTrigger: function (type, phase) {
if (this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) {
// Check if a trigger in this array is enabled
var arr = this._trigger[type][phase],
i;
for (i = 0; i < arr.length; i++) {
if (arr[i].enabled) {
return true;
}
}
}
return false;
},
/**
* Processes trigger actions based on the operation, type and phase.
* @param {Object} operation Operation data to pass to the trigger.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @param {Object} oldDoc The document snapshot before operations are
* carried out against the data.
* @param {Object} newDoc The document snapshot after operations are
* carried out against the data.
* @returns {boolean}
*/
processTrigger: function (operation, type, phase, oldDoc, newDoc) {
var self = this,
triggerArr,
triggerIndex,
triggerCount,
triggerItem,
response;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
triggerItem = triggerArr[triggerIndex];
// Check if the trigger is enabled
if (triggerItem.enabled) {
if (this.debug()) {
var typeName,
phaseName;
switch (type) {
case this.TYPE_INSERT:
typeName = 'insert';
break;
case this.TYPE_UPDATE:
typeName = 'update';
break;
case this.TYPE_REMOVE:
typeName = 'remove';
break;
default:
typeName = '';
break;
}
switch (phase) {
case this.PHASE_BEFORE:
phaseName = 'before';
break;
case this.PHASE_AFTER:
phaseName = 'after';
break;
default:
phaseName = '';
break;
}
//console.log('Triggers: Processing trigger "' + id + '" for ' + typeName + ' in phase "' + phaseName + '"');
}
// Run the trigger's method and store the response
response = triggerItem.method.call(self, operation, oldDoc, newDoc);
// Check the response for a non-expected result (anything other than
// undefined, true or false is considered a throwable error)
if (response === false) {
// The trigger wants us to cancel operations
return false;
}
if (response !== undefined && response !== true && response !== false) {
// Trigger responded with error, throw the error
throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response);
}
}
}
// Triggers all ran without issue, return a success (true)
return true;
}
},
/**
* Returns the index of a trigger by id based on type and phase.
* @param {String} id The id of the trigger to find the index of.
* @param {Number} type The type of operation. See Mixin.Constants for
* constants to use.
* @param {Number} phase The phase of the operation. See Mixin.Constants
* for constants to use.
* @returns {number}
* @private
*/
_triggerIndexOf: function (id, type, phase) {
var self = this,
triggerArr,
triggerCount,
triggerIndex;
if (self._trigger && self._trigger[type] && self._trigger[type][phase]) {
triggerArr = self._trigger[type][phase];
triggerCount = triggerArr.length;
for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) {
if (triggerArr[triggerIndex].id === id) {
return triggerIndex;
}
}
}
return -1;
}
};
module.exports = Triggers;
},{"./Overload":29}],25:[function(_dereq_,module,exports){
"use strict";
/**
* Provides methods to handle object update operations.
* @mixin
*/
var Updating = {
/**
* Updates a property on an object.
* @param {Object} doc The object whose property is to be updated.
* @param {String} prop The property to update.
* @param {*} val The new value of the property.
* @private
*/
_updateProperty: function (doc, prop, val) {
doc[prop] = val;
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '"');
}
},
/**
* Increments a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to increment by.
* @private
*/
_updateIncrement: function (doc, prop, val) {
doc[prop] += val;
},
/**
* Changes the index of an item in the passed array.
* @param {Array} arr The array to modify.
* @param {Number} indexFrom The index to move the item from.
* @param {Number} indexTo The index to move the item to.
* @private
*/
_updateSpliceMove: function (arr, indexFrom, indexTo) {
arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]);
if (this.debug()) {
console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"');
}
},
/**
* Inserts an item into the passed array at the specified index.
* @param {Array} arr The array to insert into.
* @param {Number} index The index to insert at.
* @param {Object} doc The document to insert.
* @private
*/
_updateSplicePush: function (arr, index, doc) {
if (arr.length > index) {
arr.splice(index, 0, doc);
} else {
arr.push(doc);
}
},
/**
* Inserts an item at the end of an array.
* @param {Array} arr The array to insert the item into.
* @param {Object} doc The document to insert.
* @private
*/
_updatePush: function (arr, doc) {
arr.push(doc);
},
/**
* Removes an item from the passed array.
* @param {Array} arr The array to modify.
* @param {Number} index The index of the item in the array to remove.
* @private
*/
_updatePull: function (arr, index) {
arr.splice(index, 1);
},
/**
* Multiplies a value for a property on a document by the passed number.
* @param {Object} doc The document to modify.
* @param {String} prop The property to modify.
* @param {Number} val The amount to multiply by.
* @private
*/
_updateMultiply: function (doc, prop, val) {
doc[prop] *= val;
},
/**
* Renames a property on a document to the passed property.
* @param {Object} doc The document to modify.
* @param {String} prop The property to rename.
* @param {Number} val The new property name.
* @private
*/
_updateRename: function (doc, prop, val) {
doc[val] = doc[prop];
delete doc[prop];
},
/**
* Sets a property on a document to the passed value.
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @param {*} val The new property value.
* @private
*/
_updateOverwrite: function (doc, prop, val) {
doc[prop] = val;
},
/**
* Deletes a property on a document.
* @param {Object} doc The document to modify.
* @param {String} prop The property to delete.
* @private
*/
_updateUnset: function (doc, prop) {
delete doc[prop];
},
/**
* Removes all properties from an object without destroying
* the object instance, thereby maintaining data-bound linking.
* @param {Object} doc The parent object to modify.
* @param {String} prop The name of the child object to clear.
* @private
*/
_updateClear: function (doc, prop) {
var obj = doc[prop],
i;
if (obj && typeof obj === 'object') {
for (i in obj) {
if (obj.hasOwnProperty(i)) {
this._updateUnset(obj, i);
}
}
}
},
/**
* Pops an item or items from the array stack.
* @param {Object} doc The document to modify.
* @param {Number} val If set to a positive integer, will pop the number specified
* from the stack, if set to a negative integer will shift the number specified
* from the stack.
* @return {Boolean}
* @private
*/
_updatePop: function (doc, val) {
var updated = false,
i;
if (doc.length > 0) {
if (val > 0) {
for (i = 0; i < val; i++) {
doc.pop();
}
updated = true;
} else if (val < 0) {
for (i = 0; i > val; i--) {
doc.shift();
}
updated = true;
}
}
return updated;
}
};
module.exports = Updating;
},{}],26:[function(_dereq_,module,exports){
"use strict";
// Grab the view class
var Shared,
Core,
OldView,
OldViewInit;
Shared = _dereq_('./Shared');
Core = Shared.modules.Core;
OldView = Shared.modules.OldView;
OldViewInit = OldView.prototype.init;
OldView.prototype.init = function () {
var self = 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
};
OldViewInit.apply(this, arguments);
// Hook view events to update binds
this.on('insert', function (successArr, failArr) {
self._bindEvent('insert', successArr, failArr);
});
this.on('update', function (successArr, failArr) {
self._bindEvent('update', successArr, failArr);
});
this.on('remove', function (successArr, failArr) {
self._bindEvent('remove', successArr, failArr);
});
this.on('change', self._bindChange);
};
/**
* Binds a selector to the insert, update and delete events of a particular
* view and keeps the selector in sync so that updates are reflected on the
* web page in real-time.
*
* @param {String} selector The jQuery selector string to get target elements.
* @param {Object} options The options object.
*/
OldView.prototype.bind = function (selector, options) {
if (options && options.template) {
this._binds[selector] = options;
} else {
throw('ForerunnerDB.OldView "' + this.name() + '": Cannot bind data to element, missing options information!');
}
return this;
};
/**
* Un-binds a selector from the view changes.
* @param {String} selector The jQuery selector string to identify the bind to remove.
* @returns {Collection}
*/
OldView.prototype.unBind = function (selector) {
delete this._binds[selector];
return this;
};
/**
* Returns true if the selector is bound to the view.
* @param {String} selector The jQuery selector string to identify the bind to check for.
* @returns {boolean}
*/
OldView.prototype.isBound = function (selector) {
return Boolean(this._binds[selector]);
};
/**
* Sorts items in the DOM based on the bind settings and the passed item array.
* @param {String} selector The jQuery selector of the bind container.
* @param {Array} itemArr The array of items used to determine the order the DOM
* elements should be in based on the order they are in, in the array.
*/
OldView.prototype.bindSortDom = function (selector, itemArr) {
var container = window.jQuery(selector),
arrIndex,
arrItem,
domItem;
if (this.debug()) {
console.log('ForerunnerDB.OldView.Bind: Sorting data in DOM...', itemArr);
}
for (arrIndex = 0; arrIndex < itemArr.length; arrIndex++) {
arrItem = itemArr[arrIndex];
// Now we've done our inserts into the DOM, let's ensure
// they are still ordered correctly
domItem = container.find('#' + arrItem[this._primaryKey]);
if (domItem.length) {
if (arrIndex === 0) {
if (this.debug()) {
console.log('ForerunnerDB.OldView.Bind: Sort, moving to index 0...', domItem);
}
container.prepend(domItem);
} else {
if (this.debug()) {
console.log('ForerunnerDB.OldView.Bind: Sort, moving to index ' + arrIndex + '...', domItem);
}
domItem.insertAfter(container.children(':eq(' + (arrIndex - 1) + ')'));
}
} else {
if (this.debug()) {
console.log('ForerunnerDB.OldView.Bind: Warning, element for array item not found!', arrItem);
}
}
}
};
OldView.prototype.bindRefresh = function (obj) {
var binds = this._binds,
bindKey,
bind;
if (!obj) {
// Grab current data
obj = {
data: this.find()
};
}
for (bindKey in binds) {
if (binds.hasOwnProperty(bindKey)) {
bind = binds[bindKey];
if (this.debug()) { console.log('ForerunnerDB.OldView.Bind: Sorting DOM...'); }
this.bindSortDom(bindKey, obj.data);
if (bind.afterOperation) {
bind.afterOperation();
}
if (bind.refresh) {
bind.refresh();
}
}
}
};
/**
* Renders a bind view data to the DOM.
* @param {String} bindSelector The jQuery selector string to use to identify
* the bind target. Must match the selector used when defining the original bind.
* @param {Function=} domHandler If specified, this handler method will be called
* with the final HTML for the view instead of the DB handling the DOM insertion.
*/
OldView.prototype.bindRender = function (bindSelector, domHandler) {
// Check the bind exists
var bind = this._binds[bindSelector],
domTarget = window.jQuery(bindSelector),
allData,
dataItem,
itemHtml,
finalHtml = window.jQuery('<ul></ul>'),
bindCallback,
i;
if (bind) {
allData = this._data.find();
bindCallback = function (itemHtml) {
finalHtml.append(itemHtml);
};
// Loop all items and add them to the screen
for (i = 0; i < allData.length; i++) {
dataItem = allData[i];
itemHtml = bind.template(dataItem, bindCallback);
}
if (!domHandler) {
domTarget.append(finalHtml.html());
} else {
domHandler(bindSelector, finalHtml.html());
}
}
};
OldView.prototype.processQueue = function (type, callback) {
var queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type];
if (queue.length) {
var self = this,
dataArr;
// Process items up to the threshold
if (queue.length) {
if (queue.length > deferThreshold) {
// Grab items up to the threshold value
dataArr = queue.splice(0, deferThreshold);
} else {
// Grab all the remaining items
dataArr = queue.splice(0, queue.length);
}
this._bindEvent(type, dataArr, []);
}
// Queue another process
setTimeout(function () {
self.processQueue(type, callback);
}, deferTime);
} else {
if (callback) { callback(); }
this.emit('bindQueueComplete');
}
};
OldView.prototype._bindEvent = function (type, successArr, failArr) {
/*var queue = this._deferQueue[type],
deferThreshold = this._deferThreshold[type],
deferTime = this._deferTime[type];*/
var binds = this._binds,
unfilteredDataSet = this.find({}),
filteredDataSet,
bindKey;
// Check if the number of inserts is greater than the defer threshold
/*if (successArr && successArr.length > deferThreshold) {
// Break up upsert into blocks
this._deferQueue[type] = queue.concat(successArr);
// Fire off the insert queue handler
this.processQueue(type);
return;
} else {*/
for (bindKey in binds) {
if (binds.hasOwnProperty(bindKey)) {
if (binds[bindKey].reduce) {
filteredDataSet = this.find(binds[bindKey].reduce.query, binds[bindKey].reduce.options);
} else {
filteredDataSet = unfilteredDataSet;
}
switch (type) {
case 'insert':
this._bindInsert(bindKey, binds[bindKey], successArr, failArr, filteredDataSet);
break;
case 'update':
this._bindUpdate(bindKey, binds[bindKey], successArr, failArr, filteredDataSet);
break;
case 'remove':
this._bindRemove(bindKey, binds[bindKey], successArr, failArr, filteredDataSet);
break;
}
}
}
//}
};
OldView.prototype._bindChange = function (newDataArr) {
if (this.debug()) {
console.log('ForerunnerDB.OldView.Bind: Bind data change, refreshing bind...', newDataArr);
}
this.bindRefresh(newDataArr);
};
OldView.prototype._bindInsert = function (selector, options, successArr, failArr, all) {
var container = window.jQuery(selector),
itemElem,
itemHtml,
makeCallback,
i;
makeCallback = function (itemElem, insertedItem, failArr, all) {
return function (itemHtml) {
// Check if there is custom DOM insert method
if (options.insert) {
options.insert(itemHtml, insertedItem, failArr, all);
} else {
// Handle the insert automatically
// Add the item to the container
if (options.prependInsert) {
container.prepend(itemHtml);
} else {
container.append(itemHtml);
}
}
if (options.afterInsert) {
options.afterInsert(itemHtml, insertedItem, failArr, all);
}
};
};
// Loop the inserted items
for (i = 0; i < successArr.length; i++) {
// Check for existing item in the container
itemElem = container.find('#' + successArr[i][this._primaryKey]);
if (!itemElem.length) {
itemHtml = options.template(successArr[i], makeCallback(itemElem, successArr[i], failArr, all));
}
}
};
OldView.prototype._bindUpdate = function (selector, options, successArr, failArr, all) {
var container = window.jQuery(selector),
itemElem,
makeCallback,
i;
makeCallback = function (itemElem, itemData) {
return function (itemHtml) {
// Check if there is custom DOM insert method
if (options.update) {
options.update(itemHtml, itemData, all, itemElem.length ? 'update' : 'append');
} else {
if (itemElem.length) {
// An existing item is in the container, replace it with the
// new rendered item from the updated data
itemElem.replaceWith(itemHtml);
} else {
// The item element does not already exist, append it
if (options.prependUpdate) {
container.prepend(itemHtml);
} else {
container.append(itemHtml);
}
}
}
if (options.afterUpdate) {
options.afterUpdate(itemHtml, itemData, all);
}
};
};
// Loop the updated items
for (i = 0; i < successArr.length; i++) {
// Check for existing item in the container
itemElem = container.find('#' + successArr[i][this._primaryKey]);
options.template(successArr[i], makeCallback(itemElem, successArr[i]));
}
};
OldView.prototype._bindRemove = function (selector, options, successArr, failArr, all) {
var container = window.jQuery(selector),
itemElem,
makeCallback,
i;
makeCallback = function (itemElem, data, all) {
return function () {
if (options.remove) {
options.remove(itemElem, data, all);
} else {
itemElem.remove();
if (options.afterRemove) {
options.afterRemove(itemElem, data, all);
}
}
};
};
// Loop the removed items
for (i = 0; i < successArr.length; i++) {
// Check for existing item in the container
itemElem = container.find('#' + successArr[i][this._primaryKey]);
if (itemElem.length) {
if (options.beforeRemove) {
options.beforeRemove(itemElem, successArr[i], all, makeCallback(itemElem, successArr[i], all));
} else {
if (options.remove) {
options.remove(itemElem, successArr[i], all);
} else {
itemElem.remove();
if (options.afterRemove) {
options.afterRemove(itemElem, successArr[i], all);
}
}
}
}
}
};
},{"./Shared":37}],27:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
CollectionGroup,
Collection,
CollectionInit,
CollectionGroupInit,
DbInit;
Shared = _dereq_('./Shared');
/**
* The view constructor.
* @param viewName
* @constructor
*/
var OldView = function (viewName) {
this.init.apply(this, arguments);
};
OldView.prototype.init = function (viewName) {
var self = this;
this._name = viewName;
this._listeners = {};
this._query = {
query: {},
options: {}
};
// Register listeners for the CRUD events
this._onFromSetData = function () {
self._onSetData.apply(self, arguments);
};
this._onFromInsert = function () {
self._onInsert.apply(self, arguments);
};
this._onFromUpdate = function () {
self._onUpdate.apply(self, arguments);
};
this._onFromRemove = function () {
self._onRemove.apply(self, arguments);
};
this._onFromChange = function () {
if (self.debug()) { console.log('ForerunnerDB.OldView: Received change'); }
self._onChange.apply(self, arguments);
};
};
Shared.addModule('OldView', OldView);
CollectionGroup = _dereq_('./CollectionGroup');
Collection = _dereq_('./Collection');
CollectionInit = Collection.prototype.init;
CollectionGroupInit = CollectionGroup.prototype.init;
Db = Shared.modules.Db;
DbInit = Db.prototype.init;
Shared.mixin(OldView.prototype, 'Mixin.Events');
/**
* Drops a view and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
OldView.prototype.drop = function () {
if ((this._db || this._from) && this._name) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: Dropping view ' + this._name);
}
this._state = 'dropped';
this.emit('drop', this);
if (this._db && this._db._oldViews) {
delete this._db._oldViews[this._name];
}
if (this._from && this._from._oldViews) {
delete this._from._oldViews[this._name];
}
return true;
}
return false;
};
OldView.prototype.debug = function () {
// TODO: Make this function work
return false;
};
/**
* Gets / sets the DB the view is bound against. Automatically set
* when the db.oldView(viewName) method is called.
* @param db
* @returns {*}
*/
OldView.prototype.db = function (db) {
if (db !== undefined) {
this._db = db;
return this;
}
return this._db;
};
/**
* Gets / sets the collection that the view derives it's data from.
* @param {*} collection A collection instance or the name of a collection
* to use as the data set to derive view data from.
* @returns {*}
*/
OldView.prototype.from = function (collection) {
if (collection !== undefined) {
// Check if this is a collection name or a collection instance
if (typeof(collection) === 'string') {
if (this._db.collectionExists(collection)) {
collection = this._db.collection(collection);
} else {
throw('ForerunnerDB.OldView "' + this.name() + '": Invalid collection in view.from() call.');
}
}
// Check if the existing from matches the passed one
if (this._from !== collection) {
// Check if we already have a collection assigned
if (this._from) {
// Remove ourselves from the collection view lookup
this.removeFrom();
}
this.addFrom(collection);
}
return this;
}
return this._from;
};
OldView.prototype.addFrom = function (collection) {
//var self = this;
this._from = collection;
if (this._from) {
this._from.on('setData', this._onFromSetData);
//this._from.on('insert', this._onFromInsert);
//this._from.on('update', this._onFromUpdate);
//this._from.on('remove', this._onFromRemove);
this._from.on('change', this._onFromChange);
// Add this view to the collection's view lookup
this._from._addOldView(this);
this._primaryKey = this._from._primaryKey;
this.refresh();
return this;
} else {
throw('ForerunnerDB.OldView "' + this.name() + '": Cannot determine collection type in view.from()');
}
};
OldView.prototype.removeFrom = function () {
// Unsubscribe from events on this "from"
this._from.off('setData', this._onFromSetData);
//this._from.off('insert', this._onFromInsert);
//this._from.off('update', this._onFromUpdate);
//this._from.off('remove', this._onFromRemove);
this._from.off('change', this._onFromChange);
this._from._removeOldView(this);
};
/**
* Gets the primary key for this view from the assigned collection.
* @returns {String}
*/
OldView.prototype.primaryKey = function () {
if (this._from) {
return this._from.primaryKey();
}
return undefined;
};
/**
* Gets / sets the query that the view uses to build it's data set.
* @param {Object=} query
* @param {Boolean=} options An options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
OldView.prototype.queryData = function (query, options, refresh) {
if (query !== undefined) {
this._query.query = query;
}
if (options !== undefined) {
this._query.options = options;
}
if (query !== undefined || options !== undefined) {
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._query;
};
/**
* Add data to the existing query.
* @param {Object} obj The data whose keys will be added to the existing
* query object.
* @param {Boolean} overwrite Whether or not to overwrite data that already
* exists in the query object. Defaults to true.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
OldView.prototype.queryAdd = function (obj, overwrite, refresh) {
var query = this._query.query,
i;
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (query[i] === undefined || (query[i] !== undefined && overwrite)) {
query[i] = obj[i];
}
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
};
/**
* Remove data from the existing query.
* @param {Object} obj The data whose keys will be removed from the existing
* query object.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
OldView.prototype.queryRemove = function (obj, refresh) {
var query = this._query.query,
i;
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
delete query[i];
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
};
/**
* Gets / sets the query being used to generate the view data.
* @param {Object=} query The query to set.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
OldView.prototype.query = function (query, refresh) {
if (query !== undefined) {
this._query.query = query;
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._query.query;
};
/**
* Gets / sets the query options used when applying sorting etc to the
* view data set.
* @param {Object=} options An options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
OldView.prototype.queryOptions = function (options, refresh) {
if (options !== undefined) {
this._query.options = options;
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._query.options;
};
/**
* Refreshes the view data and diffs between previous and new data to
* determine if any events need to be triggered or DOM binds updated.
*/
OldView.prototype.refresh = function (force) {
if (this._from) {
// Take a copy of the data before updating it, we will use this to
// "diff" between the old and new data and handle DOM bind updates
var oldData = this._data,
oldDataArr,
oldDataItem,
newData,
newDataArr,
query,
primaryKey,
dataItem,
inserted = [],
updated = [],
removed = [],
operated = false,
i;
if (this.debug()) {
console.log('ForerunnerDB.OldView: Refreshing view ' + this._name);
console.log('ForerunnerDB.OldView: Existing data: ' + (typeof(this._data) !== "undefined"));
if (typeof(this._data) !== "undefined") {
console.log('ForerunnerDB.OldView: Current data rows: ' + this._data.find().length);
}
//console.log(OldView.prototype.refresh.caller);
}
// Query the collection and update the data
if (this._query) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: View has query and options, getting subset...');
}
// Run query against collection
//console.log('refresh with query and options', this._query.options);
this._data = this._from.subset(this._query.query, this._query.options);
//console.log(this._data);
} else {
// No query, return whole collection
if (this._query.options) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: View has options, getting subset...');
}
this._data = this._from.subset({}, this._query.options);
} else {
if (this.debug()) {
console.log('ForerunnerDB.OldView: View has no query or options, getting subset...');
}
this._data = this._from.subset({});
}
}
// Check if there was old data
if (!force && oldData) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: Refresh not forced, old data detected...');
}
// Now determine the difference
newData = this._data;
if (oldData.subsetOf() === newData.subsetOf()) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: Old and new data are from same collection...');
}
newDataArr = newData.find();
oldDataArr = oldData.find();
primaryKey = newData._primaryKey;
// The old data and new data were derived from the same parent collection
// so scan the data to determine changes
for (i = 0; i < newDataArr.length; i++) {
dataItem = newDataArr[i];
query = {};
query[primaryKey] = dataItem[primaryKey];
// Check if this item exists in the old data
oldDataItem = oldData.find(query)[0];
if (!oldDataItem) {
// New item detected
inserted.push(dataItem);
} else {
// Check if an update has occurred
if (JSON.stringify(oldDataItem) !== JSON.stringify(dataItem)) {
// Updated / already included item detected
updated.push(dataItem);
}
}
}
// Now loop the old data and check if any records were removed
for (i = 0; i < oldDataArr.length; i++) {
dataItem = oldDataArr[i];
query = {};
query[primaryKey] = dataItem[primaryKey];
// Check if this item exists in the old data
if (!newData.find(query)[0]) {
// Removed item detected
removed.push(dataItem);
}
}
if (this.debug()) {
console.log('ForerunnerDB.OldView: Removed ' + removed.length + ' rows');
console.log('ForerunnerDB.OldView: Inserted ' + inserted.length + ' rows');
console.log('ForerunnerDB.OldView: Updated ' + updated.length + ' rows');
}
// Now we have a diff of the two data sets, we need to get the DOM updated
if (inserted.length) {
this._onInsert(inserted, []);
operated = true;
}
if (updated.length) {
this._onUpdate(updated, []);
operated = true;
}
if (removed.length) {
this._onRemove(removed, []);
operated = true;
}
} else {
// The previous data and the new data are derived from different collections
// and can therefore not be compared, all data is therefore effectively "new"
// so first perform a remove of all existing data then do an insert on all new data
if (this.debug()) {
console.log('ForerunnerDB.OldView: Old and new data are from different collections...');
}
removed = oldData.find();
if (removed.length) {
this._onRemove(removed);
operated = true;
}
inserted = newData.find();
if (inserted.length) {
this._onInsert(inserted);
operated = true;
}
}
} else {
// Force an update as if the view never got created by padding all elements
// to the insert
if (this.debug()) {
console.log('ForerunnerDB.OldView: Forcing data update', newDataArr);
}
this._data = this._from.subset(this._query.query, this._query.options);
newDataArr = this._data.find();
if (this.debug()) {
console.log('ForerunnerDB.OldView: Emitting change event with data', newDataArr);
}
this._onInsert(newDataArr, []);
}
if (this.debug()) { console.log('ForerunnerDB.OldView: Emitting change'); }
this.emit('change');
}
return this;
};
/**
* Returns the number of documents currently in the view.
* @returns {Number}
*/
OldView.prototype.count = function () {
return this._data && this._data._data ? this._data._data.length : 0;
};
/**
* Queries the view data. See Collection.find() for more information.
* @returns {*}
*/
OldView.prototype.find = function () {
if (this._data) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: Finding data in view collection...', this._data);
}
return this._data.find.apply(this._data, arguments);
} else {
return [];
}
};
/**
* Inserts into view data via the view collection. See Collection.insert() for more information.
* @returns {*}
*/
OldView.prototype.insert = function () {
if (this._from) {
// Pass the args through to the from object
return this._from.insert.apply(this._from, arguments);
} else {
return [];
}
};
/**
* Updates into view data via the view collection. See Collection.update() for more information.
* @returns {*}
*/
OldView.prototype.update = function () {
if (this._from) {
// Pass the args through to the from object
return this._from.update.apply(this._from, arguments);
} else {
return [];
}
};
/**
* Removed from view data via the view collection. See Collection.remove() for more information.
* @returns {*}
*/
OldView.prototype.remove = function () {
if (this._from) {
// Pass the args through to the from object
return this._from.remove.apply(this._from, arguments);
} else {
return [];
}
};
OldView.prototype._onSetData = function (newDataArr, oldDataArr) {
this.emit('remove', oldDataArr, []);
this.emit('insert', newDataArr, []);
//this.refresh();
};
OldView.prototype._onInsert = function (successArr, failArr) {
this.emit('insert', successArr, failArr);
//this.refresh();
};
OldView.prototype._onUpdate = function (successArr, failArr) {
this.emit('update', successArr, failArr);
//this.refresh();
};
OldView.prototype._onRemove = function (successArr, failArr) {
this.emit('remove', successArr, failArr);
//this.refresh();
};
OldView.prototype._onChange = function () {
if (this.debug()) { console.log('ForerunnerDB.OldView: Refreshing data'); }
this.refresh();
};
// Extend collection with view init
Collection.prototype.init = function () {
this._oldViews = [];
CollectionInit.apply(this, arguments);
};
/**
* Adds a view to the internal view lookup.
* @param {View} view The view to add.
* @returns {Collection}
* @private
*/
Collection.prototype._addOldView = function (view) {
if (view !== undefined) {
this._oldViews[view._name] = view;
}
return this;
};
/**
* Removes a view from the internal view lookup.
* @param {View} view The view to remove.
* @returns {Collection}
* @private
*/
Collection.prototype._removeOldView = function (view) {
if (view !== undefined) {
delete this._oldViews[view._name];
}
return this;
};
// Extend collection with view init
CollectionGroup.prototype.init = function () {
this._oldViews = [];
CollectionGroupInit.apply(this, arguments);
};
/**
* Adds a view to the internal view lookup.
* @param {View} view The view to add.
* @returns {Collection}
* @private
*/
CollectionGroup.prototype._addOldView = function (view) {
if (view !== undefined) {
this._oldViews[view._name] = view;
}
return this;
};
/**
* Removes a view from the internal view lookup.
* @param {View} view The view to remove.
* @returns {Collection}
* @private
*/
CollectionGroup.prototype._removeOldView = function (view) {
if (view !== undefined) {
delete this._oldViews[view._name];
}
return this;
};
// Extend DB with views init
Db.prototype.init = function () {
this._oldViews = {};
DbInit.apply(this, arguments);
};
/**
* Gets a view by it's name.
* @param {String} viewName The name of the view to retrieve.
* @returns {*}
*/
Db.prototype.oldView = function (viewName) {
if (!this._oldViews[viewName]) {
if (this.debug()) {
console.log('ForerunnerDB.OldView: Creating view ' + viewName);
}
}
this._oldViews[viewName] = this._oldViews[viewName] || new OldView(viewName).db(this);
return this._oldViews[viewName];
};
/**
* Determine if a view with the passed name already exists.
* @param {String} viewName The name of the view to check for.
* @returns {boolean}
*/
Db.prototype.oldViewExists = function (viewName) {
return Boolean(this._oldViews[viewName]);
};
/**
* Returns an array of views the DB currently has.
* @returns {Array} An array of objects containing details of each view
* the database is currently managing.
*/
Db.prototype.oldViews = function () {
var arr = [],
i;
for (i in this._oldViews) {
if (this._oldViews.hasOwnProperty(i)) {
arr.push({
name: i,
count: this._oldViews[i].count()
});
}
}
return arr;
};
Shared.finishModule('OldView');
module.exports = OldView;
},{"./Collection":4,"./CollectionGroup":5,"./Shared":37}],28:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
Path = _dereq_('./Path');
/**
* The operation class, used to store details about an operation being
* performed by the database.
* @param {String} name The name of the operation.
* @constructor
*/
var Operation = function (name) {
this.pathSolver = new Path();
this.counter = 0;
this.init.apply(this, arguments);
};
Operation.prototype.init = function (name) {
this._data = {
operation: name, // The name of the operation executed such as "find", "update" etc
index: {
potential: [], // Indexes that could have potentially been used
used: false // The index that was picked to use
},
steps: [], // The steps taken to generate the query results,
time: {
startMs: 0,
stopMs: 0,
totalMs: 0,
process: {}
},
flag: {}, // An object with flags that denote certain execution paths
log: [] // Any extra data that might be useful such as warnings or helpful hints
};
};
Shared.addModule('Operation', Operation);
Shared.mixin(Operation.prototype, 'Mixin.ChainReactor');
/**
* Starts the operation timer.
*/
Operation.prototype.start = function () {
this._data.time.startMs = new Date().getTime();
};
/**
* Adds an item to the operation log.
* @param {String} event The item to log.
* @returns {*}
*/
Operation.prototype.log = function (event) {
if (event) {
var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0,
logObj = {
event: event,
time: new Date().getTime(),
delta: 0
};
this._data.log.push(logObj);
if (lastLogTime) {
logObj.delta = logObj.time - lastLogTime;
}
return this;
}
return this._data.log;
};
/**
* Called when starting and ending a timed operation, used to time
* internal calls within an operation's execution.
* @param {String} section An operation name.
* @returns {*}
*/
Operation.prototype.time = function (section) {
if (section !== undefined) {
var process = this._data.time.process,
processObj = process[section] = process[section] || {};
if (!processObj.startMs) {
// Timer started
processObj.startMs = new Date().getTime();
processObj.stepObj = {
name: section
};
this._data.steps.push(processObj.stepObj);
} else {
processObj.stopMs = new Date().getTime();
processObj.totalMs = processObj.stopMs - processObj.startMs;
processObj.stepObj.totalMs = processObj.totalMs;
delete processObj.stepObj;
}
return this;
}
return this._data.time;
};
/**
* Used to set key/value flags during operation execution.
* @param {String} key
* @param {String} val
* @returns {*}
*/
Operation.prototype.flag = function (key, val) {
if (key !== undefined && val !== undefined) {
this._data.flag[key] = val;
} else if (key !== undefined) {
return this._data.flag[key];
} else {
return this._data.flag;
}
};
Operation.prototype.data = function (path, val, noTime) {
if (val !== undefined) {
// Assign value to object path
this.pathSolver.set(this._data, path, val);
return this;
}
return this.pathSolver.get(this._data, path);
};
Operation.prototype.pushData = function (path, val, noTime) {
// Assign value to object path
this.pathSolver.push(this._data, path, val);
};
/**
* Stops the operation timer.
*/
Operation.prototype.stop = function () {
this._data.time.stopMs = new Date().getTime();
this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs;
};
Shared.finishModule('Operation');
module.exports = Operation;
},{"./Path":31,"./Shared":37}],29:[function(_dereq_,module,exports){
"use strict";
/**
* Allows a method to accept overloaded calls with different parameters controlling
* which passed overload function is called.
* @param {Object} def
* @returns {Function}
* @constructor
*/
var Overload = function (def) {
if (def) {
var self = this,
index,
count,
tmpDef,
defNewKey,
sigIndex,
signatures;
if (!(def instanceof Array)) {
tmpDef = {};
// Def is an object, make sure all prop names are devoid of spaces
for (index in def) {
if (def.hasOwnProperty(index)) {
defNewKey = index.replace(/ /g, '');
// Check if the definition array has a * string in it
if (defNewKey.indexOf('*') === -1) {
// No * found
tmpDef[defNewKey] = def[index];
} else {
// A * was found, generate the different signatures that this
// definition could represent
signatures = this.generateSignaturePermutations(defNewKey);
for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) {
if (!tmpDef[signatures[sigIndex]]) {
tmpDef[signatures[sigIndex]] = def[index];
}
}
}
}
}
def = tmpDef;
}
return function () {
var arr = [],
lookup,
type,
name;
// Check if we are being passed a key/function object or an array of functions
if (def instanceof Array) {
// We were passed an array of functions
count = def.length;
for (index = 0; index < count; index++) {
if (def[index].length === arguments.length) {
return self.callExtend(this, '$main', def, def[index], arguments);
}
}
} else {
// Generate lookup key from arguments
// Copy arguments to an array
for (index = 0; index < arguments.length; index++) {
type = typeof arguments[index];
// Handle detecting arrays
if (type === 'object' && arguments[index] instanceof Array) {
type = 'array';
}
// Handle been presented with a single undefined argument
if (arguments.length === 1 && type === 'undefined') {
break;
}
// Add the type to the argument types array
arr.push(type);
}
lookup = arr.join(',');
// Check for an exact lookup match
if (def[lookup]) {
return self.callExtend(this, '$main', def, def[lookup], arguments);
} else {
for (index = arr.length; index >= 0; index--) {
// Get the closest match
lookup = arr.slice(0, index).join(',');
if (def[lookup + ',...']) {
// Matched against arguments + "any other"
return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments);
}
}
}
}
name = typeof this.name === 'function' ? this.name() : 'Unknown';
throw('ForerunnerDB.Overload "' + name + '": Overloaded method does not have a matching signature for the passed arguments: ' + this.jStringify(arr));
};
}
return function () {};
};
/**
* Generates an array of all the different definition signatures that can be
* created from the passed string with a catch-all wildcard *. E.g. it will
* convert the signature: string,*,string to all potentials:
* string,string,string
* string,number,string
* string,object,string,
* string,function,string,
* string,undefined,string
*
* @param {String} str Signature string with a wildcard in it.
* @returns {Array} An array of signature strings that are generated.
*/
Overload.prototype.generateSignaturePermutations = function (str) {
var signatures = [],
newSignature,
types = ['string', 'object', 'number', 'function', 'undefined'],
index;
if (str.indexOf('*') > -1) {
// There is at least one "any" type, break out into multiple keys
// We could do this at query time with regular expressions but
// would be significantly slower
for (index = 0; index < types.length; index++) {
newSignature = str.replace('*', types[index]);
signatures = signatures.concat(this.generateSignaturePermutations(newSignature));
}
} else {
signatures.push(str);
}
return signatures;
};
Overload.prototype.callExtend = function (context, prop, propContext, func, args) {
var tmp,
ret;
if (context && propContext[prop]) {
tmp = context[prop];
context[prop] = propContext[prop];
ret = func.apply(context, args);
context[prop] = tmp;
return ret;
} else {
return func.apply(context, args);
}
};
module.exports = Overload;
},{}],30:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
Collection,
DbDocument;
Shared = _dereq_('./Shared');
var Overview = function () {
this.init.apply(this, arguments);
};
Overview.prototype.init = function (name) {
var self = this;
this._name = name;
this._data = new DbDocument('__FDB__dc_data_' + this._name);
this._collData = new Collection();
this._sources = [];
this._sourceDroppedWrap = function () {
self._sourceDropped.apply(self, arguments);
};
};
Shared.addModule('Overview', Overview);
Shared.mixin(Overview.prototype, 'Mixin.Common');
Shared.mixin(Overview.prototype, 'Mixin.ChainReactor');
Shared.mixin(Overview.prototype, 'Mixin.Constants');
Shared.mixin(Overview.prototype, 'Mixin.Triggers');
Shared.mixin(Overview.prototype, 'Mixin.Events');
Shared.mixin(Overview.prototype, 'Mixin.Tags');
Collection = _dereq_('./Collection');
DbDocument = _dereq_('./Document');
Db = Shared.modules.Db;
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(Overview.prototype, 'state');
Shared.synthesize(Overview.prototype, 'db');
Shared.synthesize(Overview.prototype, 'name');
Shared.synthesize(Overview.prototype, 'query', function (val) {
var ret = this.$super(val);
if (val !== undefined) {
this._refresh();
}
return ret;
});
Shared.synthesize(Overview.prototype, 'queryOptions', function (val) {
var ret = this.$super(val);
if (val !== undefined) {
this._refresh();
}
return ret;
});
Shared.synthesize(Overview.prototype, 'reduce', function (val) {
var ret = this.$super(val);
if (val !== undefined) {
this._refresh();
}
return ret;
});
Overview.prototype.from = function (source) {
if (source !== undefined) {
if (typeof(source) === 'string') {
source = this._db.collection(source);
}
this._setFrom(source);
return this;
}
return this._sources;
};
Overview.prototype.find = function () {
return this._collData.find.apply(this._collData, arguments);
};
/**
* Executes and returns the response from the current reduce method
* assigned to the overview.
* @returns {*}
*/
Overview.prototype.exec = function () {
var reduceFunc = this.reduce();
return reduceFunc ? reduceFunc.apply(this) : undefined;
};
Overview.prototype.count = function () {
return this._collData.count.apply(this._collData, arguments);
};
Overview.prototype._setFrom = function (source) {
// Remove all source references
while (this._sources.length) {
this._removeSource(this._sources[0]);
}
this._addSource(source);
return this;
};
Overview.prototype._addSource = function (source) {
if (source && source.className === 'View') {
// The source is a view so IO to the internal data collection
// instead of the view proper
source = source.privateData();
if (this.debug()) {
console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking');
}
}
if (this._sources.indexOf(source) === -1) {
this._sources.push(source);
source.chain(this);
source.on('drop', this._sourceDroppedWrap);
this._refresh();
}
return this;
};
Overview.prototype._removeSource = function (source) {
if (source && source.className === 'View') {
// The source is a view so IO to the internal data collection
// instead of the view proper
source = source.privateData();
if (this.debug()) {
console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking');
}
}
var sourceIndex = this._sources.indexOf(source);
if (sourceIndex > -1) {
this._sources.splice(source, 1);
source.unChain(this);
source.off('drop', this._sourceDroppedWrap);
this._refresh();
}
return this;
};
Overview.prototype._sourceDropped = function (source) {
if (source) {
// Source was dropped, remove from overview
this._removeSource(source);
}
};
Overview.prototype._refresh = function () {
if (!this.isDropped()) {
if (this._sources && this._sources[0]) {
this._collData.primaryKey(this._sources[0].primaryKey());
var tempArr = [],
i;
for (i = 0; i < this._sources.length; i++) {
tempArr = tempArr.concat(this._sources[i].find(this._query, this._queryOptions));
}
this._collData.setData(tempArr);
}
// Now execute the reduce method
if (this._reduce) {
var reducedData = this._reduce.apply(this);
// Update the document with the newly returned data
this._data.setData(reducedData);
}
}
};
Overview.prototype._chainHandler = function (chainPacket) {
switch (chainPacket.type) {
case 'setData':
case 'insert':
case 'update':
case 'remove':
this._refresh();
break;
default:
break;
}
};
/**
* Gets the module's internal data collection.
* @returns {Collection}
*/
Overview.prototype.data = function () {
return this._data;
};
Overview.prototype.drop = function (callback) {
if (!this.isDropped()) {
this._state = 'dropped';
delete this._data;
delete this._collData;
// Remove all source references
while (this._sources.length) {
this._removeSource(this._sources[0]);
}
delete this._sources;
if (this._db && this._name) {
delete this._db._overview[this._name];
}
delete this._name;
this.emit('drop', this);
if (callback) { callback(false, true); }
}
return true;
};
Db.prototype.overview = function (overviewName) {
if (overviewName) {
// Handle being passed an instance
if (overviewName instanceof Overview) {
return overviewName;
}
this._overview = this._overview || {};
this._overview[overviewName] = this._overview[overviewName] || new Overview(overviewName).db(this);
return this._overview[overviewName];
} else {
// Return an object of collection data
return this._overview || {};
}
};
/**
* Returns an array of overviews the DB currently has.
* @returns {Array} An array of objects containing details of each overview
* the database is currently managing.
*/
Db.prototype.overviews = function () {
var arr = [],
item,
i;
for (i in this._overview) {
if (this._overview.hasOwnProperty(i)) {
item = this._overview[i];
arr.push({
name: i,
count: item.count(),
linked: item.isLinked !== undefined ? item.isLinked() : false
});
}
}
return arr;
};
Shared.finishModule('Overview');
module.exports = Overview;
},{"./Collection":4,"./Document":9,"./Shared":37}],31:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Path object used to resolve object paths and retrieve data from
* objects by using paths.
* @param {String=} path The path to assign.
* @constructor
*/
var Path = function (path) {
this.init.apply(this, arguments);
};
Path.prototype.init = function (path) {
if (path) {
this.path(path);
}
};
Shared.addModule('Path', Path);
Shared.mixin(Path.prototype, 'Mixin.Common');
Shared.mixin(Path.prototype, 'Mixin.ChainReactor');
/**
* Gets / sets the given path for the Path instance.
* @param {String=} path The path to assign.
*/
Path.prototype.path = function (path) {
if (path !== undefined) {
this._path = this.clean(path);
this._pathParts = this._path.split('.');
return this;
}
return this._path;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Boolean} True if the object paths exist.
*/
Path.prototype.hasObjectPaths = function (testKeys, testObj) {
var result = true,
i;
for (i in testKeys) {
if (testKeys.hasOwnProperty(i)) {
if (testObj[i] === undefined) {
return false;
}
if (typeof testKeys[i] === 'object') {
// Recurse object
result = this.hasObjectPaths(testKeys[i], testObj[i]);
// Should we exit early?
if (!result) {
return false;
}
}
}
}
return result;
};
/**
* Counts the total number of key endpoints in the passed object.
* @param {Object} testObj The object to count key endpoints for.
* @returns {Number} The number of endpoints.
*/
Path.prototype.countKeys = function (testObj) {
var totalKeys = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (testObj[i] !== undefined) {
if (typeof testObj[i] !== 'object') {
totalKeys++;
} else {
totalKeys += this.countKeys(testObj[i]);
}
}
}
}
return totalKeys;
};
/**
* Tests if the passed object has the paths that are specified and that
* a value exists in those paths and if so returns the number matched.
* @param {Object} testKeys The object describing the paths to test for.
* @param {Object} testObj The object to test paths against.
* @returns {Object} Stats on the matched keys
*/
Path.prototype.countObjectPaths = function (testKeys, testObj) {
var matchData,
matchedKeys = {},
matchedKeyCount = 0,
totalKeyCount = 0,
i;
for (i in testObj) {
if (testObj.hasOwnProperty(i)) {
if (typeof testObj[i] === 'object') {
// The test / query object key is an object, recurse
matchData = this.countObjectPaths(testKeys[i], testObj[i]);
matchedKeys[i] = matchData.matchedKeys;
totalKeyCount += matchData.totalKeyCount;
matchedKeyCount += matchData.matchedKeyCount;
} else {
// The test / query object has a property that is not an object so add it as a key
totalKeyCount++;
// Check if the test keys also have this key and it is also not an object
if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') {
matchedKeys[i] = true;
matchedKeyCount++;
} else {
matchedKeys[i] = false;
}
}
}
}
return {
matchedKeys: matchedKeys,
matchedKeyCount: matchedKeyCount,
totalKeyCount: totalKeyCount
};
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* a path string.
* @param {Object} obj The object to parse.
* @param {Boolean=} withValue If true will include a 'value' key in the returned
* object that represents the value the object path points to.
* @returns {Object}
*/
Path.prototype.parse = function (obj, withValue) {
var paths = [],
path = '',
resultData,
i, k;
for (i in obj) {
if (obj.hasOwnProperty(i)) {
// Set the path to the key
path = i;
if (typeof(obj[i]) === 'object') {
if (withValue) {
resultData = this.parse(obj[i], withValue);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path,
value: resultData[k].value
});
}
} else {
resultData = this.parse(obj[i]);
for (k = 0; k < resultData.length; k++) {
paths.push({
path: path + '.' + resultData[k].path
});
}
}
} else {
if (withValue) {
paths.push({
path: path,
value: obj[i]
});
} else {
paths.push({
path: path
});
}
}
}
}
return paths;
};
/**
* Takes a non-recursive object and converts the object hierarchy into
* an array of path strings that allow you to target all possible paths
* in an object.
*
* The options object accepts an "ignore" field with a regular expression
* as the value. If any key matches the expression it is not included in
* the results.
*
* The options object accepts a boolean "verbose" field. If set to true
* the results will include all paths leading up to endpoints as well as
* they endpoints themselves.
*
* @returns {Array}
*/
Path.prototype.parseArr = function (obj, options) {
options = options || {};
return this._parseArr(obj, '', [], options);
};
Path.prototype._parseArr = function (obj, path, paths, options) {
var i,
newPath = '';
path = path || '';
paths = paths || [];
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (!options.ignore || (options.ignore && !options.ignore.test(i))) {
if (path) {
newPath = path + '.' + i;
} else {
newPath = i;
}
if (typeof(obj[i]) === 'object') {
if (options.verbose) {
paths.push(newPath);
}
this._parseArr(obj[i], newPath, paths, options);
} else {
paths.push(newPath);
}
}
}
}
return paths;
};
/**
* Gets the value(s) that the object contains for the currently assigned path string.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @returns {Array} An array of values for the given path.
*/
Path.prototype.value = function (obj, path) {
if (obj !== undefined && typeof obj === 'object') {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
valuesArr = [],
i, k;
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (objPartParent instanceof Array) {
// Search inside the array for the next key
for (k = 0; k < objPartParent.length; k++) {
valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i]));
}
return valuesArr;
} else {
if (!objPart || typeof(objPart) !== 'object') {
break;
}
}
objPartParent = objPart;
}
return [objPart];
} else {
return [];
}
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
Path.prototype.get = function (obj, path) {
return this.value(obj, path)[0];
};
/**
* Push a value to an array on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to the array to push to.
* @param {*} val The value to push to the array at the object path.
* @returns {*}
*/
Path.prototype.push = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = obj[part] || [];
if (obj[part] instanceof Array) {
obj[part].push(val);
} else {
throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!');
}
}
}
return obj;
};
/**
* Gets the value(s) that the object contains for the currently assigned path string
* with their associated keys.
* @param {Object} obj The object to evaluate the path against.
* @param {String=} path A path to use instead of the existing one passed in path().
* @returns {Array} An array of values for the given path with the associated key.
*/
Path.prototype.keyValue = function (obj, path) {
var pathParts,
arr,
arrCount,
objPart,
objPartParent,
objPartHash,
i;
if (path !== undefined) {
path = this.clean(path);
pathParts = path.split('.');
}
arr = pathParts || this._pathParts;
arrCount = arr.length;
objPart = obj;
for (i = 0; i < arrCount; i++) {
objPart = objPart[arr[i]];
if (!objPart || typeof(objPart) !== 'object') {
objPartHash = arr[i] + ':' + objPart;
break;
}
objPartParent = objPart;
}
return objPartHash;
};
/**
* Sets a value on an object for the specified path.
* @param {Object} obj The object to update.
* @param {String} path The path to update.
* @param {*} val The value to set the object path to.
* @returns {*}
*/
Path.prototype.set = function (obj, path, val) {
if (obj !== undefined && path !== undefined) {
var pathParts,
part;
path = this.clean(path);
pathParts = path.split('.');
part = pathParts.shift();
if (pathParts.length) {
// Generate the path part in the object if it does not already exist
obj[part] = obj[part] || {};
// Recurse
this.set(obj[part], pathParts.join('.'), val);
} else {
// Set the value
obj[part] = val;
}
}
return obj;
};
/**
* Removes leading period (.) from string and returns it.
* @param {String} str The string to clean.
* @returns {*}
*/
Path.prototype.clean = function (str) {
if (str.substr(0, 1) === '.') {
str = str.substr(1, str.length -1);
}
return str;
};
Shared.finishModule('Path');
module.exports = Path;
},{"./Shared":37}],32:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared = _dereq_('./Shared'),
async = _dereq_('async'),
localforage = _dereq_('localforage'),
FdbCompress = _dereq_('./PersistCompress'),// jshint ignore:line
FdbCrypto = _dereq_('./PersistCrypto'),// jshint ignore:line
Db,
Collection,
CollectionDrop,
CollectionGroup,
CollectionInit,
DbInit,
DbDrop,
Persist,
Overload;//,
//DataVersion = '2.0';
/**
* The persistent storage class handles loading and saving data to browser
* storage.
* @constructor
*/
Persist = function () {
this.init.apply(this, arguments);
};
/**
* The local forage library.
*/
Persist.prototype.localforage = localforage;
/**
* The init method that can be overridden or extended.
* @param {Db} db The ForerunnerDB database instance.
*/
Persist.prototype.init = function (db) {
var self = this;
this._encodeSteps = [
function () { return self._encode.apply(self, arguments); }
];
this._decodeSteps = [
function () { return self._decode.apply(self, arguments); }
];
// Check environment
if (db.isClient()) {
if (window.Storage !== undefined) {
this.mode('localforage');
localforage.config({
driver: [
localforage.INDEXEDDB,
localforage.WEBSQL,
localforage.LOCALSTORAGE
],
name: String(db.core().name()),
storeName: 'FDB'
});
}
}
};
Shared.addModule('Persist', Persist);
Shared.mixin(Persist.prototype, 'Mixin.ChainReactor');
Shared.mixin(Persist.prototype, 'Mixin.Common');
Db = Shared.modules.Db;
Collection = _dereq_('./Collection');
CollectionDrop = Collection.prototype.drop;
CollectionGroup = _dereq_('./CollectionGroup');
CollectionInit = Collection.prototype.init;
DbInit = Db.prototype.init;
DbDrop = Db.prototype.drop;
Overload = Shared.overload;
/**
* Gets / sets the persistent storage mode (the library used
* to persist data to the browser - defaults to localForage).
* @param {String} type The library to use for storage. Defaults
* to localForage.
* @returns {*}
*/
Persist.prototype.mode = function (type) {
if (type !== undefined) {
this._mode = type;
return this;
}
return this._mode;
};
/**
* Gets / sets the driver used when persisting data.
* @param {String} val Specify the driver type (LOCALSTORAGE,
* WEBSQL or INDEXEDDB)
* @returns {*}
*/
Persist.prototype.driver = function (val) {
if (val !== undefined) {
switch (val.toUpperCase()) {
case 'LOCALSTORAGE':
localforage.setDriver(localforage.LOCALSTORAGE);
break;
case 'WEBSQL':
localforage.setDriver(localforage.WEBSQL);
break;
case 'INDEXEDDB':
localforage.setDriver(localforage.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 localforage.driver();
};
/**
* Starts a decode waterfall process.
* @param {*} val The data to be decoded.
* @param {Function} finished The callback to pass final data to.
*/
Persist.prototype.decode = function (val, finished) {
async.waterfall([function (callback) {
if (callback) { callback(false, val, {}); }
}].concat(this._decodeSteps), finished);
};
/**
* Starts an encode waterfall process.
* @param {*} val The data to be encoded.
* @param {Function} finished The callback to pass final data to.
*/
Persist.prototype.encode = function (val, finished) {
async.waterfall([function (callback) {
if (callback) { callback(false, val, {}); }
}].concat(this._encodeSteps), finished);
};
Shared.synthesize(Persist.prototype, 'encodeSteps');
Shared.synthesize(Persist.prototype, 'decodeSteps');
/**
* Adds an encode/decode step to the persistent storage system so
* that you can add custom functionality.
* @param {Function} encode The encode method called with the data from the
* previous encode step. When your method is complete it MUST call the
* callback method. If you provide anything other than false to the err
* parameter the encoder will fail and throw an error.
* @param {Function} decode The decode method called with the data from the
* previous decode step. When your method is complete it MUST call the
* callback method. If you provide anything other than false to the err
* parameter the decoder will fail and throw an error.
* @param {Number=} index Optional index to add the encoder step to. This
* allows you to place a step before or after other existing steps. If not
* provided your step is placed last in the list of steps. For instance if
* you are providing an encryption step it makes sense to place this last
* since all previous steps will then have their data encrypted by your
* final step.
*/
Persist.prototype.addStep = new Overload({
'object': function (obj) {
this.$main.call(this, function objEncode () { obj.encode.apply(obj, arguments); }, function objDecode () { obj.decode.apply(obj, arguments); }, 0);
},
'function, function': function (encode, decode) {
this.$main.call(this, encode, decode, 0);
},
'function, function, number': function (encode, decode, index) {
this.$main.call(this, encode, decode, index);
},
$main: function (encode, decode, index) {
if (index === 0 || index === undefined) {
this._encodeSteps.push(encode);
this._decodeSteps.unshift(decode);
} else {
// Place encoder step at index then work out correct
// index to place decoder step
this._encodeSteps.splice(index, 0, encode);
this._decodeSteps.splice(this._decodeSteps.length - index, 0, decode);
}
}
});
Persist.prototype.unwrap = function (dataStr) {
var parts = dataStr.split('::fdb::'),
data;
switch (parts[0]) {
case 'json':
data = this.jParse(parts[1]);
break;
case 'raw':
data = parts[1];
break;
default:
break;
}
};
/**
* Takes encoded data and decodes it for use as JS native objects and arrays.
* @param {String} val The currently encoded string data.
* @param {Object} meta Meta data object that can be used to pass back useful
* supplementary data.
* @param {Function} finished The callback method to call when decoding is
* completed.
* @private
*/
Persist.prototype._decode = function (val, meta, finished) {
var parts,
data;
if (val) {
parts = val.split('::fdb::');
switch (parts[0]) {
case 'json':
data = this.jParse(parts[1]);
break;
case 'raw':
data = parts[1];
break;
default:
break;
}
if (data) {
meta.foundData = true;
meta.rowCount = data.length;
} else {
meta.foundData = false;
}
if (finished) {
finished(false, data, meta);
}
} else {
meta.foundData = false;
meta.rowCount = 0;
if (finished) {
finished(false, val, meta);
}
}
};
/**
* Takes native JS data and encodes it for for storage as a string.
* @param {Object} val The current un-encoded data.
* @param {Object} meta Meta data object that can be used to pass back useful
* supplementary data.
* @param {Function} finished The callback method to call when encoding is
* completed.
* @private
*/
Persist.prototype._encode = function (val, meta, finished) {
var data = val;
if (typeof val === 'object') {
val = 'json::fdb::' + this.jStringify(val);
} else {
val = 'raw::fdb::' + val;
}
if (data) {
meta.foundData = true;
meta.rowCount = data.length;
} else {
meta.foundData = false;
}
if (finished) {
finished(false, val, meta);
}
};
/**
* Encodes passed data and then stores it in the browser's persistent
* storage layer.
* @param {String} key The key to store the data under in the persistent
* storage.
* @param {Object} data The data to store under the key.
* @param {Function=} callback The method to call when the save process
* has completed.
*/
Persist.prototype.save = function (key, data, callback) {
switch (this.mode()) {
case 'localforage':
this.encode(data, function (err, data, tableStats) {
localforage.setItem(key, data).then(function (data) {
if (callback) { callback(false, data, tableStats); }
}, function (err) {
if (callback) { callback(err); }
});
});
break;
default:
if (callback) { callback('No data handler.'); }
break;
}
};
/**
* Loads and decodes data from the passed key.
* @param {String} key The key to retrieve data from in the persistent
* storage.
* @param {Function=} callback The method to call when the load process
* has completed.
*/
Persist.prototype.load = function (key, callback) {
var self = this;
switch (this.mode()) {
case 'localforage':
localforage.getItem(key).then(function (val) {
self.decode(val, callback);
}, function (err) {
if (callback) { callback(err); }
});
break;
default:
if (callback) { callback('No data handler or unrecognised data type.'); }
break;
}
};
/**
* Deletes data in persistent storage stored under the passed key.
* @param {String} key The key to drop data for in the storage.
* @param {Function=} callback The method to call when the data is dropped.
*/
Persist.prototype.drop = function (key, callback) {
switch (this.mode()) {
case 'localforage':
localforage.removeItem(key).then(function () {
if (callback) { callback(false); }
}, function (err) {
if (callback) { callback(err); }
});
break;
default:
if (callback) { callback('No data handler or unrecognised data type.'); }
break;
}
};
// Extend the Collection prototype with persist methods
Collection.prototype.drop = new Overload({
/**
* Drop collection and persistent storage.
*/
'': function () {
if (!this.isDropped()) {
this.drop(true);
}
},
/**
* Drop collection and persistent storage with callback.
* @param {Function} callback Callback method.
*/
'function': function (callback) {
if (!this.isDropped()) {
this.drop(true, callback);
}
},
/**
* Drop collection and optionally drop persistent storage.
* @param {Boolean} removePersistent True to drop persistent storage, false to keep it.
*/
'boolean': function (removePersistent) {
if (!this.isDropped()) {
// Remove persistent storage
if (removePersistent) {
if (this._name) {
if (this._db) {
// Drop the collection data from storage
this._db.persist.drop(this._db._name + '-' + this._name);
this._db.persist.drop(this._db._name + '-' + this._name + '-metaData');
}
} else {
throw('ForerunnerDB.Persist: Cannot drop a collection\'s persistent storage when no name assigned to collection!');
}
}
// Call the original method
CollectionDrop.call(this);
}
},
/**
* Drop collections and optionally drop persistent storage with callback.
* @param {Boolean} removePersistent True to drop persistent storage, false to keep it.
* @param {Function} callback Callback method.
*/
'boolean, function': function (removePersistent, callback) {
var self = this;
if (!this.isDropped()) {
// Remove persistent storage
if (removePersistent) {
if (this._name) {
if (this._db) {
// Drop the collection data from storage
this._db.persist.drop(this._db._name + '-' + this._name, function () {
self._db.persist.drop(self._db._name + '-' + self._name + '-metaData', callback);
});
return CollectionDrop.call(this);
} else {
if (callback) { callback('Cannot drop a collection\'s persistent storage when the collection is not attached to a database!'); }
}
} else {
if (callback) { callback('Cannot drop a collection\'s persistent storage when no name assigned to collection!'); }
}
} else {
// Call the original method
return CollectionDrop.call(this, callback);
}
}
}
});
/**
* Saves an entire collection's data to persistent storage.
* @param {Function=} callback The method to call when the save function
* has completed.
*/
Collection.prototype.save = function (callback) {
var self = this,
processSave;
if (self._name) {
if (self._db) {
processSave = function () {
// Save the collection data
self._db.persist.save(self._db._name + '-' + self._name, self._data, function (err, data, tableStats) {
if (!err) {
self._db.persist.save(self._db._name + '-' + self._name + '-metaData', self.metaData(), function (err, data, metaStats) {
if (callback) { callback(err, data, tableStats, metaStats); }
});
} else {
if (callback) { callback(err); }
}
});
};
// Check for processing queues
if (self.isProcessingQueue()) {
// Hook queue complete to process save
self.on('queuesComplete', function () {
processSave();
});
} else {
// Process save immediately
processSave();
}
} else {
if (callback) { callback('Cannot save a collection that is not attached to a database!'); }
}
} else {
if (callback) { callback('Cannot save a collection with no assigned name!'); }
}
};
/**
* Loads an entire collection's data from persistent storage.
* @param {Function=} callback The method to call when the load function
* has completed.
*/
Collection.prototype.load = function (callback) {
var self = this;
if (self._name) {
if (self._db) {
// Load the collection data
self._db.persist.load(self._db._name + '-' + self._name, function (err, data, tableStats) {
if (!err) {
if (data) {
self.setData(data);
}
// Now load the collection's metadata
self._db.persist.load(self._db._name + '-' + self._name + '-metaData', function (err, data, metaStats) {
if (!err) {
if (data) {
self.metaData(data);
}
}
if (callback) { callback(err, tableStats, metaStats); }
});
} else {
if (callback) { callback(err); }
}
});
} else {
if (callback) { callback('Cannot load a collection that is not attached to a database!'); }
}
} else {
if (callback) { callback('Cannot load a collection with no assigned name!'); }
}
};
// Override the DB init to instantiate the plugin
Db.prototype.init = function () {
DbInit.apply(this, arguments);
this.persist = new Persist(this);
};
/**
* Loads an entire database's data from persistent storage.
* @param {Function=} callback The method to call when the load function
* has completed.
*/
Db.prototype.load = function (callback) {
// Loop the collections in the database
var obj = this._collection,
keys = obj.keys(),
keyCount = keys.length,
loadCallback,
index;
loadCallback = function (err) {
if (!err) {
keyCount--;
if (keyCount === 0) {
if (callback) { callback(false); }
}
} else {
if (callback) { callback(err); }
}
};
for (index in obj) {
if (obj.hasOwnProperty(index)) {
// Call the collection load method
obj[index].load(loadCallback);
}
}
};
/**
* Saves an entire database's data to persistent storage.
* @param {Function=} callback The method to call when the save function
* has completed.
*/
Db.prototype.save = function (callback) {
// Loop the collections in the database
var obj = this._collection,
keys = obj.keys(),
keyCount = keys.length,
saveCallback,
index;
saveCallback = function (err) {
if (!err) {
keyCount--;
if (keyCount === 0) {
if (callback) { callback(false); }
}
} else {
if (callback) { callback(err); }
}
};
for (index in obj) {
if (obj.hasOwnProperty(index)) {
// Call the collection save method
obj[index].save(saveCallback);
}
}
};
Shared.finishModule('Persist');
module.exports = Persist;
},{"./Collection":4,"./CollectionGroup":5,"./PersistCompress":33,"./PersistCrypto":34,"./Shared":37,"async":39,"localforage":81}],33:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
pako = _dereq_('pako');
var Plugin = function () {
this.init.apply(this, arguments);
};
Plugin.prototype.init = function (options) {
};
Shared.mixin(Plugin.prototype, 'Mixin.Common');
Plugin.prototype.encode = function (val, meta, finished) {
var wrapper = {
data: val,
type: 'fdbCompress',
enabled: false
},
before,
after,
compressedVal;
// Compress the data
before = val.length;
compressedVal = pako.deflate(val, {to: 'string'});
after = compressedVal.length;
// If the compressed version is smaller than the original, use it!
if (after < before) {
wrapper.data = compressedVal;
wrapper.enabled = true;
}
meta.compression = {
enabled: wrapper.enabled,
compressedBytes: after,
uncompressedBytes: before,
effect: Math.round((100 / before) * after) + '%'
};
finished(false, this.jStringify(wrapper), meta);
};
Plugin.prototype.decode = function (wrapper, meta, finished) {
var compressionEnabled = false,
data;
if (wrapper) {
wrapper = this.jParse(wrapper);
// Check if we need to decompress the string
if (wrapper.enabled) {
data = pako.inflate(wrapper.data, {to: 'string'});
compressionEnabled = true;
} else {
data = wrapper.data;
compressionEnabled = false;
}
meta.compression = {
enabled: compressionEnabled
};
if (finished) {
finished(false, data, meta);
}
} else {
if (finished) {
finished(false, data, meta);
}
}
};
// Register this plugin with the persistent storage class
Shared.plugins.FdbCompress = Plugin;
module.exports = Plugin;
},{"./Shared":37,"pako":83}],34:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared'),
CryptoJS = _dereq_('crypto-js');
var Plugin = function () {
this.init.apply(this, arguments);
};
Plugin.prototype.init = function (options) {
// Ensure at least a password is passed in options
if (!options || !options.pass) {
throw('Cannot initialise persistent storage encryption without a passphrase provided in the passed options object as the "pass" field.');
}
this._algo = options.algo || 'AES';
this._pass = options.pass;
};
Shared.mixin(Plugin.prototype, 'Mixin.Common');
/**
* Gets / sets the current pass-phrase being used to encrypt / decrypt
* data with the plugin.
*/
Shared.synthesize(Plugin.prototype, 'pass');
Plugin.prototype.stringify = function (cipherParams) {
// create json object with ciphertext
var jsonObj = {
ct: cipherParams.ciphertext.toString(CryptoJS.enc.Base64)
};
// optionally add iv and salt
if (cipherParams.iv) {
jsonObj.iv = cipherParams.iv.toString();
}
if (cipherParams.salt) {
jsonObj.s = cipherParams.salt.toString();
}
// stringify json object
return this.jStringify(jsonObj);
};
Plugin.prototype.parse = function (jsonStr) {
// parse json string
var jsonObj = this.jParse(jsonStr);
// extract ciphertext from json object, and create cipher params object
var cipherParams = CryptoJS.lib.CipherParams.create({
ciphertext: CryptoJS.enc.Base64.parse(jsonObj.ct)
});
// optionally extract iv and salt
if (jsonObj.iv) {
cipherParams.iv = CryptoJS.enc.Hex.parse(jsonObj.iv);
}
if (jsonObj.s) {
cipherParams.salt = CryptoJS.enc.Hex.parse(jsonObj.s);
}
return cipherParams;
};
Plugin.prototype.encode = function (val, meta, finished) {
var self = this,
wrapper = {
type: 'fdbCrypto'
},
encryptedVal;
// Encrypt the data
encryptedVal = CryptoJS[this._algo].encrypt(val, this._pass, {
format: {
stringify: function () { return self.stringify.apply(self, arguments); },
parse: function () { return self.parse.apply(self, arguments); }
}
});
wrapper.data = encryptedVal.toString();
wrapper.enabled = true;
meta.encryption = {
enabled: wrapper.enabled
};
if (finished) {
finished(false, this.jStringify(wrapper), meta);
}
};
Plugin.prototype.decode = function (wrapper, meta, finished) {
var self = this,
data;
if (wrapper) {
wrapper = this.jParse(wrapper);
data = CryptoJS[this._algo].decrypt(wrapper.data, this._pass, {
format: {
stringify: function () { return self.stringify.apply(self, arguments); },
parse: function () { return self.parse.apply(self, arguments); }
}
}).toString(CryptoJS.enc.Utf8);
if (finished) {
finished(false, data, meta);
}
} else {
if (finished) {
finished(false, wrapper, meta);
}
}
};
// Register this plugin with the persistent storage class
Shared.plugins.FdbCrypto = Plugin;
module.exports = Plugin;
},{"./Shared":37,"crypto-js":48}],35:[function(_dereq_,module,exports){
"use strict";
var Shared = _dereq_('./Shared');
/**
* Provides chain reactor node linking so that a chain reaction can propagate
* down a node tree. Effectively creates a chain link between the reactorIn and
* reactorOut objects where a chain reaction from the reactorIn is passed through
* the reactorProcess before being passed to the reactorOut object. Reactor
* packets are only passed through to the reactorOut if the reactor IO method
* chainSend is used.
* @param {*} reactorIn An object that has the Mixin.ChainReactor methods mixed
* in to it. Chain reactions that occur inside this object will be passed through
* to the reactorOut object.
* @param {*} reactorOut An object that has the Mixin.ChainReactor methods mixed
* in to it. Chain reactions that occur in the reactorIn object will be passed
* through to this object.
* @param {Function} reactorProcess The processing method to use when chain
* reactions occur.
* @constructor
*/
var ReactorIO = function (reactorIn, reactorOut, reactorProcess) {
if (reactorIn && reactorOut && reactorProcess) {
this._reactorIn = reactorIn;
this._reactorOut = reactorOut;
this._chainHandler = reactorProcess;
if (!reactorIn.chain || !reactorOut.chainReceive) {
throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!');
}
// Register the reactorIO with the input
reactorIn.chain(this);
// Register the output with the reactorIO
this.chain(reactorOut);
} else {
throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!');
}
};
Shared.addModule('ReactorIO', ReactorIO);
/**
* Drop a reactor IO object, breaking the reactor link between the in and out
* reactor nodes.
* @returns {boolean}
*/
ReactorIO.prototype.drop = function () {
if (!this.isDropped()) {
this._state = 'dropped';
// Remove links
if (this._reactorIn) {
this._reactorIn.unChain(this);
}
if (this._reactorOut) {
this.unChain(this._reactorOut);
}
delete this._reactorIn;
delete this._reactorOut;
delete this._chainHandler;
this.emit('drop', this);
}
return true;
};
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(ReactorIO.prototype, 'state');
Shared.mixin(ReactorIO.prototype, 'Mixin.Common');
Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor');
Shared.mixin(ReactorIO.prototype, 'Mixin.Events');
Shared.finishModule('ReactorIO');
module.exports = ReactorIO;
},{"./Shared":37}],36:[function(_dereq_,module,exports){
"use strict";
/**
* Provides functionality to encode and decode JavaScript objects to strings
* and back again. This differs from JSON.stringify and JSON.parse in that
* special objects such as dates can be encoded to strings and back again
* so that the reconstituted version of the string still contains a JavaScript
* date object.
* @constructor
*/
var Serialiser = function () {
this.init.apply(this, arguments);
};
Serialiser.prototype.init = function () {
this._encoder = [];
this._decoder = {};
// Register our handlers
this.registerEncoder('$date', function (data) {
if (data instanceof Date) {
return data.toISOString();
}
});
this.registerDecoder('$date', function (data) {
return new Date(data);
});
};
/**
* Register an encoder that can handle encoding for a particular
* object type.
* @param {String} handles The name of the handler e.g. $date.
* @param {Function} method The encoder method.
*/
Serialiser.prototype.registerEncoder = function (handles, method) {
this._encoder.push(function (data) {
var methodVal = method(data),
returnObj;
if (methodVal !== undefined) {
returnObj = {};
returnObj[handles] = methodVal;
}
return returnObj;
});
};
/**
* Register a decoder that can handle decoding for a particular
* object type.
* @param {String} handles The name of the handler e.g. $date. When an object
* has a field matching this handler name then this decode will be invoked
* to provide a decoded version of the data that was previously encoded by
* it's counterpart encoder method.
* @param {Function} method The decoder method.
*/
Serialiser.prototype.registerDecoder = function (handles, method) {
this._decoder[handles] = method;
};
/**
* Loops the encoders and asks each one if it wants to handle encoding for
* the passed data object. If no value is returned (undefined) then the data
* will be passed to the next encoder and so on. If a value is returned the
* loop will break and the encoded data will be used.
* @param {Object} data The data object to handle.
* @returns {*} The encoded data.
* @private
*/
Serialiser.prototype._encode = function (data) {
// Loop the encoders and if a return value is given by an encoder
// the loop will exit and return that value.
var count = this._encoder.length,
retVal;
while (count-- && !retVal) {
retVal = this._encoder[count](data);
}
return retVal;
};
/**
* Converts a previously encoded string back into an object.
* @param {String} data The string to convert to an object.
* @returns {Object} The reconstituted object.
*/
Serialiser.prototype.parse = function (data) {
return this._parse(JSON.parse(data));
};
/**
* Handles restoring an object with special data markers back into
* it's original format.
* @param {Object} data The object to recurse.
* @param {Object=} target The target object to restore data to.
* @returns {Object} The final restored object.
* @private
*/
Serialiser.prototype._parse = function (data, target) {
var i;
if (typeof data === 'object' && data !== null) {
if (data instanceof Array) {
target = target || [];
} else {
target = target || {};
}
// Iterate through the object's keys and handle
// special object types and restore them
for (i in data) {
if (data.hasOwnProperty(i)) {
if (i.substr(0, 1) === '$' && this._decoder[i]) {
// This is a special object type and a handler
// exists, restore it
return this._decoder[i](data[i]);
}
// Not a special object or no handler, recurse as normal
target[i] = this._parse(data[i], target[i]);
}
}
} else {
target = data;
}
// The data is a basic type
return target;
};
/**
* Converts an object to a encoded string representation.
* @param {Object} data The object to encode.
*/
Serialiser.prototype.stringify = function (data) {
return JSON.stringify(this._stringify(data));
};
/**
* Recurse down an object and encode special objects so they can be
* stringified and later restored.
* @param {Object} data The object to parse.
* @param {Object=} target The target object to store converted data to.
* @returns {Object} The converted object.
* @private
*/
Serialiser.prototype._stringify = function (data, target) {
var handledData,
i;
if (typeof data === 'object' && data !== null) {
// Handle special object types so they can be encoded with
// a special marker and later restored by a decoder counterpart
handledData = this._encode(data);
if (handledData) {
// An encoder handled this object type so return it now
return handledData;
}
if (data instanceof Array) {
target = target || [];
} else {
target = target || {};
}
// Iterate through the object's keys and serialise
for (i in data) {
if (data.hasOwnProperty(i)) {
target[i] = this._stringify(data[i], target[i]);
}
}
} else {
target = data;
}
// The data is a basic type
return target;
};
module.exports = Serialiser;
},{}],37:[function(_dereq_,module,exports){
"use strict";
var Overload = _dereq_('./Overload');
/**
* A shared object that can be used to store arbitrary data between class
* instances, and access helper methods.
* @mixin
*/
var Shared = {
version: '1.3.412',
modules: {},
plugins: {},
_synth: {},
/**
* Adds a module to ForerunnerDB.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} module The module class.
*/
addModule: function (name, module) {
// Store the module in the module registry
this.modules[name] = module;
// Tell the universe we are loading this module
this.emit('moduleLoad', [name, module]);
},
/**
* Called by the module once all processing has been completed. Used to determine
* if the module is ready for use by other modules.
* @memberof Shared
* @param {String} name The name of the module.
*/
finishModule: function (name) {
if (this.modules[name]) {
// Set the finished loading flag to true
this.modules[name]._fdbFinished = true;
// Assign the module name to itself so it knows what it
// is called
if (this.modules[name].prototype) {
this.modules[name].prototype.className = name;
} else {
this.modules[name].className = name;
}
this.emit('moduleFinished', [name, this.modules[name]]);
} else {
throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name);
}
},
/**
* Will call your callback method when the specified module has loaded. If the module
* is already loaded the callback is called immediately.
* @memberof Shared
* @param {String} name The name of the module.
* @param {Function} callback The callback method to call when the module is loaded.
*/
moduleFinished: function (name, callback) {
if (this.modules[name] && this.modules[name]._fdbFinished) {
if (callback) { callback(name, this.modules[name]); }
} else {
this.on('moduleFinished', callback);
}
},
/**
* Determines if a module has been added to ForerunnerDB or not.
* @memberof Shared
* @param {String} name The name of the module.
* @returns {Boolean} True if the module exists or false if not.
*/
moduleExists: function (name) {
return Boolean(this.modules[name]);
},
/**
* Adds the properties and methods defined in the mixin to the passed object.
* @memberof Shared
* @param {Object} obj The target object to add mixin key/values to.
* @param {String} mixinName The name of the mixin to add to the object.
*/
mixin: new Overload({
'object, string': function (obj, mixinName) {
var mixinObj;
if (typeof mixinName === 'string') {
mixinObj = this.mixins[mixinName];
if (!mixinObj) {
throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName);
}
}
return this.$main.call(this, obj, mixinObj);
},
'object, *': function (obj, mixinObj) {
return this.$main.call(this, obj, mixinObj);
},
'$main': function (obj, mixinObj) {
if (mixinObj && typeof mixinObj === 'object') {
for (var i in mixinObj) {
if (mixinObj.hasOwnProperty(i)) {
obj[i] = mixinObj[i];
}
}
}
return obj;
}
}),
/**
* Generates a generic getter/setter method for the passed method name.
* @memberof Shared
* @param {Object} obj The object to add the getter/setter to.
* @param {String} name The name of the getter/setter to generate.
* @param {Function=} extend A method to call before executing the getter/setter.
* The existing getter/setter can be accessed from the extend method via the
* $super e.g. this.$super();
*/
synthesize: function (obj, name, extend) {
this._synth[name] = this._synth[name] || function (val) {
if (val !== undefined) {
this['_' + name] = val;
return this;
}
return this['_' + name];
};
if (extend) {
var self = this;
obj[name] = function () {
var tmp = this.$super,
ret;
this.$super = self._synth[name];
ret = extend.apply(this, arguments);
this.$super = tmp;
return ret;
};
} else {
obj[name] = this._synth[name];
}
},
/**
* Allows a method to be overloaded.
* @memberof Shared
* @param arr
* @returns {Function}
* @constructor
*/
overload: Overload,
/**
* Define the mixins that other modules can use as required.
* @memberof Shared
*/
mixins: {
'Mixin.Common': _dereq_('./Mixin.Common'),
'Mixin.Events': _dereq_('./Mixin.Events'),
'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'),
'Mixin.CRUD': _dereq_('./Mixin.CRUD'),
'Mixin.Constants': _dereq_('./Mixin.Constants'),
'Mixin.Triggers': _dereq_('./Mixin.Triggers'),
'Mixin.Sorting': _dereq_('./Mixin.Sorting'),
'Mixin.Matching': _dereq_('./Mixin.Matching'),
'Mixin.Updating': _dereq_('./Mixin.Updating'),
'Mixin.Tags': _dereq_('./Mixin.Tags')
}
};
// Add event handling to shared
Shared.mixin(Shared, 'Mixin.Events');
module.exports = Shared;
},{"./Mixin.CRUD":16,"./Mixin.ChainReactor":17,"./Mixin.Common":18,"./Mixin.Constants":19,"./Mixin.Events":20,"./Mixin.Matching":21,"./Mixin.Sorting":22,"./Mixin.Tags":23,"./Mixin.Triggers":24,"./Mixin.Updating":25,"./Overload":29}],38:[function(_dereq_,module,exports){
"use strict";
// Import external names locally
var Shared,
Db,
Collection,
CollectionGroup,
CollectionInit,
DbInit,
ReactorIO,
ActiveBucket;
Shared = _dereq_('./Shared');
/**
* Creates a new view instance.
* @param {String} name The name of the view.
* @param {Object=} query The view's query.
* @param {Object=} options An options object.
* @constructor
*/
var View = function (name, query, options) {
this.init.apply(this, arguments);
};
View.prototype.init = function (name, query, options) {
var self = this;
this._name = name;
this._listeners = {};
this._querySettings = {};
this._debug = {};
this.query(query, false);
this.queryOptions(options, false);
this._collectionDroppedWrap = function () {
self._collectionDropped.apply(self, arguments);
};
this._privateData = new Collection(this.name() + '_internalPrivate');
};
Shared.addModule('View', View);
Shared.mixin(View.prototype, 'Mixin.Common');
Shared.mixin(View.prototype, 'Mixin.ChainReactor');
Shared.mixin(View.prototype, 'Mixin.Constants');
Shared.mixin(View.prototype, 'Mixin.Triggers');
Shared.mixin(View.prototype, 'Mixin.Tags');
Collection = _dereq_('./Collection');
CollectionGroup = _dereq_('./CollectionGroup');
ActiveBucket = _dereq_('./ActiveBucket');
ReactorIO = _dereq_('./ReactorIO');
CollectionInit = Collection.prototype.init;
Db = Shared.modules.Db;
DbInit = Db.prototype.init;
/**
* Gets / sets the current state.
* @param {String=} val The name of the state to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'state');
/**
* Gets / sets the current name.
* @param {String=} val The new name to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'name');
/**
* Gets / sets the current cursor.
* @param {String=} val The new cursor to set.
* @returns {*}
*/
Shared.synthesize(View.prototype, 'cursor', function (val) {
if (val === undefined) {
return this._cursor || {};
}
this.$super.apply(this, arguments);
});
/**
* Executes an insert against the view's underlying data-source.
* @see Collection::insert()
*/
View.prototype.insert = function () {
this._from.insert.apply(this._from, arguments);
};
/**
* Executes an update against the view's underlying data-source.
* @see Collection::update()
*/
View.prototype.update = function () {
this._from.update.apply(this._from, arguments);
};
/**
* Executes an updateById against the view's underlying data-source.
* @see Collection::updateById()
*/
View.prototype.updateById = function () {
this._from.updateById.apply(this._from, arguments);
};
/**
* Executes a remove against the view's underlying data-source.
* @see Collection::remove()
*/
View.prototype.remove = function () {
this._from.remove.apply(this._from, arguments);
};
/**
* Queries the view data.
* @see Collection::find()
* @returns {Array} The result of the find query.
*/
View.prototype.find = function (query, options) {
return this.publicData().find(query, options);
};
/**
* Queries the view data for a single document.
* @see Collection::findOne()
* @returns {Object} The result of the find query.
*/
View.prototype.findOne = function (query, options) {
return this.publicData().findOne(query, options);
};
/**
* Queries the view data by specific id.
* @see Collection::findById()
* @returns {Array} The result of the find query.
*/
View.prototype.findById = function (id, options) {
return this.publicData().findById(id, options);
};
/**
* Gets the module's internal data collection.
* @returns {Collection}
*/
View.prototype.data = function () {
return this._privateData;
};
/**
* Sets the source from which the view will assemble its data.
* @param {Collection|View} source The source to use to assemble view data.
* @param {Function=} callback A callback method.
* @returns {*} If no argument is passed, returns the current value of from,
* otherwise returns itself for chaining.
*/
View.prototype.from = function (source, callback) {
var self = this;
if (source !== undefined) {
// Check if we have an existing from
if (this._from) {
// Remove the listener to the drop event
this._from.off('drop', this._collectionDroppedWrap);
delete this._from;
}
if (typeof(source) === 'string') {
source = this._db.collection(source);
}
if (source.className === 'View') {
// The source is a view so IO to the internal data collection
// instead of the view proper
source = source.privateData();
if (this.debug()) {
console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking');
}
}
this._from = source;
this._from.on('drop', this._collectionDroppedWrap);
// Create a new reactor IO graph node that intercepts chain packets from the
// view's "from" source and determines how they should be interpreted by
// this view. If the view does not have a query then this reactor IO will
// simply pass along the chain packet without modifying it.
this._io = new ReactorIO(source, this, function (chainPacket) {
var data,
diff,
query,
filteredData,
doSend,
pk,
i;
// Check that the state of the "self" object is not dropped
if (self && !self.isDropped()) {
// Check if we have a constraining query
if (self._querySettings.query) {
if (chainPacket.type === 'insert') {
data = chainPacket.data;
// Check if the data matches our query
if (data instanceof Array) {
filteredData = [];
for (i = 0; i < data.length; i++) {
if (self._privateData._match(data[i], self._querySettings.query, self._querySettings.options, 'and', {})) {
filteredData.push(data[i]);
doSend = true;
}
}
} else {
if (self._privateData._match(data, self._querySettings.query, self._querySettings.options, 'and', {})) {
filteredData = data;
doSend = true;
}
}
if (doSend) {
this.chainSend('insert', filteredData);
}
return true;
}
if (chainPacket.type === 'update') {
// Do a DB diff between this view's data and the underlying collection it reads from
// to see if something has changed
diff = self._privateData.diff(self._from.subset(self._querySettings.query, self._querySettings.options));
if (diff.insert.length || diff.remove.length) {
// Now send out new chain packets for each operation
if (diff.insert.length) {
this.chainSend('insert', diff.insert);
}
if (diff.update.length) {
pk = self._privateData.primaryKey();
for (i = 0; i < diff.update.length; i++) {
query = {};
query[pk] = diff.update[i][pk];
this.chainSend('update', {
query: query,
update: diff.update[i]
});
}
}
if (diff.remove.length) {
pk = self._privateData.primaryKey();
var $or = [],
removeQuery = {
query: {
$or: $or
}
};
for (i = 0; i < diff.remove.length; i++) {
$or.push({_id: diff.remove[i][pk]});
}
this.chainSend('remove', removeQuery);
}
// Return true to stop further propagation of the chain packet
return true;
} else {
// Returning false informs the chain reactor to continue propagation
// of the chain packet down the graph tree
return false;
}
}
}
}
// Returning false informs the chain reactor to continue propagation
// of the chain packet down the graph tree
return false;
});
var collData = source.find(this._querySettings.query, this._querySettings.options);
this._privateData.primaryKey(source.primaryKey());
this._privateData.setData(collData, {}, callback);
if (this._querySettings.options && this._querySettings.options.$orderBy) {
this.rebuildActiveBucket(this._querySettings.options.$orderBy);
} else {
this.rebuildActiveBucket();
}
return this;
}
return this._from;
};
/**
* Handles when an underlying collection the view is using as a data
* source is dropped.
* @param {Collection} collection The collection that has been dropped.
* @private
*/
View.prototype._collectionDropped = function (collection) {
if (collection) {
// Collection was dropped, remove from view
delete this._from;
}
};
/**
* Creates an index on the view.
* @see Collection::ensureIndex()
* @returns {*}
*/
View.prototype.ensureIndex = function () {
return this._privateData.ensureIndex.apply(this._privateData, arguments);
};
/**
* The chain reaction handler method for the view.
* @param {Object} chainPacket The chain reaction packet to handle.
* @private
*/
View.prototype._chainHandler = function (chainPacket) {
var //self = this,
arr,
count,
index,
insertIndex,
updates,
primaryKey,
item,
currentIndex;
if (this.debug()) {
console.log(this.logIdentifier() + ' Received chain reactor data');
}
switch (chainPacket.type) {
case 'setData':
if (this.debug()) {
console.log(this.logIdentifier() + ' Setting data in underlying (internal) view collection "' + this._privateData.name() + '"');
}
// Get the new data from our underlying data source sorted as we want
var collData = this._from.find(this._querySettings.query, this._querySettings.options);
this._privateData.setData(collData);
break;
case 'insert':
if (this.debug()) {
console.log(this.logIdentifier() + ' Inserting some data into underlying (internal) view collection "' + this._privateData.name() + '"');
}
// Decouple the data to ensure we are working with our own copy
chainPacket.data = this.decouple(chainPacket.data);
// Make sure we are working with an array
if (!(chainPacket.data instanceof Array)) {
chainPacket.data = [chainPacket.data];
}
if (this._querySettings.options && this._querySettings.options.$orderBy) {
// Loop the insert data and find each item's index
arr = chainPacket.data;
count = arr.length;
for (index = 0; index < count; index++) {
insertIndex = this._activeBucket.insert(arr[index]);
this._privateData._insertHandle(chainPacket.data, insertIndex);
}
} else {
// Set the insert index to the passed index, or if none, the end of the view data array
insertIndex = this._privateData._data.length;
this._privateData._insertHandle(chainPacket.data, insertIndex);
}
break;
case 'update':
if (this.debug()) {
console.log(this.logIdentifier() + ' Updating some data in underlying (internal) view collection "' + this._privateData.name() + '"');
}
primaryKey = this._privateData.primaryKey();
// Do the update
updates = this._privateData.update(
chainPacket.data.query,
chainPacket.data.update,
chainPacket.data.options
);
if (this._querySettings.options && this._querySettings.options.$orderBy) {
// TODO: This would be a good place to improve performance by somehow
// TODO: inspecting the change that occurred when update was performed
// TODO: above and determining if it affected the order clause keys
// TODO: and if not, skipping the active bucket updates here
// Loop the updated items and work out their new sort locations
count = updates.length;
for (index = 0; index < count; index++) {
item = updates[index];
// Remove the item from the active bucket (via it's id)
this._activeBucket.remove(item);
// Get the current location of the item
currentIndex = this._privateData._data.indexOf(item);
// Add the item back in to the active bucket
insertIndex = this._activeBucket.insert(item);
if (currentIndex !== insertIndex) {
// Move the updated item to the new index
this._privateData._updateSpliceMove(this._privateData._data, currentIndex, insertIndex);
}
}
}
break;
case 'remove':
if (this.debug()) {
console.log(this.logIdentifier() + ' Removing some data from underlying (internal) view collection "' + this._privateData.name() + '"');
}
this._privateData.remove(chainPacket.data.query, chainPacket.options);
break;
default:
break;
}
};
/**
* Listens for an event.
* @see Mixin.Events::on()
*/
View.prototype.on = function () {
return this._privateData.on.apply(this._privateData, arguments);
};
/**
* Cancels an event listener.
* @see Mixin.Events::off()
*/
View.prototype.off = function () {
return this._privateData.off.apply(this._privateData, arguments);
};
/**
* Emits an event.
* @see Mixin.Events::emit()
*/
View.prototype.emit = function () {
return this._privateData.emit.apply(this._privateData, arguments);
};
/**
* Find the distinct values for a specified field across a single collection and
* returns the results in an array.
* @param {String} key The field path to return distinct values for e.g. "person.name".
* @param {Object=} query The query to use to filter the documents used to return values from.
* @param {Object=} options The query options to use when running the query.
* @returns {Array}
*/
View.prototype.distinct = function (key, query, options) {
var coll = this.publicData();
return coll.distinct.apply(coll, arguments);
};
/**
* Gets the primary key for this view from the assigned collection.
* @see Collection::primaryKey()
* @returns {String}
*/
View.prototype.primaryKey = function () {
return this.publicData().primaryKey();
};
/**
* Drops a view and all it's stored data from the database.
* @returns {boolean} True on success, false on failure.
*/
View.prototype.drop = function (callback) {
if (!this.isDropped()) {
if (this._from) {
this._from.off('drop', this._collectionDroppedWrap);
this._from._removeView(this);
}
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Dropping');
}
this._state = 'dropped';
// Clear io and chains
if (this._io) {
this._io.drop();
}
// Drop the view's internal collection
if (this._privateData) {
this._privateData.drop();
}
if (this._publicData && this._publicData !== this._privateData) {
this._publicData.drop();
}
if (this._db && this._name) {
delete this._db._view[this._name];
}
this.emit('drop', this);
if (callback) { callback(false, true); }
delete this._chain;
delete this._from;
delete this._privateData;
delete this._io;
delete this._listeners;
delete this._querySettings;
delete this._db;
return true;
}
return false;
};
/**
* Gets / sets the db instance this class instance belongs to.
* @param {Db=} db The db instance.
* @memberof View
* @returns {*}
*/
Shared.synthesize(View.prototype, 'db', function (db) {
if (db) {
this.privateData().db(db);
this.publicData().db(db);
// Apply the same debug settings
this.debug(db.debug());
this.privateData().debug(db.debug());
this.publicData().debug(db.debug());
}
return this.$super.apply(this, arguments);
});
/**
* Gets / sets the query object and query options that the view uses
* to build it's data set. This call modifies both the query and
* query options at the same time.
* @param {Object=} query The query to set.
* @param {Boolean=} options The query options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
View.prototype.queryData = function (query, options, refresh) {
if (query !== undefined) {
this._querySettings.query = query;
}
if (options !== undefined) {
this._querySettings.options = options;
}
if (query !== undefined || options !== undefined) {
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._querySettings;
};
/**
* Add data to the existing query.
* @param {Object} obj The data whose keys will be added to the existing
* query object.
* @param {Boolean} overwrite Whether or not to overwrite data that already
* exists in the query object. Defaults to true.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
View.prototype.queryAdd = function (obj, overwrite, refresh) {
this._querySettings.query = this._querySettings.query || {};
var query = this._querySettings.query,
i;
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
if (query[i] === undefined || (query[i] !== undefined && overwrite !== false)) {
query[i] = obj[i];
}
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
};
/**
* Remove data from the existing query.
* @param {Object} obj The data whose keys will be removed from the existing
* query object.
* @param {Boolean=} refresh Whether or not to refresh the view data set
* once the operation is complete. Defaults to true.
*/
View.prototype.queryRemove = function (obj, refresh) {
var query = this._querySettings.query,
i;
if (query) {
if (obj !== undefined) {
// Loop object properties and add to existing query
for (i in obj) {
if (obj.hasOwnProperty(i)) {
delete query[i];
}
}
}
if (refresh === undefined || refresh === true) {
this.refresh();
}
}
};
/**
* Gets / sets the query being used to generate the view data. It
* does not change or modify the view's query options.
* @param {Object=} query The query to set.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
View.prototype.query = function (query, refresh) {
if (query !== undefined) {
this._querySettings.query = query;
if (refresh === undefined || refresh === true) {
this.refresh();
}
return this;
}
return this._querySettings.query;
};
/**
* Gets / sets the orderBy clause in the query options for the view.
* @param {Object=} val The order object.
* @returns {*}
*/
View.prototype.orderBy = function (val) {
if (val !== undefined) {
var queryOptions = this.queryOptions() || {};
queryOptions.$orderBy = val;
this.queryOptions(queryOptions);
return this;
}
return (this.queryOptions() || {}).$orderBy;
};
/**
* Gets / sets the page clause in the query options for the view.
* @param {Number=} val The page number to change to (zero index).
* @returns {*}
*/
View.prototype.page = function (val) {
if (val !== undefined) {
var queryOptions = this.queryOptions() || {};
// Only execute a query options update if page has changed
if (val !== queryOptions.$page) {
queryOptions.$page = val;
this.queryOptions(queryOptions);
}
return this;
}
return (this.queryOptions() || {}).$page;
};
/**
* Jump to the first page in the data set.
* @returns {*}
*/
View.prototype.pageFirst = function () {
return this.page(0);
};
/**
* Jump to the last page in the data set.
* @returns {*}
*/
View.prototype.pageLast = function () {
var pages = this.cursor().pages,
lastPage = pages !== undefined ? pages : 0;
return this.page(lastPage - 1);
};
/**
* Move forward or backwards in the data set pages by passing a positive
* or negative integer of the number of pages to move.
* @param {Number} val The number of pages to move.
* @returns {*}
*/
View.prototype.pageScan = function (val) {
if (val !== undefined) {
var pages = this.cursor().pages,
queryOptions = this.queryOptions() || {},
currentPage = queryOptions.$page !== undefined ? queryOptions.$page : 0;
currentPage += val;
if (currentPage < 0) {
currentPage = 0;
}
if (currentPage >= pages) {
currentPage = pages - 1;
}
return this.page(currentPage);
}
};
/**
* Gets / sets the query options used when applying sorting etc to the
* view data set.
* @param {Object=} options An options object.
* @param {Boolean=} refresh Whether to refresh the view data after
* this operation. Defaults to true.
* @returns {*}
*/
View.prototype.queryOptions = function (options, refresh) {
if (options !== undefined) {
this._querySettings.options = options;
if (options.$decouple === undefined) { options.$decouple = true; }
if (refresh === undefined || refresh === true) {
this.refresh();
} else {
this.rebuildActiveBucket(options.$orderBy);
}
return this;
}
return this._querySettings.options;
};
View.prototype.rebuildActiveBucket = function (orderBy) {
if (orderBy) {
var arr = this._privateData._data,
arrCount = arr.length;
// Build a new active bucket
this._activeBucket = new ActiveBucket(orderBy);
this._activeBucket.primaryKey(this._privateData.primaryKey());
// Loop the current view data and add each item
for (var i = 0; i < arrCount; i++) {
this._activeBucket.insert(arr[i]);
}
} else {
// Remove any existing active bucket
delete this._activeBucket;
}
};
/**
* Refreshes the view data such as ordering etc.
*/
View.prototype.refresh = function () {
if (this._from) {
var pubData = this.publicData(),
refreshResults;
// Re-grab all the data for the view from the collection
this._privateData.remove();
//pubData.remove();
refreshResults = this._from.find(this._querySettings.query, this._querySettings.options);
this.cursor(refreshResults.$cursor);
this._privateData.insert(refreshResults);
this._privateData._data.$cursor = refreshResults.$cursor;
pubData._data.$cursor = refreshResults.$cursor;
/*if (pubData._linked) {
// Update data and observers
//var transformedData = this._privateData.find();
// TODO: Shouldn't this data get passed into a transformIn first?
// TODO: This breaks linking because its passing decoupled data and overwriting non-decoupled data
// TODO: Is this even required anymore? After commenting it all seems to work
// TODO: Might be worth setting up a test to check transforms and linking then remove this if working?
//jQuery.observable(pubData._data).refresh(transformedData);
}*/
}
if (this._querySettings.options && this._querySettings.options.$orderBy) {
this.rebuildActiveBucket(this._querySettings.options.$orderBy);
} else {
this.rebuildActiveBucket();
}
return this;
};
/**
* Returns the number of documents currently in the view.
* @returns {Number}
*/
View.prototype.count = function () {
if (this.publicData()) {
return this.publicData().count.apply(this.publicData(), arguments);
}
return 0;
};
// Call underlying
View.prototype.subset = function () {
return this.publicData().subset.apply(this._privateData, arguments);
};
/**
* Takes the passed data and uses it to set transform methods and globally
* enable or disable the transform system for the view.
* @param {Object} obj The new transform system settings "enabled", "dataIn" and "dataOut":
* {
* "enabled": true,
* "dataIn": function (data) { return data; },
* "dataOut": function (data) { return data; }
* }
* @returns {*}
*/
View.prototype.transform = function (obj) {
var self = this;
if (obj !== undefined) {
if (typeof obj === "object") {
if (obj.enabled !== undefined) {
this._transformEnabled = obj.enabled;
}
if (obj.dataIn !== undefined) {
this._transformIn = obj.dataIn;
}
if (obj.dataOut !== undefined) {
this._transformOut = obj.dataOut;
}
} else {
this._transformEnabled = obj !== false;
}
if (this._transformEnabled) {
// Check for / create the public data collection
if (!this._publicData) {
// Create the public data collection
this._publicData = new Collection('__FDB__view_publicData_' + this._name);
this._publicData.db(this._privateData._db);
this._publicData.transform({
enabled: true,
dataIn: this._transformIn,
dataOut: this._transformOut
});
// Create a chain reaction IO node to keep the private and
// public data collections in sync
this._transformIo = new ReactorIO(this._privateData, this._publicData, function (chainPacket) {
var data = chainPacket.data;
switch (chainPacket.type) {
case 'primaryKey':
self._publicData.primaryKey(data);
this.chainSend('primaryKey', data);
break;
case 'setData':
self._publicData.setData(data);
this.chainSend('setData', data);
break;
case 'insert':
self._publicData.insert(data);
this.chainSend('insert', data);
break;
case 'update':
// Do the update
self._publicData.update(
data.query,
data.update,
data.options
);
this.chainSend('update', data);
break;
case 'remove':
self._publicData.remove(data.query, chainPacket.options);
this.chainSend('remove', data);
break;
default:
break;
}
});
}
// Set initial data and settings
this._publicData.primaryKey(this.privateData().primaryKey());
this._publicData.setData(this.privateData().find());
} else {
// Remove the public data collection
if (this._publicData) {
this._publicData.drop();
delete this._publicData;
if (this._transformIo) {
this._transformIo.drop();
delete this._transformIo;
}
}
}
return this;
}
return {
enabled: this._transformEnabled,
dataIn: this._transformIn,
dataOut: this._transformOut
};
};
/**
* Executes a method against each document that matches query and returns an
* array of documents that may have been modified by the method.
* @param {Object} query The query object.
* @param {Function} func The method that each document is passed to. If this method
* returns false for a particular document it is excluded from the results.
* @param {Object=} options Optional options object.
* @returns {Array}
*/
View.prototype.filter = function (query, func, options) {
return (this.publicData()).filter(query, func, options);
};
/**
* Returns the non-transformed data the view holds as a collection
* reference.
* @return {Collection} The non-transformed collection reference.
*/
View.prototype.privateData = function () {
return this._privateData;
};
/**
* Returns a data object representing the public data this view
* contains. This can change depending on if transforms are being
* applied to the view or not.
*
* If no transforms are applied then the public data will be the
* same as the private data the view holds. If transforms are
* applied then the public data will contain the transformed version
* of the private data.
*
* The public data collection is also used by data binding to only
* changes to the publicData will show in a data-bound element.
*/
View.prototype.publicData = function () {
if (this._transformEnabled) {
return this._publicData;
} else {
return this._privateData;
}
};
// Extend collection with view init
Collection.prototype.init = function () {
this._view = [];
CollectionInit.apply(this, arguments);
};
/**
* Creates a view and assigns the collection as its data source.
* @param {String} name The name of the new view.
* @param {Object} query The query to apply to the new view.
* @param {Object} options The options object to apply to the view.
* @returns {*}
*/
Collection.prototype.view = function (name, query, options) {
if (this._db && this._db._view ) {
if (!this._db._view[name]) {
var view = new View(name, query, options)
.db(this._db)
.from(this);
this._view = this._view || [];
this._view.push(view);
return view;
} else {
throw(this.logIdentifier() + ' Cannot create a view using this collection because a view with this name already exists: ' + name);
}
}
};
/**
* Adds a view to the internal view lookup.
* @param {View} view The view to add.
* @returns {Collection}
* @private
*/
Collection.prototype._addView = CollectionGroup.prototype._addView = function (view) {
if (view !== undefined) {
this._view.push(view);
}
return this;
};
/**
* Removes a view from the internal view lookup.
* @param {View} view The view to remove.
* @returns {Collection}
* @private
*/
Collection.prototype._removeView = CollectionGroup.prototype._removeView = function (view) {
if (view !== undefined) {
var index = this._view.indexOf(view);
if (index > -1) {
this._view.splice(index, 1);
}
}
return this;
};
// Extend DB with views init
Db.prototype.init = function () {
this._view = {};
DbInit.apply(this, arguments);
};
/**
* Gets a view by it's name.
* @param {String} viewName The name of the view to retrieve.
* @returns {*}
*/
Db.prototype.view = function (viewName) {
// Handle being passed an instance
if (viewName instanceof View) {
return viewName;
}
if (!this._view[viewName]) {
if (this.debug() || (this._db && this._db.debug())) {
console.log(this.logIdentifier() + ' Creating view ' + viewName);
}
}
this._view[viewName] = this._view[viewName] || new View(viewName).db(this);
return this._view[viewName];
};
/**
* Determine if a view with the passed name already exists.
* @param {String} viewName The name of the view to check for.
* @returns {boolean}
*/
Db.prototype.viewExists = function (viewName) {
return Boolean(this._view[viewName]);
};
/**
* Returns an array of views the DB currently has.
* @returns {Array} An array of objects containing details of each view
* the database is currently managing.
*/
Db.prototype.views = function () {
var arr = [],
view,
i;
for (i in this._view) {
if (this._view.hasOwnProperty(i)) {
view = this._view[i];
arr.push({
name: i,
count: view.count(),
linked: view.isLinked !== undefined ? view.isLinked() : false
});
}
}
return arr;
};
Shared.finishModule('View');
module.exports = View;
},{"./ActiveBucket":2,"./Collection":4,"./CollectionGroup":5,"./ReactorIO":35,"./Shared":37}],39:[function(_dereq_,module,exports){
(function (process,global){
/*!
* async
* https://github.com/caolan/async
*
* Copyright 2010-2014 Caolan McMahon
* Released under the MIT license
*/
(function () {
var async = {};
function noop() {}
function identity(v) {
return v;
}
function toBool(v) {
return !!v;
}
function notId(v) {
return !v;
}
// global on the server, window in the browser
var previous_async;
// Establish the root object, `window` (`self`) in the browser, `global`
// on the server, or `this` in some virtual machines. We use `self`
// instead of `window` for `WebWorker` support.
var root = typeof self === 'object' && self.self === self && self ||
typeof global === 'object' && global.global === global && global ||
this;
if (root != null) {
previous_async = root.async;
}
async.noConflict = function () {
root.async = previous_async;
return async;
};
function only_once(fn) {
return function() {
if (fn === null) throw new Error("Callback was already called.");
fn.apply(this, arguments);
fn = null;
};
}
function _once(fn) {
return function() {
if (fn === null) return;
fn.apply(this, arguments);
fn = null;
};
}
//// cross-browser compatiblity functions ////
var _toString = Object.prototype.toString;
var _isArray = Array.isArray || function (obj) {
return _toString.call(obj) === '[object Array]';
};
// Ported from underscore.js isObject
var _isObject = function(obj) {
var type = typeof obj;
return type === 'function' || type === 'object' && !!obj;
};
function _isArrayLike(arr) {
return _isArray(arr) || (
// has a positive integer length property
typeof arr.length === "number" &&
arr.length >= 0 &&
arr.length % 1 === 0
);
}
function _arrayEach(arr, iterator) {
var index = -1,
length = arr.length;
while (++index < length) {
iterator(arr[index], index, arr);
}
}
function _map(arr, iterator) {
var index = -1,
length = arr.length,
result = Array(length);
while (++index < length) {
result[index] = iterator(arr[index], index, arr);
}
return result;
}
function _range(count) {
return _map(Array(count), function (v, i) { return i; });
}
function _reduce(arr, iterator, memo) {
_arrayEach(arr, function (x, i, a) {
memo = iterator(memo, x, i, a);
});
return memo;
}
function _forEachOf(object, iterator) {
_arrayEach(_keys(object), function (key) {
iterator(object[key], key);
});
}
function _indexOf(arr, item) {
for (var i = 0; i < arr.length; i++) {
if (arr[i] === item) return i;
}
return -1;
}
var _keys = Object.keys || function (obj) {
var keys = [];
for (var k in obj) {
if (obj.hasOwnProperty(k)) {
keys.push(k);
}
}
return keys;
};
function _keyIterator(coll) {
var i = -1;
var len;
var keys;
if (_isArrayLike(coll)) {
len = coll.length;
return function next() {
i++;
return i < len ? i : null;
};
} else {
keys = _keys(coll);
len = keys.length;
return function next() {
i++;
return i < len ? keys[i] : null;
};
}
}
// Similar to ES6's rest param (http://ariya.ofilabs.com/2013/03/es6-and-rest-parameter.html)
// This accumulates the arguments passed into an array, after a given index.
// From underscore.js (https://github.com/jashkenas/underscore/pull/2140).
function _restParam(func, startIndex) {
startIndex = startIndex == null ? func.length - 1 : +startIndex;
return function() {
var length = Math.max(arguments.length - startIndex, 0);
var rest = Array(length);
for (var index = 0; index < length; index++) {
rest[index] = arguments[index + startIndex];
}
switch (startIndex) {
case 0: return func.call(this, rest);
case 1: return func.call(this, arguments[0], rest);
}
// Currently unused but handle cases outside of the switch statement:
// var args = Array(startIndex + 1);
// for (index = 0; index < startIndex; index++) {
// args[index] = arguments[index];
// }
// args[startIndex] = rest;
// return func.apply(this, args);
};
}
function _withoutIndex(iterator) {
return function (value, index, callback) {
return iterator(value, callback);
};
}
//// exported async module functions ////
//// nextTick implementation with browser-compatible fallback ////
// capture the global reference to guard against fakeTimer mocks
var _setImmediate = typeof setImmediate === 'function' && setImmediate;
var _delay = _setImmediate ? function(fn) {
// not a direct alias for IE10 compatibility
_setImmediate(fn);
} : function(fn) {
setTimeout(fn, 0);
};
if (typeof process === 'object' && typeof process.nextTick === 'function') {
async.nextTick = process.nextTick;
} else {
async.nextTick = _delay;
}
async.setImmediate = _setImmediate ? _delay : async.nextTick;
async.forEach =
async.each = function (arr, iterator, callback) {
return async.eachOf(arr, _withoutIndex(iterator), callback);
};
async.forEachSeries =
async.eachSeries = function (arr, iterator, callback) {
return async.eachOfSeries(arr, _withoutIndex(iterator), callback);
};
async.forEachLimit =
async.eachLimit = function (arr, limit, iterator, callback) {
return _eachOfLimit(limit)(arr, _withoutIndex(iterator), callback);
};
async.forEachOf =
async.eachOf = function (object, iterator, callback) {
callback = _once(callback || noop);
object = object || [];
var iter = _keyIterator(object);
var key, completed = 0;
while ((key = iter()) != null) {
completed += 1;
iterator(object[key], key, only_once(done));
}
if (completed === 0) callback(null);
function done(err) {
completed--;
if (err) {
callback(err);
}
// Check key is null in case iterator isn't exhausted
// and done resolved synchronously.
else if (key === null && completed <= 0) {
callback(null);
}
}
};
async.forEachOfSeries =
async.eachOfSeries = function (obj, iterator, callback) {
callback = _once(callback || noop);
obj = obj || [];
var nextKey = _keyIterator(obj);
var key = nextKey();
function iterate() {
var sync = true;
if (key === null) {
return callback(null);
}
iterator(obj[key], key, only_once(function (err) {
if (err) {
callback(err);
}
else {
key = nextKey();
if (key === null) {
return callback(null);
} else {
if (sync) {
async.setImmediate(iterate);
} else {
iterate();
}
}
}
}));
sync = false;
}
iterate();
};
async.forEachOfLimit =
async.eachOfLimit = function (obj, limit, iterator, callback) {
_eachOfLimit(limit)(obj, iterator, callback);
};
function _eachOfLimit(limit) {
return function (obj, iterator, callback) {
callback = _once(callback || noop);
obj = obj || [];
var nextKey = _keyIterator(obj);
if (limit <= 0) {
return callback(null);
}
var done = false;
var running = 0;
var errored = false;
(function replenish () {
if (done && running <= 0) {
return callback(null);
}
while (running < limit && !errored) {
var key = nextKey();
if (key === null) {
done = true;
if (running <= 0) {
callback(null);
}
return;
}
running += 1;
iterator(obj[key], key, only_once(function (err) {
running -= 1;
if (err) {
callback(err);
errored = true;
}
else {
replenish();
}
}));
}
})();
};
}
function doParallel(fn) {
return function (obj, iterator, callback) {
return fn(async.eachOf, obj, iterator, callback);
};
}
function doParallelLimit(fn) {
return function (obj, limit, iterator, callback) {
return fn(_eachOfLimit(limit), obj, iterator, callback);
};
}
function doSeries(fn) {
return function (obj, iterator, callback) {
return fn(async.eachOfSeries, obj, iterator, callback);
};
}
function _asyncMap(eachfn, arr, iterator, callback) {
callback = _once(callback || noop);
arr = arr || [];
var results = _isArrayLike(arr) ? [] : {};
eachfn(arr, function (value, index, callback) {
iterator(value, function (err, v) {
results[index] = v;
callback(err);
});
}, function (err) {
callback(err, results);
});
}
async.map = doParallel(_asyncMap);
async.mapSeries = doSeries(_asyncMap);
async.mapLimit = doParallelLimit(_asyncMap);
// reduce only has a series version, as doing reduce in parallel won't
// work in many situations.
async.inject =
async.foldl =
async.reduce = function (arr, memo, iterator, callback) {
async.eachOfSeries(arr, function (x, i, callback) {
iterator(memo, x, function (err, v) {
memo = v;
callback(err);
});
}, function (err) {
callback(err, memo);
});
};
async.foldr =
async.reduceRight = function (arr, memo, iterator, callback) {
var reversed = _map(arr, identity).reverse();
async.reduce(reversed, memo, iterator, callback);
};
async.transform = function (arr, memo, iterator, callback) {
if (arguments.length === 3) {
callback = iterator;
iterator = memo;
memo = _isArray(arr) ? [] : {};
}
async.eachOf(arr, function(v, k, cb) {
iterator(memo, v, k, cb);
}, function(err) {
callback(err, memo);
});
};
function _filter(eachfn, arr, iterator, callback) {
var results = [];
eachfn(arr, function (x, index, callback) {
iterator(x, function (v) {
if (v) {
results.push({index: index, value: x});
}
callback();
});
}, function () {
callback(_map(results.sort(function (a, b) {
return a.index - b.index;
}), function (x) {
return x.value;
}));
});
}
async.select =
async.filter = doParallel(_filter);
async.selectLimit =
async.filterLimit = doParallelLimit(_filter);
async.selectSeries =
async.filterSeries = doSeries(_filter);
function _reject(eachfn, arr, iterator, callback) {
_filter(eachfn, arr, function(value, cb) {
iterator(value, function(v) {
cb(!v);
});
}, callback);
}
async.reject = doParallel(_reject);
async.rejectLimit = doParallelLimit(_reject);
async.rejectSeries = doSeries(_reject);
function _createTester(eachfn, check, getResult) {
return function(arr, limit, iterator, cb) {
function done() {
if (cb) cb(getResult(false, void 0));
}
function iteratee(x, _, callback) {
if (!cb) return callback();
iterator(x, function (v) {
if (cb && check(v)) {
cb(getResult(true, x));
cb = iterator = false;
}
callback();
});
}
if (arguments.length > 3) {
eachfn(arr, limit, iteratee, done);
} else {
cb = iterator;
iterator = limit;
eachfn(arr, iteratee, done);
}
};
}
async.any =
async.some = _createTester(async.eachOf, toBool, identity);
async.someLimit = _createTester(async.eachOfLimit, toBool, identity);
async.all =
async.every = _createTester(async.eachOf, notId, notId);
async.everyLimit = _createTester(async.eachOfLimit, notId, notId);
function _findGetResult(v, x) {
return x;
}
async.detect = _createTester(async.eachOf, identity, _findGetResult);
async.detectSeries = _createTester(async.eachOfSeries, identity, _findGetResult);
async.detectLimit = _createTester(async.eachOfLimit, identity, _findGetResult);
async.sortBy = function (arr, iterator, callback) {
async.map(arr, function (x, callback) {
iterator(x, function (err, criteria) {
if (err) {
callback(err);
}
else {
callback(null, {value: x, criteria: criteria});
}
});
}, function (err, results) {
if (err) {
return callback(err);
}
else {
callback(null, _map(results.sort(comparator), function (x) {
return x.value;
}));
}
});
function comparator(left, right) {
var a = left.criteria, b = right.criteria;
return a < b ? -1 : a > b ? 1 : 0;
}
};
async.auto = function (tasks, concurrency, callback) {
if (!callback) {
// concurrency is optional, shift the args.
callback = concurrency;
concurrency = null;
}
callback = _once(callback || noop);
var keys = _keys(tasks);
var remainingTasks = keys.length;
if (!remainingTasks) {
return callback(null);
}
if (!concurrency) {
concurrency = remainingTasks;
}
var results = {};
var runningTasks = 0;
var listeners = [];
function addListener(fn) {
listeners.unshift(fn);
}
function removeListener(fn) {
var idx = _indexOf(listeners, fn);
if (idx >= 0) listeners.splice(idx, 1);
}
function taskComplete() {
remainingTasks--;
_arrayEach(listeners.slice(0), function (fn) {
fn();
});
}
addListener(function () {
if (!remainingTasks) {
callback(null, results);
}
});
_arrayEach(keys, function (k) {
var task = _isArray(tasks[k]) ? tasks[k]: [tasks[k]];
var taskCallback = _restParam(function(err, args) {
runningTasks--;
if (args.length <= 1) {
args = args[0];
}
if (err) {
var safeResults = {};
_forEachOf(results, function(val, rkey) {
safeResults[rkey] = val;
});
safeResults[k] = args;
callback(err, safeResults);
}
else {
results[k] = args;
async.setImmediate(taskComplete);
}
});
var requires = task.slice(0, task.length - 1);
// prevent dead-locks
var len = requires.length;
var dep;
while (len--) {
if (!(dep = tasks[requires[len]])) {
throw new Error('Has inexistant dependency');
}
if (_isArray(dep) && _indexOf(dep, k) >= 0) {
throw new Error('Has cyclic dependencies');
}
}
function ready() {
return runningTasks < concurrency && _reduce(requires, function (a, x) {
return (a && results.hasOwnProperty(x));
}, true) && !results.hasOwnProperty(k);
}
if (ready()) {
runningTasks++;
task[task.length - 1](taskCallback, results);
}
else {
addListener(listener);
}
function listener() {
if (ready()) {
runningTasks++;
removeListener(listener);
task[task.length - 1](taskCallback, results);
}
}
});
};
async.retry = function(times, task, callback) {
var DEFAULT_TIMES = 5;
var DEFAULT_INTERVAL = 0;
var attempts = [];
var opts = {
times: DEFAULT_TIMES,
interval: DEFAULT_INTERVAL
};
function parseTimes(acc, t){
if(typeof t === 'number'){
acc.times = parseInt(t, 10) || DEFAULT_TIMES;
} else if(typeof t === 'object'){
acc.times = parseInt(t.times, 10) || DEFAULT_TIMES;
acc.interval = parseInt(t.interval, 10) || DEFAULT_INTERVAL;
} else {
throw new Error('Unsupported argument type for \'times\': ' + typeof t);
}
}
var length = arguments.length;
if (length < 1 || length > 3) {
throw new Error('Invalid arguments - must be either (task), (task, callback), (times, task) or (times, task, callback)');
} else if (length <= 2 && typeof times === 'function') {
callback = task;
task = times;
}
if (typeof times !== 'function') {
parseTimes(opts, times);
}
opts.callback = callback;
opts.task = task;
function wrappedTask(wrappedCallback, wrappedResults) {
function retryAttempt(task, finalAttempt) {
return function(seriesCallback) {
task(function(err, result){
seriesCallback(!err || finalAttempt, {err: err, result: result});
}, wrappedResults);
};
}
function retryInterval(interval){
return function(seriesCallback){
setTimeout(function(){
seriesCallback(null);
}, interval);
};
}
while (opts.times) {
var finalAttempt = !(opts.times-=1);
attempts.push(retryAttempt(opts.task, finalAttempt));
if(!finalAttempt && opts.interval > 0){
attempts.push(retryInterval(opts.interval));
}
}
async.series(attempts, function(done, data){
data = data[data.length - 1];
(wrappedCallback || opts.callback)(data.err, data.result);
});
}
// If a callback is passed, run this as a controll flow
return opts.callback ? wrappedTask() : wrappedTask;
};
async.waterfall = function (tasks, callback) {
callback = _once(callback || noop);
if (!_isArray(tasks)) {
var err = new Error('First argument to waterfall must be an array of functions');
return callback(err);
}
if (!tasks.length) {
return callback();
}
function wrapIterator(iterator) {
return _restParam(function (err, args) {
if (err) {
callback.apply(null, [err].concat(args));
}
else {
var next = iterator.next();
if (next) {
args.push(wrapIterator(next));
}
else {
args.push(callback);
}
ensureAsync(iterator).apply(null, args);
}
});
}
wrapIterator(async.iterator(tasks))();
};
function _parallel(eachfn, tasks, callback) {
callback = callback || noop;
var results = _isArrayLike(tasks) ? [] : {};
eachfn(tasks, function (task, key, callback) {
task(_restParam(function (err, args) {
if (args.length <= 1) {
args = args[0];
}
results[key] = args;
callback(err);
}));
}, function (err) {
callback(err, results);
});
}
async.parallel = function (tasks, callback) {
_parallel(async.eachOf, tasks, callback);
};
async.parallelLimit = function(tasks, limit, callback) {
_parallel(_eachOfLimit(limit), tasks, callback);
};
async.series = function(tasks, callback) {
_parallel(async.eachOfSeries, tasks, callback);
};
async.iterator = function (tasks) {
function makeCallback(index) {
function fn() {
if (tasks.length) {
tasks[index].apply(null, arguments);
}
return fn.next();
}
fn.next = function () {
return (index < tasks.length - 1) ? makeCallback(index + 1): null;
};
return fn;
}
return makeCallback(0);
};
async.apply = _restParam(function (fn, args) {
return _restParam(function (callArgs) {
return fn.apply(
null, args.concat(callArgs)
);
});
});
function _concat(eachfn, arr, fn, callback) {
var result = [];
eachfn(arr, function (x, index, cb) {
fn(x, function (err, y) {
result = result.concat(y || []);
cb(err);
});
}, function (err) {
callback(err, result);
});
}
async.concat = doParallel(_concat);
async.concatSeries = doSeries(_concat);
async.whilst = function (test, iterator, callback) {
callback = callback || noop;
if (test()) {
var next = _restParam(function(err, args) {
if (err) {
callback(err);
} else if (test.apply(this, args)) {
iterator(next);
} else {
callback(null);
}
});
iterator(next);
} else {
callback(null);
}
};
async.doWhilst = function (iterator, test, callback) {
var calls = 0;
return async.whilst(function() {
return ++calls <= 1 || test.apply(this, arguments);
}, iterator, callback);
};
async.until = function (test, iterator, callback) {
return async.whilst(function() {
return !test.apply(this, arguments);
}, iterator, callback);
};
async.doUntil = function (iterator, test, callback) {
return async.doWhilst(iterator, function() {
return !test.apply(this, arguments);
}, callback);
};
async.during = function (test, iterator, callback) {
callback = callback || noop;
var next = _restParam(function(err, args) {
if (err) {
callback(err);
} else {
args.push(check);
test.apply(this, args);
}
});
var check = function(err, truth) {
if (err) {
callback(err);
} else if (truth) {
iterator(next);
} else {
callback(null);
}
};
test(check);
};
async.doDuring = function (iterator, test, callback) {
var calls = 0;
async.during(function(next) {
if (calls++ < 1) {
next(null, true);
} else {
test.apply(this, arguments);
}
}, iterator, callback);
};
function _queue(worker, concurrency, payload) {
if (concurrency == null) {
concurrency = 1;
}
else if(concurrency === 0) {
throw new Error('Concurrency must not be zero');
}
function _insert(q, data, pos, callback) {
if (callback != null && typeof callback !== "function") {
throw new Error("task callback must be a function");
}
q.started = true;
if (!_isArray(data)) {
data = [data];
}
if(data.length === 0 && q.idle()) {
// call drain immediately if there are no tasks
return async.setImmediate(function() {
q.drain();
});
}
_arrayEach(data, function(task) {
var item = {
data: task,
callback: callback || noop
};
if (pos) {
q.tasks.unshift(item);
} else {
q.tasks.push(item);
}
if (q.tasks.length === q.concurrency) {
q.saturated();
}
});
async.setImmediate(q.process);
}
function _next(q, tasks) {
return function(){
workers -= 1;
var removed = false;
var args = arguments;
_arrayEach(tasks, function (task) {
_arrayEach(workersList, function (worker, index) {
if (worker === task && !removed) {
workersList.splice(index, 1);
removed = true;
}
});
task.callback.apply(task, args);
});
if (q.tasks.length + workers === 0) {
q.drain();
}
q.process();
};
}
var workers = 0;
var workersList = [];
var q = {
tasks: [],
concurrency: concurrency,
payload: payload,
saturated: noop,
empty: noop,
drain: noop,
started: false,
paused: false,
push: function (data, callback) {
_insert(q, data, false, callback);
},
kill: function () {
q.drain = noop;
q.tasks = [];
},
unshift: function (data, callback) {
_insert(q, data, true, callback);
},
process: function () {
if (!q.paused && workers < q.concurrency && q.tasks.length) {
while(workers < q.concurrency && q.tasks.length){
var tasks = q.payload ?
q.tasks.splice(0, q.payload) :
q.tasks.splice(0, q.tasks.length);
var data = _map(tasks, function (task) {
return task.data;
});
if (q.tasks.length === 0) {
q.empty();
}
workers += 1;
workersList.push(tasks[0]);
var cb = only_once(_next(q, tasks));
worker(data, cb);
}
}
},
length: function () {
return q.tasks.length;
},
running: function () {
return workers;
},
workersList: function () {
return workersList;
},
idle: function() {
return q.tasks.length + workers === 0;
},
pause: function () {
q.paused = true;
},
resume: function () {
if (q.paused === false) { return; }
q.paused = false;
var resumeCount = Math.min(q.concurrency, q.tasks.length);
// Need to call q.process once per concurrent
// worker to preserve full concurrency after pause
for (var w = 1; w <= resumeCount; w++) {
async.setImmediate(q.process);
}
}
};
return q;
}
async.queue = function (worker, concurrency) {
var q = _queue(function (items, cb) {
worker(items[0], cb);
}, concurrency, 1);
return q;
};
async.priorityQueue = function (worker, concurrency) {
function _compareTasks(a, b){
return a.priority - b.priority;
}
function _binarySearch(sequence, item, compare) {
var beg = -1,
end = sequence.length - 1;
while (beg < end) {
var mid = beg + ((end - beg + 1) >>> 1);
if (compare(item, sequence[mid]) >= 0) {
beg = mid;
} else {
end = mid - 1;
}
}
return beg;
}
function _insert(q, data, priority, callback) {
if (callback != null && typeof callback !== "function") {
throw new Error("task callback must be a function");
}
q.started = true;
if (!_isArray(data)) {
data = [data];
}
if(data.length === 0) {
// call drain immediately if there are no tasks
return async.setImmediate(function() {
q.drain();
});
}
_arrayEach(data, function(task) {
var item = {
data: task,
priority: priority,
callback: typeof callback === 'function' ? callback : noop
};
q.tasks.splice(_binarySearch(q.tasks, item, _compareTasks) + 1, 0, item);
if (q.tasks.length === q.concurrency) {
q.saturated();
}
async.setImmediate(q.process);
});
}
// Start with a normal queue
var q = async.queue(worker, concurrency);
// Override push to accept second parameter representing priority
q.push = function (data, priority, callback) {
_insert(q, data, priority, callback);
};
// Remove unshift function
delete q.unshift;
return q;
};
async.cargo = function (worker, payload) {
return _queue(worker, 1, payload);
};
function _console_fn(name) {
return _restParam(function (fn, args) {
fn.apply(null, args.concat([_restParam(function (err, args) {
if (typeof console === 'object') {
if (err) {
if (console.error) {
console.error(err);
}
}
else if (console[name]) {
_arrayEach(args, function (x) {
console[name](x);
});
}
}
})]));
});
}
async.log = _console_fn('log');
async.dir = _console_fn('dir');
/*async.info = _console_fn('info');
async.warn = _console_fn('warn');
async.error = _console_fn('error');*/
async.memoize = function (fn, hasher) {
var memo = {};
var queues = {};
hasher = hasher || identity;
var memoized = _restParam(function memoized(args) {
var callback = args.pop();
var key = hasher.apply(null, args);
if (key in memo) {
async.setImmediate(function () {
callback.apply(null, memo[key]);
});
}
else if (key in queues) {
queues[key].push(callback);
}
else {
queues[key] = [callback];
fn.apply(null, args.concat([_restParam(function (args) {
memo[key] = args;
var q = queues[key];
delete queues[key];
for (var i = 0, l = q.length; i < l; i++) {
q[i].apply(null, args);
}
})]));
}
});
memoized.memo = memo;
memoized.unmemoized = fn;
return memoized;
};
async.unmemoize = function (fn) {
return function () {
return (fn.unmemoized || fn).apply(null, arguments);
};
};
function _times(mapper) {
return function (count, iterator, callback) {
mapper(_range(count), iterator, callback);
};
}
async.times = _times(async.map);
async.timesSeries = _times(async.mapSeries);
async.timesLimit = function (count, limit, iterator, callback) {
return async.mapLimit(_range(count), limit, iterator, callback);
};
async.seq = function (/* functions... */) {
var fns = arguments;
return _restParam(function (args) {
var that = this;
var callback = args[args.length - 1];
if (typeof callback == 'function') {
args.pop();
} else {
callback = noop;
}
async.reduce(fns, args, function (newargs, fn, cb) {
fn.apply(that, newargs.concat([_restParam(function (err, nextargs) {
cb(err, nextargs);
})]));
},
function (err, results) {
callback.apply(that, [err].concat(results));
});
});
};
async.compose = function (/* functions... */) {
return async.seq.apply(null, Array.prototype.reverse.call(arguments));
};
function _applyEach(eachfn) {
return _restParam(function(fns, args) {
var go = _restParam(function(args) {
var that = this;
var callback = args.pop();
return eachfn(fns, function (fn, _, cb) {
fn.apply(that, args.concat([cb]));
},
callback);
});
if (args.length) {
return go.apply(this, args);
}
else {
return go;
}
});
}
async.applyEach = _applyEach(async.eachOf);
async.applyEachSeries = _applyEach(async.eachOfSeries);
async.forever = function (fn, callback) {
var done = only_once(callback || noop);
var task = ensureAsync(fn);
function next(err) {
if (err) {
return done(err);
}
task(next);
}
next();
};
function ensureAsync(fn) {
return _restParam(function (args) {
var callback = args.pop();
args.push(function () {
var innerArgs = arguments;
if (sync) {
async.setImmediate(function () {
callback.apply(null, innerArgs);
});
} else {
callback.apply(null, innerArgs);
}
});
var sync = true;
fn.apply(this, args);
sync = false;
});
}
async.ensureAsync = ensureAsync;
async.constant = _restParam(function(values) {
var args = [null].concat(values);
return function (callback) {
return callback.apply(this, args);
};
});
async.wrapSync =
async.asyncify = function asyncify(func) {
return _restParam(function (args) {
var callback = args.pop();
var result;
try {
result = func.apply(this, args);
} catch (e) {
return callback(e);
}
// if result is Promise object
if (_isObject(result) && typeof result.then === "function") {
result.then(function(value) {
callback(null, value);
})["catch"](function(err) {
callback(err.message ? err : new Error(err));
});
} else {
callback(null, result);
}
});
};
// Node.js
if (typeof module === 'object' && module.exports) {
module.exports = async;
}
// AMD / RequireJS
else if (typeof define === 'function' && define.amd) {
define([], function () {
return async;
});
}
// included directly via <script> tag
else {
root.async = async;
}
}());
}).call(this,_dereq_('_process'),typeof global !== "undefined" ? global : typeof self !== "undefined" ? self : typeof window !== "undefined" ? window : {})
},{"_process":74}],40:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var BlockCipher = C_lib.BlockCipher;
var C_algo = C.algo;
// Lookup tables
var SBOX = [];
var INV_SBOX = [];
var SUB_MIX_0 = [];
var SUB_MIX_1 = [];
var SUB_MIX_2 = [];
var SUB_MIX_3 = [];
var INV_SUB_MIX_0 = [];
var INV_SUB_MIX_1 = [];
var INV_SUB_MIX_2 = [];
var INV_SUB_MIX_3 = [];
// Compute lookup tables
(function () {
// Compute double table
var d = [];
for (var i = 0; i < 256; i++) {
if (i < 128) {
d[i] = i << 1;
} else {
d[i] = (i << 1) ^ 0x11b;
}
}
// Walk GF(2^8)
var x = 0;
var xi = 0;
for (var i = 0; i < 256; i++) {
// Compute sbox
var sx = xi ^ (xi << 1) ^ (xi << 2) ^ (xi << 3) ^ (xi << 4);
sx = (sx >>> 8) ^ (sx & 0xff) ^ 0x63;
SBOX[x] = sx;
INV_SBOX[sx] = x;
// Compute multiplication
var x2 = d[x];
var x4 = d[x2];
var x8 = d[x4];
// Compute sub bytes, mix columns tables
var t = (d[sx] * 0x101) ^ (sx * 0x1010100);
SUB_MIX_0[x] = (t << 24) | (t >>> 8);
SUB_MIX_1[x] = (t << 16) | (t >>> 16);
SUB_MIX_2[x] = (t << 8) | (t >>> 24);
SUB_MIX_3[x] = t;
// Compute inv sub bytes, inv mix columns tables
var t = (x8 * 0x1010101) ^ (x4 * 0x10001) ^ (x2 * 0x101) ^ (x * 0x1010100);
INV_SUB_MIX_0[sx] = (t << 24) | (t >>> 8);
INV_SUB_MIX_1[sx] = (t << 16) | (t >>> 16);
INV_SUB_MIX_2[sx] = (t << 8) | (t >>> 24);
INV_SUB_MIX_3[sx] = t;
// Compute next counter
if (!x) {
x = xi = 1;
} else {
x = x2 ^ d[d[d[x8 ^ x2]]];
xi ^= d[d[xi]];
}
}
}());
// Precomputed Rcon lookup
var RCON = [0x00, 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80, 0x1b, 0x36];
/**
* AES block cipher algorithm.
*/
var AES = C_algo.AES = BlockCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
var keySize = key.sigBytes / 4;
// Compute number of rounds
var nRounds = this._nRounds = keySize + 6
// Compute number of key schedule rows
var ksRows = (nRounds + 1) * 4;
// Compute key schedule
var keySchedule = this._keySchedule = [];
for (var ksRow = 0; ksRow < ksRows; ksRow++) {
if (ksRow < keySize) {
keySchedule[ksRow] = keyWords[ksRow];
} else {
var t = keySchedule[ksRow - 1];
if (!(ksRow % keySize)) {
// Rot word
t = (t << 8) | (t >>> 24);
// Sub word
t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff];
// Mix Rcon
t ^= RCON[(ksRow / keySize) | 0] << 24;
} else if (keySize > 6 && ksRow % keySize == 4) {
// Sub word
t = (SBOX[t >>> 24] << 24) | (SBOX[(t >>> 16) & 0xff] << 16) | (SBOX[(t >>> 8) & 0xff] << 8) | SBOX[t & 0xff];
}
keySchedule[ksRow] = keySchedule[ksRow - keySize] ^ t;
}
}
// Compute inv key schedule
var invKeySchedule = this._invKeySchedule = [];
for (var invKsRow = 0; invKsRow < ksRows; invKsRow++) {
var ksRow = ksRows - invKsRow;
if (invKsRow % 4) {
var t = keySchedule[ksRow];
} else {
var t = keySchedule[ksRow - 4];
}
if (invKsRow < 4 || ksRow <= 4) {
invKeySchedule[invKsRow] = t;
} else {
invKeySchedule[invKsRow] = INV_SUB_MIX_0[SBOX[t >>> 24]] ^ INV_SUB_MIX_1[SBOX[(t >>> 16) & 0xff]] ^
INV_SUB_MIX_2[SBOX[(t >>> 8) & 0xff]] ^ INV_SUB_MIX_3[SBOX[t & 0xff]];
}
}
},
encryptBlock: function (M, offset) {
this._doCryptBlock(M, offset, this._keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX);
},
decryptBlock: function (M, offset) {
// Swap 2nd and 4th rows
var t = M[offset + 1];
M[offset + 1] = M[offset + 3];
M[offset + 3] = t;
this._doCryptBlock(M, offset, this._invKeySchedule, INV_SUB_MIX_0, INV_SUB_MIX_1, INV_SUB_MIX_2, INV_SUB_MIX_3, INV_SBOX);
// Inv swap 2nd and 4th rows
var t = M[offset + 1];
M[offset + 1] = M[offset + 3];
M[offset + 3] = t;
},
_doCryptBlock: function (M, offset, keySchedule, SUB_MIX_0, SUB_MIX_1, SUB_MIX_2, SUB_MIX_3, SBOX) {
// Shortcut
var nRounds = this._nRounds;
// Get input, add round key
var s0 = M[offset] ^ keySchedule[0];
var s1 = M[offset + 1] ^ keySchedule[1];
var s2 = M[offset + 2] ^ keySchedule[2];
var s3 = M[offset + 3] ^ keySchedule[3];
// Key schedule row counter
var ksRow = 4;
// Rounds
for (var round = 1; round < nRounds; round++) {
// Shift rows, sub bytes, mix columns, add round key
var t0 = SUB_MIX_0[s0 >>> 24] ^ SUB_MIX_1[(s1 >>> 16) & 0xff] ^ SUB_MIX_2[(s2 >>> 8) & 0xff] ^ SUB_MIX_3[s3 & 0xff] ^ keySchedule[ksRow++];
var t1 = SUB_MIX_0[s1 >>> 24] ^ SUB_MIX_1[(s2 >>> 16) & 0xff] ^ SUB_MIX_2[(s3 >>> 8) & 0xff] ^ SUB_MIX_3[s0 & 0xff] ^ keySchedule[ksRow++];
var t2 = SUB_MIX_0[s2 >>> 24] ^ SUB_MIX_1[(s3 >>> 16) & 0xff] ^ SUB_MIX_2[(s0 >>> 8) & 0xff] ^ SUB_MIX_3[s1 & 0xff] ^ keySchedule[ksRow++];
var t3 = SUB_MIX_0[s3 >>> 24] ^ SUB_MIX_1[(s0 >>> 16) & 0xff] ^ SUB_MIX_2[(s1 >>> 8) & 0xff] ^ SUB_MIX_3[s2 & 0xff] ^ keySchedule[ksRow++];
// Update state
s0 = t0;
s1 = t1;
s2 = t2;
s3 = t3;
}
// Shift rows, sub bytes, add round key
var t0 = ((SBOX[s0 >>> 24] << 24) | (SBOX[(s1 >>> 16) & 0xff] << 16) | (SBOX[(s2 >>> 8) & 0xff] << 8) | SBOX[s3 & 0xff]) ^ keySchedule[ksRow++];
var t1 = ((SBOX[s1 >>> 24] << 24) | (SBOX[(s2 >>> 16) & 0xff] << 16) | (SBOX[(s3 >>> 8) & 0xff] << 8) | SBOX[s0 & 0xff]) ^ keySchedule[ksRow++];
var t2 = ((SBOX[s2 >>> 24] << 24) | (SBOX[(s3 >>> 16) & 0xff] << 16) | (SBOX[(s0 >>> 8) & 0xff] << 8) | SBOX[s1 & 0xff]) ^ keySchedule[ksRow++];
var t3 = ((SBOX[s3 >>> 24] << 24) | (SBOX[(s0 >>> 16) & 0xff] << 16) | (SBOX[(s1 >>> 8) & 0xff] << 8) | SBOX[s2 & 0xff]) ^ keySchedule[ksRow++];
// Set output
M[offset] = t0;
M[offset + 1] = t1;
M[offset + 2] = t2;
M[offset + 3] = t3;
},
keySize: 256/32
});
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.AES.encrypt(message, key, cfg);
* var plaintext = CryptoJS.AES.decrypt(ciphertext, key, cfg);
*/
C.AES = BlockCipher._createHelper(AES);
}());
return CryptoJS.AES;
}));
},{"./cipher-core":41,"./core":42,"./enc-base64":43,"./evpkdf":45,"./md5":50}],41:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Cipher core components.
*/
CryptoJS.lib.Cipher || (function (undefined) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var WordArray = C_lib.WordArray;
var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm;
var C_enc = C.enc;
var Utf8 = C_enc.Utf8;
var Base64 = C_enc.Base64;
var C_algo = C.algo;
var EvpKDF = C_algo.EvpKDF;
/**
* Abstract base cipher template.
*
* @property {number} keySize This cipher's key size. Default: 4 (128 bits)
* @property {number} ivSize This cipher's IV size. Default: 4 (128 bits)
* @property {number} _ENC_XFORM_MODE A constant representing encryption mode.
* @property {number} _DEC_XFORM_MODE A constant representing decryption mode.
*/
var Cipher = C_lib.Cipher = BufferedBlockAlgorithm.extend({
/**
* Configuration options.
*
* @property {WordArray} iv The IV to use for this operation.
*/
cfg: Base.extend(),
/**
* Creates this cipher in encryption mode.
*
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {Cipher} A cipher instance.
*
* @static
*
* @example
*
* var cipher = CryptoJS.algo.AES.createEncryptor(keyWordArray, { iv: ivWordArray });
*/
createEncryptor: function (key, cfg) {
return this.create(this._ENC_XFORM_MODE, key, cfg);
},
/**
* Creates this cipher in decryption mode.
*
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {Cipher} A cipher instance.
*
* @static
*
* @example
*
* var cipher = CryptoJS.algo.AES.createDecryptor(keyWordArray, { iv: ivWordArray });
*/
createDecryptor: function (key, cfg) {
return this.create(this._DEC_XFORM_MODE, key, cfg);
},
/**
* Initializes a newly created cipher.
*
* @param {number} xformMode Either the encryption or decryption transormation mode constant.
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @example
*
* var cipher = CryptoJS.algo.AES.create(CryptoJS.algo.AES._ENC_XFORM_MODE, keyWordArray, { iv: ivWordArray });
*/
init: function (xformMode, key, cfg) {
// Apply config defaults
this.cfg = this.cfg.extend(cfg);
// Store transform mode and key
this._xformMode = xformMode;
this._key = key;
// Set initial values
this.reset();
},
/**
* Resets this cipher to its initial state.
*
* @example
*
* cipher.reset();
*/
reset: function () {
// Reset data buffer
BufferedBlockAlgorithm.reset.call(this);
// Perform concrete-cipher logic
this._doReset();
},
/**
* Adds data to be encrypted or decrypted.
*
* @param {WordArray|string} dataUpdate The data to encrypt or decrypt.
*
* @return {WordArray} The data after processing.
*
* @example
*
* var encrypted = cipher.process('data');
* var encrypted = cipher.process(wordArray);
*/
process: function (dataUpdate) {
// Append
this._append(dataUpdate);
// Process available blocks
return this._process();
},
/**
* Finalizes the encryption or decryption process.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} dataUpdate The final data to encrypt or decrypt.
*
* @return {WordArray} The data after final processing.
*
* @example
*
* var encrypted = cipher.finalize();
* var encrypted = cipher.finalize('data');
* var encrypted = cipher.finalize(wordArray);
*/
finalize: function (dataUpdate) {
// Final data update
if (dataUpdate) {
this._append(dataUpdate);
}
// Perform concrete-cipher logic
var finalProcessedData = this._doFinalize();
return finalProcessedData;
},
keySize: 128/32,
ivSize: 128/32,
_ENC_XFORM_MODE: 1,
_DEC_XFORM_MODE: 2,
/**
* Creates shortcut functions to a cipher's object interface.
*
* @param {Cipher} cipher The cipher to create a helper for.
*
* @return {Object} An object with encrypt and decrypt shortcut functions.
*
* @static
*
* @example
*
* var AES = CryptoJS.lib.Cipher._createHelper(CryptoJS.algo.AES);
*/
_createHelper: (function () {
function selectCipherStrategy(key) {
if (typeof key == 'string') {
return PasswordBasedCipher;
} else {
return SerializableCipher;
}
}
return function (cipher) {
return {
encrypt: function (message, key, cfg) {
return selectCipherStrategy(key).encrypt(cipher, message, key, cfg);
},
decrypt: function (ciphertext, key, cfg) {
return selectCipherStrategy(key).decrypt(cipher, ciphertext, key, cfg);
}
};
};
}())
});
/**
* Abstract base stream cipher template.
*
* @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 1 (32 bits)
*/
var StreamCipher = C_lib.StreamCipher = Cipher.extend({
_doFinalize: function () {
// Process partial blocks
var finalProcessedBlocks = this._process(!!'flush');
return finalProcessedBlocks;
},
blockSize: 1
});
/**
* Mode namespace.
*/
var C_mode = C.mode = {};
/**
* Abstract base block cipher mode template.
*/
var BlockCipherMode = C_lib.BlockCipherMode = Base.extend({
/**
* Creates this mode for encryption.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @static
*
* @example
*
* var mode = CryptoJS.mode.CBC.createEncryptor(cipher, iv.words);
*/
createEncryptor: function (cipher, iv) {
return this.Encryptor.create(cipher, iv);
},
/**
* Creates this mode for decryption.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @static
*
* @example
*
* var mode = CryptoJS.mode.CBC.createDecryptor(cipher, iv.words);
*/
createDecryptor: function (cipher, iv) {
return this.Decryptor.create(cipher, iv);
},
/**
* Initializes a newly created mode.
*
* @param {Cipher} cipher A block cipher instance.
* @param {Array} iv The IV words.
*
* @example
*
* var mode = CryptoJS.mode.CBC.Encryptor.create(cipher, iv.words);
*/
init: function (cipher, iv) {
this._cipher = cipher;
this._iv = iv;
}
});
/**
* Cipher Block Chaining mode.
*/
var CBC = C_mode.CBC = (function () {
/**
* Abstract base CBC mode.
*/
var CBC = BlockCipherMode.extend();
/**
* CBC encryptor.
*/
CBC.Encryptor = CBC.extend({
/**
* Processes the data block at offset.
*
* @param {Array} words The data words to operate on.
* @param {number} offset The offset where the block starts.
*
* @example
*
* mode.processBlock(data.words, offset);
*/
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
// XOR and encrypt
xorBlock.call(this, words, offset, blockSize);
cipher.encryptBlock(words, offset);
// Remember this block to use with next block
this._prevBlock = words.slice(offset, offset + blockSize);
}
});
/**
* CBC decryptor.
*/
CBC.Decryptor = CBC.extend({
/**
* Processes the data block at offset.
*
* @param {Array} words The data words to operate on.
* @param {number} offset The offset where the block starts.
*
* @example
*
* mode.processBlock(data.words, offset);
*/
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
// Remember this block to use with next block
var thisBlock = words.slice(offset, offset + blockSize);
// Decrypt and XOR
cipher.decryptBlock(words, offset);
xorBlock.call(this, words, offset, blockSize);
// This block becomes the previous block
this._prevBlock = thisBlock;
}
});
function xorBlock(words, offset, blockSize) {
// Shortcut
var iv = this._iv;
// Choose mixing block
if (iv) {
var block = iv;
// Remove IV for subsequent blocks
this._iv = undefined;
} else {
var block = this._prevBlock;
}
// XOR blocks
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= block[i];
}
}
return CBC;
}());
/**
* Padding namespace.
*/
var C_pad = C.pad = {};
/**
* PKCS #5/7 padding strategy.
*/
var Pkcs7 = C_pad.Pkcs7 = {
/**
* Pads data using the algorithm defined in PKCS #5/7.
*
* @param {WordArray} data The data to pad.
* @param {number} blockSize The multiple that the data should be padded to.
*
* @static
*
* @example
*
* CryptoJS.pad.Pkcs7.pad(wordArray, 4);
*/
pad: function (data, blockSize) {
// Shortcut
var blockSizeBytes = blockSize * 4;
// Count padding bytes
var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes;
// Create padding word
var paddingWord = (nPaddingBytes << 24) | (nPaddingBytes << 16) | (nPaddingBytes << 8) | nPaddingBytes;
// Create padding
var paddingWords = [];
for (var i = 0; i < nPaddingBytes; i += 4) {
paddingWords.push(paddingWord);
}
var padding = WordArray.create(paddingWords, nPaddingBytes);
// Add padding
data.concat(padding);
},
/**
* Unpads data that had been padded using the algorithm defined in PKCS #5/7.
*
* @param {WordArray} data The data to unpad.
*
* @static
*
* @example
*
* CryptoJS.pad.Pkcs7.unpad(wordArray);
*/
unpad: function (data) {
// Get number of padding bytes from last byte
var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff;
// Remove padding
data.sigBytes -= nPaddingBytes;
}
};
/**
* Abstract base block cipher template.
*
* @property {number} blockSize The number of 32-bit words this cipher operates on. Default: 4 (128 bits)
*/
var BlockCipher = C_lib.BlockCipher = Cipher.extend({
/**
* Configuration options.
*
* @property {Mode} mode The block mode to use. Default: CBC
* @property {Padding} padding The padding strategy to use. Default: Pkcs7
*/
cfg: Cipher.cfg.extend({
mode: CBC,
padding: Pkcs7
}),
reset: function () {
// Reset cipher
Cipher.reset.call(this);
// Shortcuts
var cfg = this.cfg;
var iv = cfg.iv;
var mode = cfg.mode;
// Reset block mode
if (this._xformMode == this._ENC_XFORM_MODE) {
var modeCreator = mode.createEncryptor;
} else /* if (this._xformMode == this._DEC_XFORM_MODE) */ {
var modeCreator = mode.createDecryptor;
// Keep at least one block in the buffer for unpadding
this._minBufferSize = 1;
}
this._mode = modeCreator.call(mode, this, iv && iv.words);
},
_doProcessBlock: function (words, offset) {
this._mode.processBlock(words, offset);
},
_doFinalize: function () {
// Shortcut
var padding = this.cfg.padding;
// Finalize
if (this._xformMode == this._ENC_XFORM_MODE) {
// Pad data
padding.pad(this._data, this.blockSize);
// Process final blocks
var finalProcessedBlocks = this._process(!!'flush');
} else /* if (this._xformMode == this._DEC_XFORM_MODE) */ {
// Process final blocks
var finalProcessedBlocks = this._process(!!'flush');
// Unpad data
padding.unpad(finalProcessedBlocks);
}
return finalProcessedBlocks;
},
blockSize: 128/32
});
/**
* A collection of cipher parameters.
*
* @property {WordArray} ciphertext The raw ciphertext.
* @property {WordArray} key The key to this ciphertext.
* @property {WordArray} iv The IV used in the ciphering operation.
* @property {WordArray} salt The salt used with a key derivation function.
* @property {Cipher} algorithm The cipher algorithm.
* @property {Mode} mode The block mode used in the ciphering operation.
* @property {Padding} padding The padding scheme used in the ciphering operation.
* @property {number} blockSize The block size of the cipher.
* @property {Format} formatter The default formatting strategy to convert this cipher params object to a string.
*/
var CipherParams = C_lib.CipherParams = Base.extend({
/**
* Initializes a newly created cipher params object.
*
* @param {Object} cipherParams An object with any of the possible cipher parameters.
*
* @example
*
* var cipherParams = CryptoJS.lib.CipherParams.create({
* ciphertext: ciphertextWordArray,
* key: keyWordArray,
* iv: ivWordArray,
* salt: saltWordArray,
* algorithm: CryptoJS.algo.AES,
* mode: CryptoJS.mode.CBC,
* padding: CryptoJS.pad.PKCS7,
* blockSize: 4,
* formatter: CryptoJS.format.OpenSSL
* });
*/
init: function (cipherParams) {
this.mixIn(cipherParams);
},
/**
* Converts this cipher params object to a string.
*
* @param {Format} formatter (Optional) The formatting strategy to use.
*
* @return {string} The stringified cipher params.
*
* @throws Error If neither the formatter nor the default formatter is set.
*
* @example
*
* var string = cipherParams + '';
* var string = cipherParams.toString();
* var string = cipherParams.toString(CryptoJS.format.OpenSSL);
*/
toString: function (formatter) {
return (formatter || this.formatter).stringify(this);
}
});
/**
* Format namespace.
*/
var C_format = C.format = {};
/**
* OpenSSL formatting strategy.
*/
var OpenSSLFormatter = C_format.OpenSSL = {
/**
* Converts a cipher params object to an OpenSSL-compatible string.
*
* @param {CipherParams} cipherParams The cipher params object.
*
* @return {string} The OpenSSL-compatible string.
*
* @static
*
* @example
*
* var openSSLString = CryptoJS.format.OpenSSL.stringify(cipherParams);
*/
stringify: function (cipherParams) {
// Shortcuts
var ciphertext = cipherParams.ciphertext;
var salt = cipherParams.salt;
// Format
if (salt) {
var wordArray = WordArray.create([0x53616c74, 0x65645f5f]).concat(salt).concat(ciphertext);
} else {
var wordArray = ciphertext;
}
return wordArray.toString(Base64);
},
/**
* Converts an OpenSSL-compatible string to a cipher params object.
*
* @param {string} openSSLStr The OpenSSL-compatible string.
*
* @return {CipherParams} The cipher params object.
*
* @static
*
* @example
*
* var cipherParams = CryptoJS.format.OpenSSL.parse(openSSLString);
*/
parse: function (openSSLStr) {
// Parse base64
var ciphertext = Base64.parse(openSSLStr);
// Shortcut
var ciphertextWords = ciphertext.words;
// Test for salt
if (ciphertextWords[0] == 0x53616c74 && ciphertextWords[1] == 0x65645f5f) {
// Extract salt
var salt = WordArray.create(ciphertextWords.slice(2, 4));
// Remove salt from ciphertext
ciphertextWords.splice(0, 4);
ciphertext.sigBytes -= 16;
}
return CipherParams.create({ ciphertext: ciphertext, salt: salt });
}
};
/**
* A cipher wrapper that returns ciphertext as a serializable cipher params object.
*/
var SerializableCipher = C_lib.SerializableCipher = Base.extend({
/**
* Configuration options.
*
* @property {Formatter} format The formatting strategy to convert cipher param objects to and from a string. Default: OpenSSL
*/
cfg: Base.extend({
format: OpenSSLFormatter
}),
/**
* Encrypts a message.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {WordArray|string} message The message to encrypt.
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {CipherParams} A cipher params object.
*
* @static
*
* @example
*
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key);
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv });
* var ciphertextParams = CryptoJS.lib.SerializableCipher.encrypt(CryptoJS.algo.AES, message, key, { iv: iv, format: CryptoJS.format.OpenSSL });
*/
encrypt: function (cipher, message, key, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Encrypt
var encryptor = cipher.createEncryptor(key, cfg);
var ciphertext = encryptor.finalize(message);
// Shortcut
var cipherCfg = encryptor.cfg;
// Create and return serializable cipher params
return CipherParams.create({
ciphertext: ciphertext,
key: key,
iv: cipherCfg.iv,
algorithm: cipher,
mode: cipherCfg.mode,
padding: cipherCfg.padding,
blockSize: cipher.blockSize,
formatter: cfg.format
});
},
/**
* Decrypts serialized ciphertext.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {CipherParams|string} ciphertext The ciphertext to decrypt.
* @param {WordArray} key The key.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {WordArray} The plaintext.
*
* @static
*
* @example
*
* var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, key, { iv: iv, format: CryptoJS.format.OpenSSL });
* var plaintext = CryptoJS.lib.SerializableCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, key, { iv: iv, format: CryptoJS.format.OpenSSL });
*/
decrypt: function (cipher, ciphertext, key, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Convert string to CipherParams
ciphertext = this._parse(ciphertext, cfg.format);
// Decrypt
var plaintext = cipher.createDecryptor(key, cfg).finalize(ciphertext.ciphertext);
return plaintext;
},
/**
* Converts serialized ciphertext to CipherParams,
* else assumed CipherParams already and returns ciphertext unchanged.
*
* @param {CipherParams|string} ciphertext The ciphertext.
* @param {Formatter} format The formatting strategy to use to parse serialized ciphertext.
*
* @return {CipherParams} The unserialized ciphertext.
*
* @static
*
* @example
*
* var ciphertextParams = CryptoJS.lib.SerializableCipher._parse(ciphertextStringOrParams, format);
*/
_parse: function (ciphertext, format) {
if (typeof ciphertext == 'string') {
return format.parse(ciphertext, this);
} else {
return ciphertext;
}
}
});
/**
* Key derivation function namespace.
*/
var C_kdf = C.kdf = {};
/**
* OpenSSL key derivation function.
*/
var OpenSSLKdf = C_kdf.OpenSSL = {
/**
* Derives a key and IV from a password.
*
* @param {string} password The password to derive from.
* @param {number} keySize The size in words of the key to generate.
* @param {number} ivSize The size in words of the IV to generate.
* @param {WordArray|string} salt (Optional) A 64-bit salt to use. If omitted, a salt will be generated randomly.
*
* @return {CipherParams} A cipher params object with the key, IV, and salt.
*
* @static
*
* @example
*
* var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32);
* var derivedParams = CryptoJS.kdf.OpenSSL.execute('Password', 256/32, 128/32, 'saltsalt');
*/
execute: function (password, keySize, ivSize, salt) {
// Generate random salt
if (!salt) {
salt = WordArray.random(64/8);
}
// Derive key and IV
var key = EvpKDF.create({ keySize: keySize + ivSize }).compute(password, salt);
// Separate key and IV
var iv = WordArray.create(key.words.slice(keySize), ivSize * 4);
key.sigBytes = keySize * 4;
// Return params
return CipherParams.create({ key: key, iv: iv, salt: salt });
}
};
/**
* A serializable cipher wrapper that derives the key from a password,
* and returns ciphertext as a serializable cipher params object.
*/
var PasswordBasedCipher = C_lib.PasswordBasedCipher = SerializableCipher.extend({
/**
* Configuration options.
*
* @property {KDF} kdf The key derivation function to use to generate a key and IV from a password. Default: OpenSSL
*/
cfg: SerializableCipher.cfg.extend({
kdf: OpenSSLKdf
}),
/**
* Encrypts a message using a password.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {WordArray|string} message The message to encrypt.
* @param {string} password The password.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {CipherParams} A cipher params object.
*
* @static
*
* @example
*
* var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password');
* var ciphertextParams = CryptoJS.lib.PasswordBasedCipher.encrypt(CryptoJS.algo.AES, message, 'password', { format: CryptoJS.format.OpenSSL });
*/
encrypt: function (cipher, message, password, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Derive key and other params
var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize);
// Add IV to config
cfg.iv = derivedParams.iv;
// Encrypt
var ciphertext = SerializableCipher.encrypt.call(this, cipher, message, derivedParams.key, cfg);
// Mix in derived params
ciphertext.mixIn(derivedParams);
return ciphertext;
},
/**
* Decrypts serialized ciphertext using a password.
*
* @param {Cipher} cipher The cipher algorithm to use.
* @param {CipherParams|string} ciphertext The ciphertext to decrypt.
* @param {string} password The password.
* @param {Object} cfg (Optional) The configuration options to use for this operation.
*
* @return {WordArray} The plaintext.
*
* @static
*
* @example
*
* var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, formattedCiphertext, 'password', { format: CryptoJS.format.OpenSSL });
* var plaintext = CryptoJS.lib.PasswordBasedCipher.decrypt(CryptoJS.algo.AES, ciphertextParams, 'password', { format: CryptoJS.format.OpenSSL });
*/
decrypt: function (cipher, ciphertext, password, cfg) {
// Apply config defaults
cfg = this.cfg.extend(cfg);
// Convert string to CipherParams
ciphertext = this._parse(ciphertext, cfg.format);
// Derive key and other params
var derivedParams = cfg.kdf.execute(password, cipher.keySize, cipher.ivSize, ciphertext.salt);
// Add IV to config
cfg.iv = derivedParams.iv;
// Decrypt
var plaintext = SerializableCipher.decrypt.call(this, cipher, ciphertext, derivedParams.key, cfg);
return plaintext;
}
});
}());
}));
},{"./core":42}],42:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory();
}
else if (typeof define === "function" && define.amd) {
// AMD
define([], factory);
}
else {
// Global (browser)
root.CryptoJS = factory();
}
}(this, function () {
/**
* CryptoJS core components.
*/
var CryptoJS = CryptoJS || (function (Math, undefined) {
/**
* CryptoJS namespace.
*/
var C = {};
/**
* Library namespace.
*/
var C_lib = C.lib = {};
/**
* Base object for prototypal inheritance.
*/
var Base = C_lib.Base = (function () {
function F() {}
return {
/**
* Creates a new object that inherits from this object.
*
* @param {Object} overrides Properties to copy into the new object.
*
* @return {Object} The new object.
*
* @static
*
* @example
*
* var MyType = CryptoJS.lib.Base.extend({
* field: 'value',
*
* method: function () {
* }
* });
*/
extend: function (overrides) {
// Spawn
F.prototype = this;
var subtype = new F();
// Augment
if (overrides) {
subtype.mixIn(overrides);
}
// Create default initializer
if (!subtype.hasOwnProperty('init')) {
subtype.init = function () {
subtype.$super.init.apply(this, arguments);
};
}
// Initializer's prototype is the subtype object
subtype.init.prototype = subtype;
// Reference supertype
subtype.$super = this;
return subtype;
},
/**
* Extends this object and runs the init method.
* Arguments to create() will be passed to init().
*
* @return {Object} The new object.
*
* @static
*
* @example
*
* var instance = MyType.create();
*/
create: function () {
var instance = this.extend();
instance.init.apply(instance, arguments);
return instance;
},
/**
* Initializes a newly created object.
* Override this method to add some logic when your objects are created.
*
* @example
*
* var MyType = CryptoJS.lib.Base.extend({
* init: function () {
* // ...
* }
* });
*/
init: function () {
},
/**
* Copies properties into this object.
*
* @param {Object} properties The properties to mix in.
*
* @example
*
* MyType.mixIn({
* field: 'value'
* });
*/
mixIn: function (properties) {
for (var propertyName in properties) {
if (properties.hasOwnProperty(propertyName)) {
this[propertyName] = properties[propertyName];
}
}
// IE won't copy toString using the loop above
if (properties.hasOwnProperty('toString')) {
this.toString = properties.toString;
}
},
/**
* Creates a copy of this object.
*
* @return {Object} The clone.
*
* @example
*
* var clone = instance.clone();
*/
clone: function () {
return this.init.prototype.extend(this);
}
};
}());
/**
* An array of 32-bit words.
*
* @property {Array} words The array of 32-bit words.
* @property {number} sigBytes The number of significant bytes in this word array.
*/
var WordArray = C_lib.WordArray = Base.extend({
/**
* Initializes a newly created word array.
*
* @param {Array} words (Optional) An array of 32-bit words.
* @param {number} sigBytes (Optional) The number of significant bytes in the words.
*
* @example
*
* var wordArray = CryptoJS.lib.WordArray.create();
* var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607]);
* var wordArray = CryptoJS.lib.WordArray.create([0x00010203, 0x04050607], 6);
*/
init: function (words, sigBytes) {
words = this.words = words || [];
if (sigBytes != undefined) {
this.sigBytes = sigBytes;
} else {
this.sigBytes = words.length * 4;
}
},
/**
* Converts this word array to a string.
*
* @param {Encoder} encoder (Optional) The encoding strategy to use. Default: CryptoJS.enc.Hex
*
* @return {string} The stringified word array.
*
* @example
*
* var string = wordArray + '';
* var string = wordArray.toString();
* var string = wordArray.toString(CryptoJS.enc.Utf8);
*/
toString: function (encoder) {
return (encoder || Hex).stringify(this);
},
/**
* Concatenates a word array to this word array.
*
* @param {WordArray} wordArray The word array to append.
*
* @return {WordArray} This word array.
*
* @example
*
* wordArray1.concat(wordArray2);
*/
concat: function (wordArray) {
// Shortcuts
var thisWords = this.words;
var thatWords = wordArray.words;
var thisSigBytes = this.sigBytes;
var thatSigBytes = wordArray.sigBytes;
// Clamp excess bits
this.clamp();
// Concat
if (thisSigBytes % 4) {
// Copy one byte at a time
for (var i = 0; i < thatSigBytes; i++) {
var thatByte = (thatWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
thisWords[(thisSigBytes + i) >>> 2] |= thatByte << (24 - ((thisSigBytes + i) % 4) * 8);
}
} else {
// Copy one word at a time
for (var i = 0; i < thatSigBytes; i += 4) {
thisWords[(thisSigBytes + i) >>> 2] = thatWords[i >>> 2];
}
}
this.sigBytes += thatSigBytes;
// Chainable
return this;
},
/**
* Removes insignificant bits.
*
* @example
*
* wordArray.clamp();
*/
clamp: function () {
// Shortcuts
var words = this.words;
var sigBytes = this.sigBytes;
// Clamp
words[sigBytes >>> 2] &= 0xffffffff << (32 - (sigBytes % 4) * 8);
words.length = Math.ceil(sigBytes / 4);
},
/**
* Creates a copy of this word array.
*
* @return {WordArray} The clone.
*
* @example
*
* var clone = wordArray.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
clone.words = this.words.slice(0);
return clone;
},
/**
* Creates a word array filled with random bytes.
*
* @param {number} nBytes The number of random bytes to generate.
*
* @return {WordArray} The random word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.lib.WordArray.random(16);
*/
random: function (nBytes) {
var words = [];
var r = (function (m_w) {
var m_w = m_w;
var m_z = 0x3ade68b1;
var mask = 0xffffffff;
return function () {
m_z = (0x9069 * (m_z & 0xFFFF) + (m_z >> 0x10)) & mask;
m_w = (0x4650 * (m_w & 0xFFFF) + (m_w >> 0x10)) & mask;
var result = ((m_z << 0x10) + m_w) & mask;
result /= 0x100000000;
result += 0.5;
return result * (Math.random() > .5 ? 1 : -1);
}
});
for (var i = 0, rcache; i < nBytes; i += 4) {
var _r = r((rcache || Math.random()) * 0x100000000);
rcache = _r() * 0x3ade67b7;
words.push((_r() * 0x100000000) | 0);
}
return new WordArray.init(words, nBytes);
}
});
/**
* Encoder namespace.
*/
var C_enc = C.enc = {};
/**
* Hex encoding strategy.
*/
var Hex = C_enc.Hex = {
/**
* Converts a word array to a hex string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The hex string.
*
* @static
*
* @example
*
* var hexString = CryptoJS.enc.Hex.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var hexChars = [];
for (var i = 0; i < sigBytes; i++) {
var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
hexChars.push((bite >>> 4).toString(16));
hexChars.push((bite & 0x0f).toString(16));
}
return hexChars.join('');
},
/**
* Converts a hex string to a word array.
*
* @param {string} hexStr The hex string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Hex.parse(hexString);
*/
parse: function (hexStr) {
// Shortcut
var hexStrLength = hexStr.length;
// Convert
var words = [];
for (var i = 0; i < hexStrLength; i += 2) {
words[i >>> 3] |= parseInt(hexStr.substr(i, 2), 16) << (24 - (i % 8) * 4);
}
return new WordArray.init(words, hexStrLength / 2);
}
};
/**
* Latin1 encoding strategy.
*/
var Latin1 = C_enc.Latin1 = {
/**
* Converts a word array to a Latin1 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The Latin1 string.
*
* @static
*
* @example
*
* var latin1String = CryptoJS.enc.Latin1.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var latin1Chars = [];
for (var i = 0; i < sigBytes; i++) {
var bite = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
latin1Chars.push(String.fromCharCode(bite));
}
return latin1Chars.join('');
},
/**
* Converts a Latin1 string to a word array.
*
* @param {string} latin1Str The Latin1 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Latin1.parse(latin1String);
*/
parse: function (latin1Str) {
// Shortcut
var latin1StrLength = latin1Str.length;
// Convert
var words = [];
for (var i = 0; i < latin1StrLength; i++) {
words[i >>> 2] |= (latin1Str.charCodeAt(i) & 0xff) << (24 - (i % 4) * 8);
}
return new WordArray.init(words, latin1StrLength);
}
};
/**
* UTF-8 encoding strategy.
*/
var Utf8 = C_enc.Utf8 = {
/**
* Converts a word array to a UTF-8 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-8 string.
*
* @static
*
* @example
*
* var utf8String = CryptoJS.enc.Utf8.stringify(wordArray);
*/
stringify: function (wordArray) {
try {
return decodeURIComponent(escape(Latin1.stringify(wordArray)));
} catch (e) {
throw new Error('Malformed UTF-8 data');
}
},
/**
* Converts a UTF-8 string to a word array.
*
* @param {string} utf8Str The UTF-8 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf8.parse(utf8String);
*/
parse: function (utf8Str) {
return Latin1.parse(unescape(encodeURIComponent(utf8Str)));
}
};
/**
* Abstract buffered block algorithm template.
*
* The property blockSize must be implemented in a concrete subtype.
*
* @property {number} _minBufferSize The number of blocks that should be kept unprocessed in the buffer. Default: 0
*/
var BufferedBlockAlgorithm = C_lib.BufferedBlockAlgorithm = Base.extend({
/**
* Resets this block algorithm's data buffer to its initial state.
*
* @example
*
* bufferedBlockAlgorithm.reset();
*/
reset: function () {
// Initial values
this._data = new WordArray.init();
this._nDataBytes = 0;
},
/**
* Adds new data to this block algorithm's buffer.
*
* @param {WordArray|string} data The data to append. Strings are converted to a WordArray using UTF-8.
*
* @example
*
* bufferedBlockAlgorithm._append('data');
* bufferedBlockAlgorithm._append(wordArray);
*/
_append: function (data) {
// Convert string to WordArray, else assume WordArray already
if (typeof data == 'string') {
data = Utf8.parse(data);
}
// Append
this._data.concat(data);
this._nDataBytes += data.sigBytes;
},
/**
* Processes available data blocks.
*
* This method invokes _doProcessBlock(offset), which must be implemented by a concrete subtype.
*
* @param {boolean} doFlush Whether all blocks and partial blocks should be processed.
*
* @return {WordArray} The processed data.
*
* @example
*
* var processedData = bufferedBlockAlgorithm._process();
* var processedData = bufferedBlockAlgorithm._process(!!'flush');
*/
_process: function (doFlush) {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var dataSigBytes = data.sigBytes;
var blockSize = this.blockSize;
var blockSizeBytes = blockSize * 4;
// Count blocks ready
var nBlocksReady = dataSigBytes / blockSizeBytes;
if (doFlush) {
// Round up to include partial blocks
nBlocksReady = Math.ceil(nBlocksReady);
} else {
// Round down to include only full blocks,
// less the number of blocks that must remain in the buffer
nBlocksReady = Math.max((nBlocksReady | 0) - this._minBufferSize, 0);
}
// Count words ready
var nWordsReady = nBlocksReady * blockSize;
// Count bytes ready
var nBytesReady = Math.min(nWordsReady * 4, dataSigBytes);
// Process blocks
if (nWordsReady) {
for (var offset = 0; offset < nWordsReady; offset += blockSize) {
// Perform concrete-algorithm logic
this._doProcessBlock(dataWords, offset);
}
// Remove processed words
var processedWords = dataWords.splice(0, nWordsReady);
data.sigBytes -= nBytesReady;
}
// Return processed words
return new WordArray.init(processedWords, nBytesReady);
},
/**
* Creates a copy of this object.
*
* @return {Object} The clone.
*
* @example
*
* var clone = bufferedBlockAlgorithm.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
clone._data = this._data.clone();
return clone;
},
_minBufferSize: 0
});
/**
* Abstract hasher template.
*
* @property {number} blockSize The number of 32-bit words this hasher operates on. Default: 16 (512 bits)
*/
var Hasher = C_lib.Hasher = BufferedBlockAlgorithm.extend({
/**
* Configuration options.
*/
cfg: Base.extend(),
/**
* Initializes a newly created hasher.
*
* @param {Object} cfg (Optional) The configuration options to use for this hash computation.
*
* @example
*
* var hasher = CryptoJS.algo.SHA256.create();
*/
init: function (cfg) {
// Apply config defaults
this.cfg = this.cfg.extend(cfg);
// Set initial values
this.reset();
},
/**
* Resets this hasher to its initial state.
*
* @example
*
* hasher.reset();
*/
reset: function () {
// Reset data buffer
BufferedBlockAlgorithm.reset.call(this);
// Perform concrete-hasher logic
this._doReset();
},
/**
* Updates this hasher with a message.
*
* @param {WordArray|string} messageUpdate The message to append.
*
* @return {Hasher} This hasher.
*
* @example
*
* hasher.update('message');
* hasher.update(wordArray);
*/
update: function (messageUpdate) {
// Append
this._append(messageUpdate);
// Update the hash
this._process();
// Chainable
return this;
},
/**
* Finalizes the hash computation.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} messageUpdate (Optional) A final message update.
*
* @return {WordArray} The hash.
*
* @example
*
* var hash = hasher.finalize();
* var hash = hasher.finalize('message');
* var hash = hasher.finalize(wordArray);
*/
finalize: function (messageUpdate) {
// Final message update
if (messageUpdate) {
this._append(messageUpdate);
}
// Perform concrete-hasher logic
var hash = this._doFinalize();
return hash;
},
blockSize: 512/32,
/**
* Creates a shortcut function to a hasher's object interface.
*
* @param {Hasher} hasher The hasher to create a helper for.
*
* @return {Function} The shortcut function.
*
* @static
*
* @example
*
* var SHA256 = CryptoJS.lib.Hasher._createHelper(CryptoJS.algo.SHA256);
*/
_createHelper: function (hasher) {
return function (message, cfg) {
return new hasher.init(cfg).finalize(message);
};
},
/**
* Creates a shortcut function to the HMAC's object interface.
*
* @param {Hasher} hasher The hasher to use in this HMAC helper.
*
* @return {Function} The shortcut function.
*
* @static
*
* @example
*
* var HmacSHA256 = CryptoJS.lib.Hasher._createHmacHelper(CryptoJS.algo.SHA256);
*/
_createHmacHelper: function (hasher) {
return function (message, key) {
return new C_algo.HMAC.init(hasher, key).finalize(message);
};
}
});
/**
* Algorithm namespace.
*/
var C_algo = C.algo = {};
return C;
}(Math));
return CryptoJS;
}));
},{}],43:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var C_enc = C.enc;
/**
* Base64 encoding strategy.
*/
var Base64 = C_enc.Base64 = {
/**
* Converts a word array to a Base64 string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The Base64 string.
*
* @static
*
* @example
*
* var base64String = CryptoJS.enc.Base64.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
var map = this._map;
// Clamp excess bits
wordArray.clamp();
// Convert
var base64Chars = [];
for (var i = 0; i < sigBytes; i += 3) {
var byte1 = (words[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff;
var byte2 = (words[(i + 1) >>> 2] >>> (24 - ((i + 1) % 4) * 8)) & 0xff;
var byte3 = (words[(i + 2) >>> 2] >>> (24 - ((i + 2) % 4) * 8)) & 0xff;
var triplet = (byte1 << 16) | (byte2 << 8) | byte3;
for (var j = 0; (j < 4) && (i + j * 0.75 < sigBytes); j++) {
base64Chars.push(map.charAt((triplet >>> (6 * (3 - j))) & 0x3f));
}
}
// Add padding
var paddingChar = map.charAt(64);
if (paddingChar) {
while (base64Chars.length % 4) {
base64Chars.push(paddingChar);
}
}
return base64Chars.join('');
},
/**
* Converts a Base64 string to a word array.
*
* @param {string} base64Str The Base64 string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Base64.parse(base64String);
*/
parse: function (base64Str) {
// Shortcuts
var base64StrLength = base64Str.length;
var map = this._map;
// Ignore padding
var paddingChar = map.charAt(64);
if (paddingChar) {
var paddingIndex = base64Str.indexOf(paddingChar);
if (paddingIndex != -1) {
base64StrLength = paddingIndex;
}
}
// Convert
var words = [];
var nBytes = 0;
for (var i = 0; i < base64StrLength; i++) {
if (i % 4) {
var bits1 = map.indexOf(base64Str.charAt(i - 1)) << ((i % 4) * 2);
var bits2 = map.indexOf(base64Str.charAt(i)) >>> (6 - (i % 4) * 2);
words[nBytes >>> 2] |= (bits1 | bits2) << (24 - (nBytes % 4) * 8);
nBytes++;
}
}
return WordArray.create(words, nBytes);
},
_map: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/='
};
}());
return CryptoJS.enc.Base64;
}));
},{"./core":42}],44:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var C_enc = C.enc;
/**
* UTF-16 BE encoding strategy.
*/
var Utf16BE = C_enc.Utf16 = C_enc.Utf16BE = {
/**
* Converts a word array to a UTF-16 BE string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-16 BE string.
*
* @static
*
* @example
*
* var utf16String = CryptoJS.enc.Utf16.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var utf16Chars = [];
for (var i = 0; i < sigBytes; i += 2) {
var codePoint = (words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff;
utf16Chars.push(String.fromCharCode(codePoint));
}
return utf16Chars.join('');
},
/**
* Converts a UTF-16 BE string to a word array.
*
* @param {string} utf16Str The UTF-16 BE string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf16.parse(utf16String);
*/
parse: function (utf16Str) {
// Shortcut
var utf16StrLength = utf16Str.length;
// Convert
var words = [];
for (var i = 0; i < utf16StrLength; i++) {
words[i >>> 1] |= utf16Str.charCodeAt(i) << (16 - (i % 2) * 16);
}
return WordArray.create(words, utf16StrLength * 2);
}
};
/**
* UTF-16 LE encoding strategy.
*/
C_enc.Utf16LE = {
/**
* Converts a word array to a UTF-16 LE string.
*
* @param {WordArray} wordArray The word array.
*
* @return {string} The UTF-16 LE string.
*
* @static
*
* @example
*
* var utf16Str = CryptoJS.enc.Utf16LE.stringify(wordArray);
*/
stringify: function (wordArray) {
// Shortcuts
var words = wordArray.words;
var sigBytes = wordArray.sigBytes;
// Convert
var utf16Chars = [];
for (var i = 0; i < sigBytes; i += 2) {
var codePoint = swapEndian((words[i >>> 2] >>> (16 - (i % 4) * 8)) & 0xffff);
utf16Chars.push(String.fromCharCode(codePoint));
}
return utf16Chars.join('');
},
/**
* Converts a UTF-16 LE string to a word array.
*
* @param {string} utf16Str The UTF-16 LE string.
*
* @return {WordArray} The word array.
*
* @static
*
* @example
*
* var wordArray = CryptoJS.enc.Utf16LE.parse(utf16Str);
*/
parse: function (utf16Str) {
// Shortcut
var utf16StrLength = utf16Str.length;
// Convert
var words = [];
for (var i = 0; i < utf16StrLength; i++) {
words[i >>> 1] |= swapEndian(utf16Str.charCodeAt(i) << (16 - (i % 2) * 16));
}
return WordArray.create(words, utf16StrLength * 2);
}
};
function swapEndian(word) {
return ((word << 8) & 0xff00ff00) | ((word >>> 8) & 0x00ff00ff);
}
}());
return CryptoJS.enc.Utf16;
}));
},{"./core":42}],45:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha1"), _dereq_("./hmac"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./sha1", "./hmac"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var WordArray = C_lib.WordArray;
var C_algo = C.algo;
var MD5 = C_algo.MD5;
/**
* This key derivation function is meant to conform with EVP_BytesToKey.
* www.openssl.org/docs/crypto/EVP_BytesToKey.html
*/
var EvpKDF = C_algo.EvpKDF = Base.extend({
/**
* Configuration options.
*
* @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
* @property {Hasher} hasher The hash algorithm to use. Default: MD5
* @property {number} iterations The number of iterations to perform. Default: 1
*/
cfg: Base.extend({
keySize: 128/32,
hasher: MD5,
iterations: 1
}),
/**
* Initializes a newly created key derivation function.
*
* @param {Object} cfg (Optional) The configuration options to use for the derivation.
*
* @example
*
* var kdf = CryptoJS.algo.EvpKDF.create();
* var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8 });
* var kdf = CryptoJS.algo.EvpKDF.create({ keySize: 8, iterations: 1000 });
*/
init: function (cfg) {
this.cfg = this.cfg.extend(cfg);
},
/**
* Derives a key from a password.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
*
* @return {WordArray} The derived key.
*
* @example
*
* var key = kdf.compute(password, salt);
*/
compute: function (password, salt) {
// Shortcut
var cfg = this.cfg;
// Init hasher
var hasher = cfg.hasher.create();
// Initial values
var derivedKey = WordArray.create();
// Shortcuts
var derivedKeyWords = derivedKey.words;
var keySize = cfg.keySize;
var iterations = cfg.iterations;
// Generate key
while (derivedKeyWords.length < keySize) {
if (block) {
hasher.update(block);
}
var block = hasher.update(password).finalize(salt);
hasher.reset();
// Iterations
for (var i = 1; i < iterations; i++) {
block = hasher.finalize(block);
hasher.reset();
}
derivedKey.concat(block);
}
derivedKey.sigBytes = keySize * 4;
return derivedKey;
}
});
/**
* Derives a key from a password.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
* @param {Object} cfg (Optional) The configuration options to use for this computation.
*
* @return {WordArray} The derived key.
*
* @static
*
* @example
*
* var key = CryptoJS.EvpKDF(password, salt);
* var key = CryptoJS.EvpKDF(password, salt, { keySize: 8 });
* var key = CryptoJS.EvpKDF(password, salt, { keySize: 8, iterations: 1000 });
*/
C.EvpKDF = function (password, salt, cfg) {
return EvpKDF.create(cfg).compute(password, salt);
};
}());
return CryptoJS.EvpKDF;
}));
},{"./core":42,"./hmac":47,"./sha1":66}],46:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (undefined) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var CipherParams = C_lib.CipherParams;
var C_enc = C.enc;
var Hex = C_enc.Hex;
var C_format = C.format;
var HexFormatter = C_format.Hex = {
/**
* Converts the ciphertext of a cipher params object to a hexadecimally encoded string.
*
* @param {CipherParams} cipherParams The cipher params object.
*
* @return {string} The hexadecimally encoded string.
*
* @static
*
* @example
*
* var hexString = CryptoJS.format.Hex.stringify(cipherParams);
*/
stringify: function (cipherParams) {
return cipherParams.ciphertext.toString(Hex);
},
/**
* Converts a hexadecimally encoded ciphertext string to a cipher params object.
*
* @param {string} input The hexadecimally encoded string.
*
* @return {CipherParams} The cipher params object.
*
* @static
*
* @example
*
* var cipherParams = CryptoJS.format.Hex.parse(hexString);
*/
parse: function (input) {
var ciphertext = Hex.parse(input);
return CipherParams.create({ ciphertext: ciphertext });
}
};
}());
return CryptoJS.format.Hex;
}));
},{"./cipher-core":41,"./core":42}],47:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var C_enc = C.enc;
var Utf8 = C_enc.Utf8;
var C_algo = C.algo;
/**
* HMAC algorithm.
*/
var HMAC = C_algo.HMAC = Base.extend({
/**
* Initializes a newly created HMAC.
*
* @param {Hasher} hasher The hash algorithm to use.
* @param {WordArray|string} key The secret key.
*
* @example
*
* var hmacHasher = CryptoJS.algo.HMAC.create(CryptoJS.algo.SHA256, key);
*/
init: function (hasher, key) {
// Init hasher
hasher = this._hasher = new hasher.init();
// Convert string to WordArray, else assume WordArray already
if (typeof key == 'string') {
key = Utf8.parse(key);
}
// Shortcuts
var hasherBlockSize = hasher.blockSize;
var hasherBlockSizeBytes = hasherBlockSize * 4;
// Allow arbitrary length keys
if (key.sigBytes > hasherBlockSizeBytes) {
key = hasher.finalize(key);
}
// Clamp excess bits
key.clamp();
// Clone key for inner and outer pads
var oKey = this._oKey = key.clone();
var iKey = this._iKey = key.clone();
// Shortcuts
var oKeyWords = oKey.words;
var iKeyWords = iKey.words;
// XOR keys with pad constants
for (var i = 0; i < hasherBlockSize; i++) {
oKeyWords[i] ^= 0x5c5c5c5c;
iKeyWords[i] ^= 0x36363636;
}
oKey.sigBytes = iKey.sigBytes = hasherBlockSizeBytes;
// Set initial values
this.reset();
},
/**
* Resets this HMAC to its initial state.
*
* @example
*
* hmacHasher.reset();
*/
reset: function () {
// Shortcut
var hasher = this._hasher;
// Reset
hasher.reset();
hasher.update(this._iKey);
},
/**
* Updates this HMAC with a message.
*
* @param {WordArray|string} messageUpdate The message to append.
*
* @return {HMAC} This HMAC instance.
*
* @example
*
* hmacHasher.update('message');
* hmacHasher.update(wordArray);
*/
update: function (messageUpdate) {
this._hasher.update(messageUpdate);
// Chainable
return this;
},
/**
* Finalizes the HMAC computation.
* Note that the finalize operation is effectively a destructive, read-once operation.
*
* @param {WordArray|string} messageUpdate (Optional) A final message update.
*
* @return {WordArray} The HMAC.
*
* @example
*
* var hmac = hmacHasher.finalize();
* var hmac = hmacHasher.finalize('message');
* var hmac = hmacHasher.finalize(wordArray);
*/
finalize: function (messageUpdate) {
// Shortcut
var hasher = this._hasher;
// Compute HMAC
var innerHash = hasher.finalize(messageUpdate);
hasher.reset();
var hmac = hasher.finalize(this._oKey.clone().concat(innerHash));
return hmac;
}
});
}());
}));
},{"./core":42}],48:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"), _dereq_("./lib-typedarrays"), _dereq_("./enc-utf16"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./sha1"), _dereq_("./sha256"), _dereq_("./sha224"), _dereq_("./sha512"), _dereq_("./sha384"), _dereq_("./sha3"), _dereq_("./ripemd160"), _dereq_("./hmac"), _dereq_("./pbkdf2"), _dereq_("./evpkdf"), _dereq_("./cipher-core"), _dereq_("./mode-cfb"), _dereq_("./mode-ctr"), _dereq_("./mode-ctr-gladman"), _dereq_("./mode-ofb"), _dereq_("./mode-ecb"), _dereq_("./pad-ansix923"), _dereq_("./pad-iso10126"), _dereq_("./pad-iso97971"), _dereq_("./pad-zeropadding"), _dereq_("./pad-nopadding"), _dereq_("./format-hex"), _dereq_("./aes"), _dereq_("./tripledes"), _dereq_("./rc4"), _dereq_("./rabbit"), _dereq_("./rabbit-legacy"));
}
else if (typeof define === "function" && define.amd) {
// 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"], factory);
}
else {
// Global (browser)
root.CryptoJS = factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
return CryptoJS;
}));
},{"./aes":40,"./cipher-core":41,"./core":42,"./enc-base64":43,"./enc-utf16":44,"./evpkdf":45,"./format-hex":46,"./hmac":47,"./lib-typedarrays":49,"./md5":50,"./mode-cfb":51,"./mode-ctr":53,"./mode-ctr-gladman":52,"./mode-ecb":54,"./mode-ofb":55,"./pad-ansix923":56,"./pad-iso10126":57,"./pad-iso97971":58,"./pad-nopadding":59,"./pad-zeropadding":60,"./pbkdf2":61,"./rabbit":63,"./rabbit-legacy":62,"./rc4":64,"./ripemd160":65,"./sha1":66,"./sha224":67,"./sha256":68,"./sha3":69,"./sha384":70,"./sha512":71,"./tripledes":72,"./x64-core":73}],49:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Check if typed arrays are supported
if (typeof ArrayBuffer != 'function') {
return;
}
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
// Reference original init
var superInit = WordArray.init;
// Augment WordArray.init to handle typed arrays
var subInit = WordArray.init = function (typedArray) {
// Convert buffers to uint8
if (typedArray instanceof ArrayBuffer) {
typedArray = new Uint8Array(typedArray);
}
// Convert other array views to uint8
if (
typedArray instanceof Int8Array ||
(typeof Uint8ClampedArray !== "undefined" && typedArray instanceof Uint8ClampedArray) ||
typedArray instanceof Int16Array ||
typedArray instanceof Uint16Array ||
typedArray instanceof Int32Array ||
typedArray instanceof Uint32Array ||
typedArray instanceof Float32Array ||
typedArray instanceof Float64Array
) {
typedArray = new Uint8Array(typedArray.buffer, typedArray.byteOffset, typedArray.byteLength);
}
// Handle Uint8Array
if (typedArray instanceof Uint8Array) {
// Shortcut
var typedArrayByteLength = typedArray.byteLength;
// Extract bytes
var words = [];
for (var i = 0; i < typedArrayByteLength; i++) {
words[i >>> 2] |= typedArray[i] << (24 - (i % 4) * 8);
}
// Initialize this word array
superInit.call(this, words, typedArrayByteLength);
} else {
// Else call normal init
superInit.apply(this, arguments);
}
};
subInit.prototype = WordArray;
}());
return CryptoJS.lib.WordArray;
}));
},{"./core":42}],50:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Constants table
var T = [];
// Compute constants
(function () {
for (var i = 0; i < 64; i++) {
T[i] = (Math.abs(Math.sin(i + 1)) * 0x100000000) | 0;
}
}());
/**
* MD5 hash algorithm.
*/
var MD5 = C_algo.MD5 = Hasher.extend({
_doReset: function () {
this._hash = new WordArray.init([
0x67452301, 0xefcdab89,
0x98badcfe, 0x10325476
]);
},
_doProcessBlock: function (M, offset) {
// Swap endian
for (var i = 0; i < 16; i++) {
// Shortcuts
var offset_i = offset + i;
var M_offset_i = M[offset_i];
M[offset_i] = (
(((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) |
(((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00)
);
}
// Shortcuts
var H = this._hash.words;
var M_offset_0 = M[offset + 0];
var M_offset_1 = M[offset + 1];
var M_offset_2 = M[offset + 2];
var M_offset_3 = M[offset + 3];
var M_offset_4 = M[offset + 4];
var M_offset_5 = M[offset + 5];
var M_offset_6 = M[offset + 6];
var M_offset_7 = M[offset + 7];
var M_offset_8 = M[offset + 8];
var M_offset_9 = M[offset + 9];
var M_offset_10 = M[offset + 10];
var M_offset_11 = M[offset + 11];
var M_offset_12 = M[offset + 12];
var M_offset_13 = M[offset + 13];
var M_offset_14 = M[offset + 14];
var M_offset_15 = M[offset + 15];
// Working varialbes
var a = H[0];
var b = H[1];
var c = H[2];
var d = H[3];
// Computation
a = FF(a, b, c, d, M_offset_0, 7, T[0]);
d = FF(d, a, b, c, M_offset_1, 12, T[1]);
c = FF(c, d, a, b, M_offset_2, 17, T[2]);
b = FF(b, c, d, a, M_offset_3, 22, T[3]);
a = FF(a, b, c, d, M_offset_4, 7, T[4]);
d = FF(d, a, b, c, M_offset_5, 12, T[5]);
c = FF(c, d, a, b, M_offset_6, 17, T[6]);
b = FF(b, c, d, a, M_offset_7, 22, T[7]);
a = FF(a, b, c, d, M_offset_8, 7, T[8]);
d = FF(d, a, b, c, M_offset_9, 12, T[9]);
c = FF(c, d, a, b, M_offset_10, 17, T[10]);
b = FF(b, c, d, a, M_offset_11, 22, T[11]);
a = FF(a, b, c, d, M_offset_12, 7, T[12]);
d = FF(d, a, b, c, M_offset_13, 12, T[13]);
c = FF(c, d, a, b, M_offset_14, 17, T[14]);
b = FF(b, c, d, a, M_offset_15, 22, T[15]);
a = GG(a, b, c, d, M_offset_1, 5, T[16]);
d = GG(d, a, b, c, M_offset_6, 9, T[17]);
c = GG(c, d, a, b, M_offset_11, 14, T[18]);
b = GG(b, c, d, a, M_offset_0, 20, T[19]);
a = GG(a, b, c, d, M_offset_5, 5, T[20]);
d = GG(d, a, b, c, M_offset_10, 9, T[21]);
c = GG(c, d, a, b, M_offset_15, 14, T[22]);
b = GG(b, c, d, a, M_offset_4, 20, T[23]);
a = GG(a, b, c, d, M_offset_9, 5, T[24]);
d = GG(d, a, b, c, M_offset_14, 9, T[25]);
c = GG(c, d, a, b, M_offset_3, 14, T[26]);
b = GG(b, c, d, a, M_offset_8, 20, T[27]);
a = GG(a, b, c, d, M_offset_13, 5, T[28]);
d = GG(d, a, b, c, M_offset_2, 9, T[29]);
c = GG(c, d, a, b, M_offset_7, 14, T[30]);
b = GG(b, c, d, a, M_offset_12, 20, T[31]);
a = HH(a, b, c, d, M_offset_5, 4, T[32]);
d = HH(d, a, b, c, M_offset_8, 11, T[33]);
c = HH(c, d, a, b, M_offset_11, 16, T[34]);
b = HH(b, c, d, a, M_offset_14, 23, T[35]);
a = HH(a, b, c, d, M_offset_1, 4, T[36]);
d = HH(d, a, b, c, M_offset_4, 11, T[37]);
c = HH(c, d, a, b, M_offset_7, 16, T[38]);
b = HH(b, c, d, a, M_offset_10, 23, T[39]);
a = HH(a, b, c, d, M_offset_13, 4, T[40]);
d = HH(d, a, b, c, M_offset_0, 11, T[41]);
c = HH(c, d, a, b, M_offset_3, 16, T[42]);
b = HH(b, c, d, a, M_offset_6, 23, T[43]);
a = HH(a, b, c, d, M_offset_9, 4, T[44]);
d = HH(d, a, b, c, M_offset_12, 11, T[45]);
c = HH(c, d, a, b, M_offset_15, 16, T[46]);
b = HH(b, c, d, a, M_offset_2, 23, T[47]);
a = II(a, b, c, d, M_offset_0, 6, T[48]);
d = II(d, a, b, c, M_offset_7, 10, T[49]);
c = II(c, d, a, b, M_offset_14, 15, T[50]);
b = II(b, c, d, a, M_offset_5, 21, T[51]);
a = II(a, b, c, d, M_offset_12, 6, T[52]);
d = II(d, a, b, c, M_offset_3, 10, T[53]);
c = II(c, d, a, b, M_offset_10, 15, T[54]);
b = II(b, c, d, a, M_offset_1, 21, T[55]);
a = II(a, b, c, d, M_offset_8, 6, T[56]);
d = II(d, a, b, c, M_offset_15, 10, T[57]);
c = II(c, d, a, b, M_offset_6, 15, T[58]);
b = II(b, c, d, a, M_offset_13, 21, T[59]);
a = II(a, b, c, d, M_offset_4, 6, T[60]);
d = II(d, a, b, c, M_offset_11, 10, T[61]);
c = II(c, d, a, b, M_offset_2, 15, T[62]);
b = II(b, c, d, a, M_offset_9, 21, T[63]);
// Intermediate hash value
H[0] = (H[0] + a) | 0;
H[1] = (H[1] + b) | 0;
H[2] = (H[2] + c) | 0;
H[3] = (H[3] + d) | 0;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
var nBitsTotalH = Math.floor(nBitsTotal / 0x100000000);
var nBitsTotalL = nBitsTotal;
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = (
(((nBitsTotalH << 8) | (nBitsTotalH >>> 24)) & 0x00ff00ff) |
(((nBitsTotalH << 24) | (nBitsTotalH >>> 8)) & 0xff00ff00)
);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = (
(((nBitsTotalL << 8) | (nBitsTotalL >>> 24)) & 0x00ff00ff) |
(((nBitsTotalL << 24) | (nBitsTotalL >>> 8)) & 0xff00ff00)
);
data.sigBytes = (dataWords.length + 1) * 4;
// Hash final blocks
this._process();
// Shortcuts
var hash = this._hash;
var H = hash.words;
// Swap endian
for (var i = 0; i < 4; i++) {
// Shortcut
var H_i = H[i];
H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) |
(((H_i << 24) | (H_i >>> 8)) & 0xff00ff00);
}
// Return final computed hash
return hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
function FF(a, b, c, d, x, s, t) {
var n = a + ((b & c) | (~b & d)) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
function GG(a, b, c, d, x, s, t) {
var n = a + ((b & d) | (c & ~d)) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
function HH(a, b, c, d, x, s, t) {
var n = a + (b ^ c ^ d) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
function II(a, b, c, d, x, s, t) {
var n = a + (c ^ (b | ~d)) + x + t;
return ((n << s) | (n >>> (32 - s))) + b;
}
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.MD5('message');
* var hash = CryptoJS.MD5(wordArray);
*/
C.MD5 = Hasher._createHelper(MD5);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacMD5(message, key);
*/
C.HmacMD5 = Hasher._createHmacHelper(MD5);
}(Math));
return CryptoJS.MD5;
}));
},{"./core":42}],51:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Cipher Feedback block mode.
*/
CryptoJS.mode.CFB = (function () {
var CFB = CryptoJS.lib.BlockCipherMode.extend();
CFB.Encryptor = CFB.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher);
// Remember this block to use with next block
this._prevBlock = words.slice(offset, offset + blockSize);
}
});
CFB.Decryptor = CFB.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher;
var blockSize = cipher.blockSize;
// Remember this block to use with next block
var thisBlock = words.slice(offset, offset + blockSize);
generateKeystreamAndEncrypt.call(this, words, offset, blockSize, cipher);
// This block becomes the previous block
this._prevBlock = thisBlock;
}
});
function generateKeystreamAndEncrypt(words, offset, blockSize, cipher) {
// Shortcut
var iv = this._iv;
// Generate keystream
if (iv) {
var keystream = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
} else {
var keystream = this._prevBlock;
}
cipher.encryptBlock(keystream, 0);
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
return CFB;
}());
return CryptoJS.mode.CFB;
}));
},{"./cipher-core":41,"./core":42}],52:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/** @preserve
* Counter block mode compatible with Dr Brian Gladman fileenc.c
* derived from CryptoJS.mode.CTR
* Jan Hruby [email protected]
*/
CryptoJS.mode.CTRGladman = (function () {
var CTRGladman = CryptoJS.lib.BlockCipherMode.extend();
function incWord(word)
{
if (((word >> 24) & 0xff) === 0xff) { //overflow
var b1 = (word >> 16)&0xff;
var b2 = (word >> 8)&0xff;
var b3 = word & 0xff;
if (b1 === 0xff) // overflow b1
{
b1 = 0;
if (b2 === 0xff)
{
b2 = 0;
if (b3 === 0xff)
{
b3 = 0;
}
else
{
++b3;
}
}
else
{
++b2;
}
}
else
{
++b1;
}
word = 0;
word += (b1 << 16);
word += (b2 << 8);
word += b3;
}
else
{
word += (0x01 << 24);
}
return word;
}
function incCounter(counter)
{
if ((counter[0] = incWord(counter[0])) === 0)
{
// encr_data in fileenc.c from Dr Brian Gladman's counts only with DWORD j < 8
counter[1] = incWord(counter[1]);
}
return counter;
}
var Encryptor = CTRGladman.Encryptor = CTRGladman.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher
var blockSize = cipher.blockSize;
var iv = this._iv;
var counter = this._counter;
// Generate keystream
if (iv) {
counter = this._counter = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
}
incCounter(counter);
var keystream = counter.slice(0);
cipher.encryptBlock(keystream, 0);
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
});
CTRGladman.Decryptor = Encryptor;
return CTRGladman;
}());
return CryptoJS.mode.CTRGladman;
}));
},{"./cipher-core":41,"./core":42}],53:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Counter block mode.
*/
CryptoJS.mode.CTR = (function () {
var CTR = CryptoJS.lib.BlockCipherMode.extend();
var Encryptor = CTR.Encryptor = CTR.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher
var blockSize = cipher.blockSize;
var iv = this._iv;
var counter = this._counter;
// Generate keystream
if (iv) {
counter = this._counter = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
}
var keystream = counter.slice(0);
cipher.encryptBlock(keystream, 0);
// Increment counter
counter[blockSize - 1] = (counter[blockSize - 1] + 1) | 0
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
});
CTR.Decryptor = Encryptor;
return CTR;
}());
return CryptoJS.mode.CTR;
}));
},{"./cipher-core":41,"./core":42}],54:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Electronic Codebook block mode.
*/
CryptoJS.mode.ECB = (function () {
var ECB = CryptoJS.lib.BlockCipherMode.extend();
ECB.Encryptor = ECB.extend({
processBlock: function (words, offset) {
this._cipher.encryptBlock(words, offset);
}
});
ECB.Decryptor = ECB.extend({
processBlock: function (words, offset) {
this._cipher.decryptBlock(words, offset);
}
});
return ECB;
}());
return CryptoJS.mode.ECB;
}));
},{"./cipher-core":41,"./core":42}],55:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Output Feedback block mode.
*/
CryptoJS.mode.OFB = (function () {
var OFB = CryptoJS.lib.BlockCipherMode.extend();
var Encryptor = OFB.Encryptor = OFB.extend({
processBlock: function (words, offset) {
// Shortcuts
var cipher = this._cipher
var blockSize = cipher.blockSize;
var iv = this._iv;
var keystream = this._keystream;
// Generate keystream
if (iv) {
keystream = this._keystream = iv.slice(0);
// Remove IV for subsequent blocks
this._iv = undefined;
}
cipher.encryptBlock(keystream, 0);
// Encrypt
for (var i = 0; i < blockSize; i++) {
words[offset + i] ^= keystream[i];
}
}
});
OFB.Decryptor = Encryptor;
return OFB;
}());
return CryptoJS.mode.OFB;
}));
},{"./cipher-core":41,"./core":42}],56:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* ANSI X.923 padding strategy.
*/
CryptoJS.pad.AnsiX923 = {
pad: function (data, blockSize) {
// Shortcuts
var dataSigBytes = data.sigBytes;
var blockSizeBytes = blockSize * 4;
// Count padding bytes
var nPaddingBytes = blockSizeBytes - dataSigBytes % blockSizeBytes;
// Compute last byte position
var lastBytePos = dataSigBytes + nPaddingBytes - 1;
// Pad
data.clamp();
data.words[lastBytePos >>> 2] |= nPaddingBytes << (24 - (lastBytePos % 4) * 8);
data.sigBytes += nPaddingBytes;
},
unpad: function (data) {
// Get number of padding bytes from last byte
var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff;
// Remove padding
data.sigBytes -= nPaddingBytes;
}
};
return CryptoJS.pad.Ansix923;
}));
},{"./cipher-core":41,"./core":42}],57:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* ISO 10126 padding strategy.
*/
CryptoJS.pad.Iso10126 = {
pad: function (data, blockSize) {
// Shortcut
var blockSizeBytes = blockSize * 4;
// Count padding bytes
var nPaddingBytes = blockSizeBytes - data.sigBytes % blockSizeBytes;
// Pad
data.concat(CryptoJS.lib.WordArray.random(nPaddingBytes - 1)).
concat(CryptoJS.lib.WordArray.create([nPaddingBytes << 24], 1));
},
unpad: function (data) {
// Get number of padding bytes from last byte
var nPaddingBytes = data.words[(data.sigBytes - 1) >>> 2] & 0xff;
// Remove padding
data.sigBytes -= nPaddingBytes;
}
};
return CryptoJS.pad.Iso10126;
}));
},{"./cipher-core":41,"./core":42}],58:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* ISO/IEC 9797-1 Padding Method 2.
*/
CryptoJS.pad.Iso97971 = {
pad: function (data, blockSize) {
// Add 0x80 byte
data.concat(CryptoJS.lib.WordArray.create([0x80000000], 1));
// Zero pad the rest
CryptoJS.pad.ZeroPadding.pad(data, blockSize);
},
unpad: function (data) {
// Remove zero padding
CryptoJS.pad.ZeroPadding.unpad(data);
// Remove one more byte -- the 0x80 byte
data.sigBytes--;
}
};
return CryptoJS.pad.Iso97971;
}));
},{"./cipher-core":41,"./core":42}],59:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* A noop padding strategy.
*/
CryptoJS.pad.NoPadding = {
pad: function () {
},
unpad: function () {
}
};
return CryptoJS.pad.NoPadding;
}));
},{"./cipher-core":41,"./core":42}],60:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/**
* Zero padding strategy.
*/
CryptoJS.pad.ZeroPadding = {
pad: function (data, blockSize) {
// Shortcut
var blockSizeBytes = blockSize * 4;
// Pad
data.clamp();
data.sigBytes += blockSizeBytes - ((data.sigBytes % blockSizeBytes) || blockSizeBytes);
},
unpad: function (data) {
// Shortcut
var dataWords = data.words;
// Unpad
var i = data.sigBytes - 1;
while (!((dataWords[i >>> 2] >>> (24 - (i % 4) * 8)) & 0xff)) {
i--;
}
data.sigBytes = i + 1;
}
};
return CryptoJS.pad.ZeroPadding;
}));
},{"./cipher-core":41,"./core":42}],61:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha1"), _dereq_("./hmac"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./sha1", "./hmac"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var WordArray = C_lib.WordArray;
var C_algo = C.algo;
var SHA1 = C_algo.SHA1;
var HMAC = C_algo.HMAC;
/**
* Password-Based Key Derivation Function 2 algorithm.
*/
var PBKDF2 = C_algo.PBKDF2 = Base.extend({
/**
* Configuration options.
*
* @property {number} keySize The key size in words to generate. Default: 4 (128 bits)
* @property {Hasher} hasher The hasher to use. Default: SHA1
* @property {number} iterations The number of iterations to perform. Default: 1
*/
cfg: Base.extend({
keySize: 128/32,
hasher: SHA1,
iterations: 1
}),
/**
* Initializes a newly created key derivation function.
*
* @param {Object} cfg (Optional) The configuration options to use for the derivation.
*
* @example
*
* var kdf = CryptoJS.algo.PBKDF2.create();
* var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8 });
* var kdf = CryptoJS.algo.PBKDF2.create({ keySize: 8, iterations: 1000 });
*/
init: function (cfg) {
this.cfg = this.cfg.extend(cfg);
},
/**
* Computes the Password-Based Key Derivation Function 2.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
*
* @return {WordArray} The derived key.
*
* @example
*
* var key = kdf.compute(password, salt);
*/
compute: function (password, salt) {
// Shortcut
var cfg = this.cfg;
// Init HMAC
var hmac = HMAC.create(cfg.hasher, password);
// Initial values
var derivedKey = WordArray.create();
var blockIndex = WordArray.create([0x00000001]);
// Shortcuts
var derivedKeyWords = derivedKey.words;
var blockIndexWords = blockIndex.words;
var keySize = cfg.keySize;
var iterations = cfg.iterations;
// Generate key
while (derivedKeyWords.length < keySize) {
var block = hmac.update(salt).finalize(blockIndex);
hmac.reset();
// Shortcuts
var blockWords = block.words;
var blockWordsLength = blockWords.length;
// Iterations
var intermediate = block;
for (var i = 1; i < iterations; i++) {
intermediate = hmac.finalize(intermediate);
hmac.reset();
// Shortcut
var intermediateWords = intermediate.words;
// XOR intermediate with block
for (var j = 0; j < blockWordsLength; j++) {
blockWords[j] ^= intermediateWords[j];
}
}
derivedKey.concat(block);
blockIndexWords[0]++;
}
derivedKey.sigBytes = keySize * 4;
return derivedKey;
}
});
/**
* Computes the Password-Based Key Derivation Function 2.
*
* @param {WordArray|string} password The password.
* @param {WordArray|string} salt A salt.
* @param {Object} cfg (Optional) The configuration options to use for this computation.
*
* @return {WordArray} The derived key.
*
* @static
*
* @example
*
* var key = CryptoJS.PBKDF2(password, salt);
* var key = CryptoJS.PBKDF2(password, salt, { keySize: 8 });
* var key = CryptoJS.PBKDF2(password, salt, { keySize: 8, iterations: 1000 });
*/
C.PBKDF2 = function (password, salt, cfg) {
return PBKDF2.create(cfg).compute(password, salt);
};
}());
return CryptoJS.PBKDF2;
}));
},{"./core":42,"./hmac":47,"./sha1":66}],62:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var StreamCipher = C_lib.StreamCipher;
var C_algo = C.algo;
// Reusable objects
var S = [];
var C_ = [];
var G = [];
/**
* Rabbit stream cipher algorithm.
*
* This is a legacy version that neglected to convert the key to little-endian.
* This error doesn't affect the cipher's security,
* but it does affect its compatibility with other implementations.
*/
var RabbitLegacy = C_algo.RabbitLegacy = StreamCipher.extend({
_doReset: function () {
// Shortcuts
var K = this._key.words;
var iv = this.cfg.iv;
// Generate initial state values
var X = this._X = [
K[0], (K[3] << 16) | (K[2] >>> 16),
K[1], (K[0] << 16) | (K[3] >>> 16),
K[2], (K[1] << 16) | (K[0] >>> 16),
K[3], (K[2] << 16) | (K[1] >>> 16)
];
// Generate initial counter values
var C = this._C = [
(K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff),
(K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff),
(K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff),
(K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff)
];
// Carry bit
this._b = 0;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
// Modify the counters
for (var i = 0; i < 8; i++) {
C[i] ^= X[(i + 4) & 7];
}
// IV setup
if (iv) {
// Shortcuts
var IV = iv.words;
var IV_0 = IV[0];
var IV_1 = IV[1];
// Generate four subvectors
var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00);
var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00);
var i1 = (i0 >>> 16) | (i2 & 0xffff0000);
var i3 = (i2 << 16) | (i0 & 0x0000ffff);
// Modify counter values
C[0] ^= i0;
C[1] ^= i1;
C[2] ^= i2;
C[3] ^= i3;
C[4] ^= i0;
C[5] ^= i1;
C[6] ^= i2;
C[7] ^= i3;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
}
},
_doProcessBlock: function (M, offset) {
// Shortcut
var X = this._X;
// Iterate the system
nextState.call(this);
// Generate four keystream words
S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16);
S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16);
S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16);
S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16);
for (var i = 0; i < 4; i++) {
// Swap endian
S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) |
(((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00);
// Encrypt
M[offset + i] ^= S[i];
}
},
blockSize: 128/32,
ivSize: 64/32
});
function nextState() {
// Shortcuts
var X = this._X;
var C = this._C;
// Save old counter values
for (var i = 0; i < 8; i++) {
C_[i] = C[i];
}
// Calculate new counter values
C[0] = (C[0] + 0x4d34d34d + this._b) | 0;
C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0;
C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0;
C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0;
C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0;
C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0;
C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0;
C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0;
this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0;
// Calculate the g-values
for (var i = 0; i < 8; i++) {
var gx = X[i] + C[i];
// Construct high and low argument for squaring
var ga = gx & 0xffff;
var gb = gx >>> 16;
// Calculate high and low result of squaring
var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb;
var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0);
// High XOR low
G[i] = gh ^ gl;
}
// Calculate new state values
X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0;
X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0;
X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0;
X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0;
X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0;
X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0;
X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0;
X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.RabbitLegacy.encrypt(message, key, cfg);
* var plaintext = CryptoJS.RabbitLegacy.decrypt(ciphertext, key, cfg);
*/
C.RabbitLegacy = StreamCipher._createHelper(RabbitLegacy);
}());
return CryptoJS.RabbitLegacy;
}));
},{"./cipher-core":41,"./core":42,"./enc-base64":43,"./evpkdf":45,"./md5":50}],63:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var StreamCipher = C_lib.StreamCipher;
var C_algo = C.algo;
// Reusable objects
var S = [];
var C_ = [];
var G = [];
/**
* Rabbit stream cipher algorithm
*/
var Rabbit = C_algo.Rabbit = StreamCipher.extend({
_doReset: function () {
// Shortcuts
var K = this._key.words;
var iv = this.cfg.iv;
// Swap endian
for (var i = 0; i < 4; i++) {
K[i] = (((K[i] << 8) | (K[i] >>> 24)) & 0x00ff00ff) |
(((K[i] << 24) | (K[i] >>> 8)) & 0xff00ff00);
}
// Generate initial state values
var X = this._X = [
K[0], (K[3] << 16) | (K[2] >>> 16),
K[1], (K[0] << 16) | (K[3] >>> 16),
K[2], (K[1] << 16) | (K[0] >>> 16),
K[3], (K[2] << 16) | (K[1] >>> 16)
];
// Generate initial counter values
var C = this._C = [
(K[2] << 16) | (K[2] >>> 16), (K[0] & 0xffff0000) | (K[1] & 0x0000ffff),
(K[3] << 16) | (K[3] >>> 16), (K[1] & 0xffff0000) | (K[2] & 0x0000ffff),
(K[0] << 16) | (K[0] >>> 16), (K[2] & 0xffff0000) | (K[3] & 0x0000ffff),
(K[1] << 16) | (K[1] >>> 16), (K[3] & 0xffff0000) | (K[0] & 0x0000ffff)
];
// Carry bit
this._b = 0;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
// Modify the counters
for (var i = 0; i < 8; i++) {
C[i] ^= X[(i + 4) & 7];
}
// IV setup
if (iv) {
// Shortcuts
var IV = iv.words;
var IV_0 = IV[0];
var IV_1 = IV[1];
// Generate four subvectors
var i0 = (((IV_0 << 8) | (IV_0 >>> 24)) & 0x00ff00ff) | (((IV_0 << 24) | (IV_0 >>> 8)) & 0xff00ff00);
var i2 = (((IV_1 << 8) | (IV_1 >>> 24)) & 0x00ff00ff) | (((IV_1 << 24) | (IV_1 >>> 8)) & 0xff00ff00);
var i1 = (i0 >>> 16) | (i2 & 0xffff0000);
var i3 = (i2 << 16) | (i0 & 0x0000ffff);
// Modify counter values
C[0] ^= i0;
C[1] ^= i1;
C[2] ^= i2;
C[3] ^= i3;
C[4] ^= i0;
C[5] ^= i1;
C[6] ^= i2;
C[7] ^= i3;
// Iterate the system four times
for (var i = 0; i < 4; i++) {
nextState.call(this);
}
}
},
_doProcessBlock: function (M, offset) {
// Shortcut
var X = this._X;
// Iterate the system
nextState.call(this);
// Generate four keystream words
S[0] = X[0] ^ (X[5] >>> 16) ^ (X[3] << 16);
S[1] = X[2] ^ (X[7] >>> 16) ^ (X[5] << 16);
S[2] = X[4] ^ (X[1] >>> 16) ^ (X[7] << 16);
S[3] = X[6] ^ (X[3] >>> 16) ^ (X[1] << 16);
for (var i = 0; i < 4; i++) {
// Swap endian
S[i] = (((S[i] << 8) | (S[i] >>> 24)) & 0x00ff00ff) |
(((S[i] << 24) | (S[i] >>> 8)) & 0xff00ff00);
// Encrypt
M[offset + i] ^= S[i];
}
},
blockSize: 128/32,
ivSize: 64/32
});
function nextState() {
// Shortcuts
var X = this._X;
var C = this._C;
// Save old counter values
for (var i = 0; i < 8; i++) {
C_[i] = C[i];
}
// Calculate new counter values
C[0] = (C[0] + 0x4d34d34d + this._b) | 0;
C[1] = (C[1] + 0xd34d34d3 + ((C[0] >>> 0) < (C_[0] >>> 0) ? 1 : 0)) | 0;
C[2] = (C[2] + 0x34d34d34 + ((C[1] >>> 0) < (C_[1] >>> 0) ? 1 : 0)) | 0;
C[3] = (C[3] + 0x4d34d34d + ((C[2] >>> 0) < (C_[2] >>> 0) ? 1 : 0)) | 0;
C[4] = (C[4] + 0xd34d34d3 + ((C[3] >>> 0) < (C_[3] >>> 0) ? 1 : 0)) | 0;
C[5] = (C[5] + 0x34d34d34 + ((C[4] >>> 0) < (C_[4] >>> 0) ? 1 : 0)) | 0;
C[6] = (C[6] + 0x4d34d34d + ((C[5] >>> 0) < (C_[5] >>> 0) ? 1 : 0)) | 0;
C[7] = (C[7] + 0xd34d34d3 + ((C[6] >>> 0) < (C_[6] >>> 0) ? 1 : 0)) | 0;
this._b = (C[7] >>> 0) < (C_[7] >>> 0) ? 1 : 0;
// Calculate the g-values
for (var i = 0; i < 8; i++) {
var gx = X[i] + C[i];
// Construct high and low argument for squaring
var ga = gx & 0xffff;
var gb = gx >>> 16;
// Calculate high and low result of squaring
var gh = ((((ga * ga) >>> 17) + ga * gb) >>> 15) + gb * gb;
var gl = (((gx & 0xffff0000) * gx) | 0) + (((gx & 0x0000ffff) * gx) | 0);
// High XOR low
G[i] = gh ^ gl;
}
// Calculate new state values
X[0] = (G[0] + ((G[7] << 16) | (G[7] >>> 16)) + ((G[6] << 16) | (G[6] >>> 16))) | 0;
X[1] = (G[1] + ((G[0] << 8) | (G[0] >>> 24)) + G[7]) | 0;
X[2] = (G[2] + ((G[1] << 16) | (G[1] >>> 16)) + ((G[0] << 16) | (G[0] >>> 16))) | 0;
X[3] = (G[3] + ((G[2] << 8) | (G[2] >>> 24)) + G[1]) | 0;
X[4] = (G[4] + ((G[3] << 16) | (G[3] >>> 16)) + ((G[2] << 16) | (G[2] >>> 16))) | 0;
X[5] = (G[5] + ((G[4] << 8) | (G[4] >>> 24)) + G[3]) | 0;
X[6] = (G[6] + ((G[5] << 16) | (G[5] >>> 16)) + ((G[4] << 16) | (G[4] >>> 16))) | 0;
X[7] = (G[7] + ((G[6] << 8) | (G[6] >>> 24)) + G[5]) | 0;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.Rabbit.encrypt(message, key, cfg);
* var plaintext = CryptoJS.Rabbit.decrypt(ciphertext, key, cfg);
*/
C.Rabbit = StreamCipher._createHelper(Rabbit);
}());
return CryptoJS.Rabbit;
}));
},{"./cipher-core":41,"./core":42,"./enc-base64":43,"./evpkdf":45,"./md5":50}],64:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var StreamCipher = C_lib.StreamCipher;
var C_algo = C.algo;
/**
* RC4 stream cipher algorithm.
*/
var RC4 = C_algo.RC4 = StreamCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
var keySigBytes = key.sigBytes;
// Init sbox
var S = this._S = [];
for (var i = 0; i < 256; i++) {
S[i] = i;
}
// Key setup
for (var i = 0, j = 0; i < 256; i++) {
var keyByteIndex = i % keySigBytes;
var keyByte = (keyWords[keyByteIndex >>> 2] >>> (24 - (keyByteIndex % 4) * 8)) & 0xff;
j = (j + S[i] + keyByte) % 256;
// Swap
var t = S[i];
S[i] = S[j];
S[j] = t;
}
// Counters
this._i = this._j = 0;
},
_doProcessBlock: function (M, offset) {
M[offset] ^= generateKeystreamWord.call(this);
},
keySize: 256/32,
ivSize: 0
});
function generateKeystreamWord() {
// Shortcuts
var S = this._S;
var i = this._i;
var j = this._j;
// Generate keystream word
var keystreamWord = 0;
for (var n = 0; n < 4; n++) {
i = (i + 1) % 256;
j = (j + S[i]) % 256;
// Swap
var t = S[i];
S[i] = S[j];
S[j] = t;
keystreamWord |= S[(S[i] + S[j]) % 256] << (24 - n * 8);
}
// Update counters
this._i = i;
this._j = j;
return keystreamWord;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.RC4.encrypt(message, key, cfg);
* var plaintext = CryptoJS.RC4.decrypt(ciphertext, key, cfg);
*/
C.RC4 = StreamCipher._createHelper(RC4);
/**
* Modified RC4 stream cipher algorithm.
*/
var RC4Drop = C_algo.RC4Drop = RC4.extend({
/**
* Configuration options.
*
* @property {number} drop The number of keystream words to drop. Default 192
*/
cfg: RC4.cfg.extend({
drop: 192
}),
_doReset: function () {
RC4._doReset.call(this);
// Drop
for (var i = this.cfg.drop; i > 0; i--) {
generateKeystreamWord.call(this);
}
}
});
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.RC4Drop.encrypt(message, key, cfg);
* var plaintext = CryptoJS.RC4Drop.decrypt(ciphertext, key, cfg);
*/
C.RC4Drop = StreamCipher._createHelper(RC4Drop);
}());
return CryptoJS.RC4;
}));
},{"./cipher-core":41,"./core":42,"./enc-base64":43,"./evpkdf":45,"./md5":50}],65:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
/** @preserve
(c) 2012 by Cédric Mesnil. All rights reserved.
Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met:
- Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer.
- Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Constants table
var _zl = WordArray.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]);
var _zr = WordArray.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]);
var _sl = WordArray.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 ]);
var _sr = WordArray.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 ]);
var _hl = WordArray.create([ 0x00000000, 0x5A827999, 0x6ED9EBA1, 0x8F1BBCDC, 0xA953FD4E]);
var _hr = WordArray.create([ 0x50A28BE6, 0x5C4DD124, 0x6D703EF3, 0x7A6D76E9, 0x00000000]);
/**
* RIPEMD160 hash algorithm.
*/
var RIPEMD160 = C_algo.RIPEMD160 = Hasher.extend({
_doReset: function () {
this._hash = WordArray.create([0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0]);
},
_doProcessBlock: function (M, offset) {
// Swap endian
for (var i = 0; i < 16; i++) {
// Shortcuts
var offset_i = offset + i;
var M_offset_i = M[offset_i];
// Swap
M[offset_i] = (
(((M_offset_i << 8) | (M_offset_i >>> 24)) & 0x00ff00ff) |
(((M_offset_i << 24) | (M_offset_i >>> 8)) & 0xff00ff00)
);
}
// Shortcut
var H = this._hash.words;
var hl = _hl.words;
var hr = _hr.words;
var zl = _zl.words;
var zr = _zr.words;
var sl = _sl.words;
var sr = _sr.words;
// Working variables
var al, bl, cl, dl, el;
var ar, br, cr, dr, er;
ar = al = H[0];
br = bl = H[1];
cr = cl = H[2];
dr = dl = H[3];
er = el = H[4];
// Computation
var t;
for (var i = 0; i < 80; i += 1) {
t = (al + M[offset+zl[i]])|0;
if (i<16){
t += f1(bl,cl,dl) + hl[0];
} else if (i<32) {
t += f2(bl,cl,dl) + hl[1];
} else if (i<48) {
t += f3(bl,cl,dl) + hl[2];
} else if (i<64) {
t += f4(bl,cl,dl) + hl[3];
} else {// if (i<80) {
t += f5(bl,cl,dl) + hl[4];
}
t = t|0;
t = rotl(t,sl[i]);
t = (t+el)|0;
al = el;
el = dl;
dl = rotl(cl, 10);
cl = bl;
bl = t;
t = (ar + M[offset+zr[i]])|0;
if (i<16){
t += f5(br,cr,dr) + hr[0];
} else if (i<32) {
t += f4(br,cr,dr) + hr[1];
} else if (i<48) {
t += f3(br,cr,dr) + hr[2];
} else if (i<64) {
t += f2(br,cr,dr) + hr[3];
} else {// if (i<80) {
t += f1(br,cr,dr) + hr[4];
}
t = t|0;
t = rotl(t,sr[i]) ;
t = (t+er)|0;
ar = er;
er = dr;
dr = rotl(cr, 10);
cr = br;
br = t;
}
// Intermediate hash value
t = (H[1] + cl + dr)|0;
H[1] = (H[2] + dl + er)|0;
H[2] = (H[3] + el + ar)|0;
H[3] = (H[4] + al + br)|0;
H[4] = (H[0] + bl + cr)|0;
H[0] = t;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = (
(((nBitsTotal << 8) | (nBitsTotal >>> 24)) & 0x00ff00ff) |
(((nBitsTotal << 24) | (nBitsTotal >>> 8)) & 0xff00ff00)
);
data.sigBytes = (dataWords.length + 1) * 4;
// Hash final blocks
this._process();
// Shortcuts
var hash = this._hash;
var H = hash.words;
// Swap endian
for (var i = 0; i < 5; i++) {
// Shortcut
var H_i = H[i];
// Swap
H[i] = (((H_i << 8) | (H_i >>> 24)) & 0x00ff00ff) |
(((H_i << 24) | (H_i >>> 8)) & 0xff00ff00);
}
// Return final computed hash
return hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
function f1(x, y, z) {
return ((x) ^ (y) ^ (z));
}
function f2(x, y, z) {
return (((x)&(y)) | ((~x)&(z)));
}
function f3(x, y, z) {
return (((x) | (~(y))) ^ (z));
}
function f4(x, y, z) {
return (((x) & (z)) | ((y)&(~(z))));
}
function f5(x, y, z) {
return ((x) ^ ((y) |(~(z))));
}
function rotl(x,n) {
return (x<<n) | (x>>>(32-n));
}
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.RIPEMD160('message');
* var hash = CryptoJS.RIPEMD160(wordArray);
*/
C.RIPEMD160 = Hasher._createHelper(RIPEMD160);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacRIPEMD160(message, key);
*/
C.HmacRIPEMD160 = Hasher._createHmacHelper(RIPEMD160);
}(Math));
return CryptoJS.RIPEMD160;
}));
},{"./core":42}],66:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Reusable object
var W = [];
/**
* SHA-1 hash algorithm.
*/
var SHA1 = C_algo.SHA1 = Hasher.extend({
_doReset: function () {
this._hash = new WordArray.init([
0x67452301, 0xefcdab89,
0x98badcfe, 0x10325476,
0xc3d2e1f0
]);
},
_doProcessBlock: function (M, offset) {
// Shortcut
var H = this._hash.words;
// Working variables
var a = H[0];
var b = H[1];
var c = H[2];
var d = H[3];
var e = H[4];
// Computation
for (var i = 0; i < 80; i++) {
if (i < 16) {
W[i] = M[offset + i] | 0;
} else {
var n = W[i - 3] ^ W[i - 8] ^ W[i - 14] ^ W[i - 16];
W[i] = (n << 1) | (n >>> 31);
}
var t = ((a << 5) | (a >>> 27)) + e + W[i];
if (i < 20) {
t += ((b & c) | (~b & d)) + 0x5a827999;
} else if (i < 40) {
t += (b ^ c ^ d) + 0x6ed9eba1;
} else if (i < 60) {
t += ((b & c) | (b & d) | (c & d)) - 0x70e44324;
} else /* if (i < 80) */ {
t += (b ^ c ^ d) - 0x359d3e2a;
}
e = d;
d = c;
c = (b << 30) | (b >>> 2);
b = a;
a = t;
}
// Intermediate hash value
H[0] = (H[0] + a) | 0;
H[1] = (H[1] + b) | 0;
H[2] = (H[2] + c) | 0;
H[3] = (H[3] + d) | 0;
H[4] = (H[4] + e) | 0;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Return final computed hash
return this._hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA1('message');
* var hash = CryptoJS.SHA1(wordArray);
*/
C.SHA1 = Hasher._createHelper(SHA1);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA1(message, key);
*/
C.HmacSHA1 = Hasher._createHmacHelper(SHA1);
}());
return CryptoJS.SHA1;
}));
},{"./core":42}],67:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./sha256"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./sha256"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var C_algo = C.algo;
var SHA256 = C_algo.SHA256;
/**
* SHA-224 hash algorithm.
*/
var SHA224 = C_algo.SHA224 = SHA256.extend({
_doReset: function () {
this._hash = new WordArray.init([
0xc1059ed8, 0x367cd507, 0x3070dd17, 0xf70e5939,
0xffc00b31, 0x68581511, 0x64f98fa7, 0xbefa4fa4
]);
},
_doFinalize: function () {
var hash = SHA256._doFinalize.call(this);
hash.sigBytes -= 4;
return hash;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA224('message');
* var hash = CryptoJS.SHA224(wordArray);
*/
C.SHA224 = SHA256._createHelper(SHA224);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA224(message, key);
*/
C.HmacSHA224 = SHA256._createHmacHelper(SHA224);
}());
return CryptoJS.SHA224;
}));
},{"./core":42,"./sha256":68}],68:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_algo = C.algo;
// Initialization and round constants tables
var H = [];
var K = [];
// Compute constants
(function () {
function isPrime(n) {
var sqrtN = Math.sqrt(n);
for (var factor = 2; factor <= sqrtN; factor++) {
if (!(n % factor)) {
return false;
}
}
return true;
}
function getFractionalBits(n) {
return ((n - (n | 0)) * 0x100000000) | 0;
}
var n = 2;
var nPrime = 0;
while (nPrime < 64) {
if (isPrime(n)) {
if (nPrime < 8) {
H[nPrime] = getFractionalBits(Math.pow(n, 1 / 2));
}
K[nPrime] = getFractionalBits(Math.pow(n, 1 / 3));
nPrime++;
}
n++;
}
}());
// Reusable object
var W = [];
/**
* SHA-256 hash algorithm.
*/
var SHA256 = C_algo.SHA256 = Hasher.extend({
_doReset: function () {
this._hash = new WordArray.init(H.slice(0));
},
_doProcessBlock: function (M, offset) {
// Shortcut
var H = this._hash.words;
// Working variables
var a = H[0];
var b = H[1];
var c = H[2];
var d = H[3];
var e = H[4];
var f = H[5];
var g = H[6];
var h = H[7];
// Computation
for (var i = 0; i < 64; i++) {
if (i < 16) {
W[i] = M[offset + i] | 0;
} else {
var gamma0x = W[i - 15];
var gamma0 = ((gamma0x << 25) | (gamma0x >>> 7)) ^
((gamma0x << 14) | (gamma0x >>> 18)) ^
(gamma0x >>> 3);
var gamma1x = W[i - 2];
var gamma1 = ((gamma1x << 15) | (gamma1x >>> 17)) ^
((gamma1x << 13) | (gamma1x >>> 19)) ^
(gamma1x >>> 10);
W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16];
}
var ch = (e & f) ^ (~e & g);
var maj = (a & b) ^ (a & c) ^ (b & c);
var sigma0 = ((a << 30) | (a >>> 2)) ^ ((a << 19) | (a >>> 13)) ^ ((a << 10) | (a >>> 22));
var sigma1 = ((e << 26) | (e >>> 6)) ^ ((e << 21) | (e >>> 11)) ^ ((e << 7) | (e >>> 25));
var t1 = h + sigma1 + ch + K[i] + W[i];
var t2 = sigma0 + maj;
h = g;
g = f;
f = e;
e = (d + t1) | 0;
d = c;
c = b;
b = a;
a = (t1 + t2) | 0;
}
// Intermediate hash value
H[0] = (H[0] + a) | 0;
H[1] = (H[1] + b) | 0;
H[2] = (H[2] + c) | 0;
H[3] = (H[3] + d) | 0;
H[4] = (H[4] + e) | 0;
H[5] = (H[5] + f) | 0;
H[6] = (H[6] + g) | 0;
H[7] = (H[7] + h) | 0;
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 14] = Math.floor(nBitsTotal / 0x100000000);
dataWords[(((nBitsLeft + 64) >>> 9) << 4) + 15] = nBitsTotal;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Return final computed hash
return this._hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA256('message');
* var hash = CryptoJS.SHA256(wordArray);
*/
C.SHA256 = Hasher._createHelper(SHA256);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA256(message, key);
*/
C.HmacSHA256 = Hasher._createHmacHelper(SHA256);
}(Math));
return CryptoJS.SHA256;
}));
},{"./core":42}],69:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (Math) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var Hasher = C_lib.Hasher;
var C_x64 = C.x64;
var X64Word = C_x64.Word;
var C_algo = C.algo;
// Constants tables
var RHO_OFFSETS = [];
var PI_INDEXES = [];
var ROUND_CONSTANTS = [];
// Compute Constants
(function () {
// Compute rho offset constants
var x = 1, y = 0;
for (var t = 0; t < 24; t++) {
RHO_OFFSETS[x + 5 * y] = ((t + 1) * (t + 2) / 2) % 64;
var newX = y % 5;
var newY = (2 * x + 3 * y) % 5;
x = newX;
y = newY;
}
// Compute pi index constants
for (var x = 0; x < 5; x++) {
for (var y = 0; y < 5; y++) {
PI_INDEXES[x + 5 * y] = y + ((2 * x + 3 * y) % 5) * 5;
}
}
// Compute round constants
var LFSR = 0x01;
for (var i = 0; i < 24; i++) {
var roundConstantMsw = 0;
var roundConstantLsw = 0;
for (var j = 0; j < 7; j++) {
if (LFSR & 0x01) {
var bitPosition = (1 << j) - 1;
if (bitPosition < 32) {
roundConstantLsw ^= 1 << bitPosition;
} else /* if (bitPosition >= 32) */ {
roundConstantMsw ^= 1 << (bitPosition - 32);
}
}
// Compute next LFSR
if (LFSR & 0x80) {
// Primitive polynomial over GF(2): x^8 + x^6 + x^5 + x^4 + 1
LFSR = (LFSR << 1) ^ 0x71;
} else {
LFSR <<= 1;
}
}
ROUND_CONSTANTS[i] = X64Word.create(roundConstantMsw, roundConstantLsw);
}
}());
// Reusable objects for temporary values
var T = [];
(function () {
for (var i = 0; i < 25; i++) {
T[i] = X64Word.create();
}
}());
/**
* SHA-3 hash algorithm.
*/
var SHA3 = C_algo.SHA3 = Hasher.extend({
/**
* Configuration options.
*
* @property {number} outputLength
* The desired number of bits in the output hash.
* Only values permitted are: 224, 256, 384, 512.
* Default: 512
*/
cfg: Hasher.cfg.extend({
outputLength: 512
}),
_doReset: function () {
var state = this._state = []
for (var i = 0; i < 25; i++) {
state[i] = new X64Word.init();
}
this.blockSize = (1600 - 2 * this.cfg.outputLength) / 32;
},
_doProcessBlock: function (M, offset) {
// Shortcuts
var state = this._state;
var nBlockSizeLanes = this.blockSize / 2;
// Absorb
for (var i = 0; i < nBlockSizeLanes; i++) {
// Shortcuts
var M2i = M[offset + 2 * i];
var M2i1 = M[offset + 2 * i + 1];
// Swap endian
M2i = (
(((M2i << 8) | (M2i >>> 24)) & 0x00ff00ff) |
(((M2i << 24) | (M2i >>> 8)) & 0xff00ff00)
);
M2i1 = (
(((M2i1 << 8) | (M2i1 >>> 24)) & 0x00ff00ff) |
(((M2i1 << 24) | (M2i1 >>> 8)) & 0xff00ff00)
);
// Absorb message into state
var lane = state[i];
lane.high ^= M2i1;
lane.low ^= M2i;
}
// Rounds
for (var round = 0; round < 24; round++) {
// Theta
for (var x = 0; x < 5; x++) {
// Mix column lanes
var tMsw = 0, tLsw = 0;
for (var y = 0; y < 5; y++) {
var lane = state[x + 5 * y];
tMsw ^= lane.high;
tLsw ^= lane.low;
}
// Temporary values
var Tx = T[x];
Tx.high = tMsw;
Tx.low = tLsw;
}
for (var x = 0; x < 5; x++) {
// Shortcuts
var Tx4 = T[(x + 4) % 5];
var Tx1 = T[(x + 1) % 5];
var Tx1Msw = Tx1.high;
var Tx1Lsw = Tx1.low;
// Mix surrounding columns
var tMsw = Tx4.high ^ ((Tx1Msw << 1) | (Tx1Lsw >>> 31));
var tLsw = Tx4.low ^ ((Tx1Lsw << 1) | (Tx1Msw >>> 31));
for (var y = 0; y < 5; y++) {
var lane = state[x + 5 * y];
lane.high ^= tMsw;
lane.low ^= tLsw;
}
}
// Rho Pi
for (var laneIndex = 1; laneIndex < 25; laneIndex++) {
// Shortcuts
var lane = state[laneIndex];
var laneMsw = lane.high;
var laneLsw = lane.low;
var rhoOffset = RHO_OFFSETS[laneIndex];
// Rotate lanes
if (rhoOffset < 32) {
var tMsw = (laneMsw << rhoOffset) | (laneLsw >>> (32 - rhoOffset));
var tLsw = (laneLsw << rhoOffset) | (laneMsw >>> (32 - rhoOffset));
} else /* if (rhoOffset >= 32) */ {
var tMsw = (laneLsw << (rhoOffset - 32)) | (laneMsw >>> (64 - rhoOffset));
var tLsw = (laneMsw << (rhoOffset - 32)) | (laneLsw >>> (64 - rhoOffset));
}
// Transpose lanes
var TPiLane = T[PI_INDEXES[laneIndex]];
TPiLane.high = tMsw;
TPiLane.low = tLsw;
}
// Rho pi at x = y = 0
var T0 = T[0];
var state0 = state[0];
T0.high = state0.high;
T0.low = state0.low;
// Chi
for (var x = 0; x < 5; x++) {
for (var y = 0; y < 5; y++) {
// Shortcuts
var laneIndex = x + 5 * y;
var lane = state[laneIndex];
var TLane = T[laneIndex];
var Tx1Lane = T[((x + 1) % 5) + 5 * y];
var Tx2Lane = T[((x + 2) % 5) + 5 * y];
// Mix rows
lane.high = TLane.high ^ (~Tx1Lane.high & Tx2Lane.high);
lane.low = TLane.low ^ (~Tx1Lane.low & Tx2Lane.low);
}
}
// Iota
var lane = state[0];
var roundConstant = ROUND_CONSTANTS[round];
lane.high ^= roundConstant.high;
lane.low ^= roundConstant.low;;
}
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
var blockSizeBits = this.blockSize * 32;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x1 << (24 - nBitsLeft % 32);
dataWords[((Math.ceil((nBitsLeft + 1) / blockSizeBits) * blockSizeBits) >>> 5) - 1] |= 0x80;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Shortcuts
var state = this._state;
var outputLengthBytes = this.cfg.outputLength / 8;
var outputLengthLanes = outputLengthBytes / 8;
// Squeeze
var hashWords = [];
for (var i = 0; i < outputLengthLanes; i++) {
// Shortcuts
var lane = state[i];
var laneMsw = lane.high;
var laneLsw = lane.low;
// Swap endian
laneMsw = (
(((laneMsw << 8) | (laneMsw >>> 24)) & 0x00ff00ff) |
(((laneMsw << 24) | (laneMsw >>> 8)) & 0xff00ff00)
);
laneLsw = (
(((laneLsw << 8) | (laneLsw >>> 24)) & 0x00ff00ff) |
(((laneLsw << 24) | (laneLsw >>> 8)) & 0xff00ff00)
);
// Squeeze state to retrieve hash
hashWords.push(laneLsw);
hashWords.push(laneMsw);
}
// Return final computed hash
return new WordArray.init(hashWords, outputLengthBytes);
},
clone: function () {
var clone = Hasher.clone.call(this);
var state = clone._state = this._state.slice(0);
for (var i = 0; i < 25; i++) {
state[i] = state[i].clone();
}
return clone;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA3('message');
* var hash = CryptoJS.SHA3(wordArray);
*/
C.SHA3 = Hasher._createHelper(SHA3);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA3(message, key);
*/
C.HmacSHA3 = Hasher._createHmacHelper(SHA3);
}(Math));
return CryptoJS.SHA3;
}));
},{"./core":42,"./x64-core":73}],70:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"), _dereq_("./sha512"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core", "./sha512"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_x64 = C.x64;
var X64Word = C_x64.Word;
var X64WordArray = C_x64.WordArray;
var C_algo = C.algo;
var SHA512 = C_algo.SHA512;
/**
* SHA-384 hash algorithm.
*/
var SHA384 = C_algo.SHA384 = SHA512.extend({
_doReset: function () {
this._hash = new X64WordArray.init([
new X64Word.init(0xcbbb9d5d, 0xc1059ed8), new X64Word.init(0x629a292a, 0x367cd507),
new X64Word.init(0x9159015a, 0x3070dd17), new X64Word.init(0x152fecd8, 0xf70e5939),
new X64Word.init(0x67332667, 0xffc00b31), new X64Word.init(0x8eb44a87, 0x68581511),
new X64Word.init(0xdb0c2e0d, 0x64f98fa7), new X64Word.init(0x47b5481d, 0xbefa4fa4)
]);
},
_doFinalize: function () {
var hash = SHA512._doFinalize.call(this);
hash.sigBytes -= 16;
return hash;
}
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA384('message');
* var hash = CryptoJS.SHA384(wordArray);
*/
C.SHA384 = SHA512._createHelper(SHA384);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA384(message, key);
*/
C.HmacSHA384 = SHA512._createHmacHelper(SHA384);
}());
return CryptoJS.SHA384;
}));
},{"./core":42,"./sha512":71,"./x64-core":73}],71:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./x64-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./x64-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Hasher = C_lib.Hasher;
var C_x64 = C.x64;
var X64Word = C_x64.Word;
var X64WordArray = C_x64.WordArray;
var C_algo = C.algo;
function X64Word_create() {
return X64Word.create.apply(X64Word, arguments);
}
// Constants
var K = [
X64Word_create(0x428a2f98, 0xd728ae22), X64Word_create(0x71374491, 0x23ef65cd),
X64Word_create(0xb5c0fbcf, 0xec4d3b2f), X64Word_create(0xe9b5dba5, 0x8189dbbc),
X64Word_create(0x3956c25b, 0xf348b538), X64Word_create(0x59f111f1, 0xb605d019),
X64Word_create(0x923f82a4, 0xaf194f9b), X64Word_create(0xab1c5ed5, 0xda6d8118),
X64Word_create(0xd807aa98, 0xa3030242), X64Word_create(0x12835b01, 0x45706fbe),
X64Word_create(0x243185be, 0x4ee4b28c), X64Word_create(0x550c7dc3, 0xd5ffb4e2),
X64Word_create(0x72be5d74, 0xf27b896f), X64Word_create(0x80deb1fe, 0x3b1696b1),
X64Word_create(0x9bdc06a7, 0x25c71235), X64Word_create(0xc19bf174, 0xcf692694),
X64Word_create(0xe49b69c1, 0x9ef14ad2), X64Word_create(0xefbe4786, 0x384f25e3),
X64Word_create(0x0fc19dc6, 0x8b8cd5b5), X64Word_create(0x240ca1cc, 0x77ac9c65),
X64Word_create(0x2de92c6f, 0x592b0275), X64Word_create(0x4a7484aa, 0x6ea6e483),
X64Word_create(0x5cb0a9dc, 0xbd41fbd4), X64Word_create(0x76f988da, 0x831153b5),
X64Word_create(0x983e5152, 0xee66dfab), X64Word_create(0xa831c66d, 0x2db43210),
X64Word_create(0xb00327c8, 0x98fb213f), X64Word_create(0xbf597fc7, 0xbeef0ee4),
X64Word_create(0xc6e00bf3, 0x3da88fc2), X64Word_create(0xd5a79147, 0x930aa725),
X64Word_create(0x06ca6351, 0xe003826f), X64Word_create(0x14292967, 0x0a0e6e70),
X64Word_create(0x27b70a85, 0x46d22ffc), X64Word_create(0x2e1b2138, 0x5c26c926),
X64Word_create(0x4d2c6dfc, 0x5ac42aed), X64Word_create(0x53380d13, 0x9d95b3df),
X64Word_create(0x650a7354, 0x8baf63de), X64Word_create(0x766a0abb, 0x3c77b2a8),
X64Word_create(0x81c2c92e, 0x47edaee6), X64Word_create(0x92722c85, 0x1482353b),
X64Word_create(0xa2bfe8a1, 0x4cf10364), X64Word_create(0xa81a664b, 0xbc423001),
X64Word_create(0xc24b8b70, 0xd0f89791), X64Word_create(0xc76c51a3, 0x0654be30),
X64Word_create(0xd192e819, 0xd6ef5218), X64Word_create(0xd6990624, 0x5565a910),
X64Word_create(0xf40e3585, 0x5771202a), X64Word_create(0x106aa070, 0x32bbd1b8),
X64Word_create(0x19a4c116, 0xb8d2d0c8), X64Word_create(0x1e376c08, 0x5141ab53),
X64Word_create(0x2748774c, 0xdf8eeb99), X64Word_create(0x34b0bcb5, 0xe19b48a8),
X64Word_create(0x391c0cb3, 0xc5c95a63), X64Word_create(0x4ed8aa4a, 0xe3418acb),
X64Word_create(0x5b9cca4f, 0x7763e373), X64Word_create(0x682e6ff3, 0xd6b2b8a3),
X64Word_create(0x748f82ee, 0x5defb2fc), X64Word_create(0x78a5636f, 0x43172f60),
X64Word_create(0x84c87814, 0xa1f0ab72), X64Word_create(0x8cc70208, 0x1a6439ec),
X64Word_create(0x90befffa, 0x23631e28), X64Word_create(0xa4506ceb, 0xde82bde9),
X64Word_create(0xbef9a3f7, 0xb2c67915), X64Word_create(0xc67178f2, 0xe372532b),
X64Word_create(0xca273ece, 0xea26619c), X64Word_create(0xd186b8c7, 0x21c0c207),
X64Word_create(0xeada7dd6, 0xcde0eb1e), X64Word_create(0xf57d4f7f, 0xee6ed178),
X64Word_create(0x06f067aa, 0x72176fba), X64Word_create(0x0a637dc5, 0xa2c898a6),
X64Word_create(0x113f9804, 0xbef90dae), X64Word_create(0x1b710b35, 0x131c471b),
X64Word_create(0x28db77f5, 0x23047d84), X64Word_create(0x32caab7b, 0x40c72493),
X64Word_create(0x3c9ebe0a, 0x15c9bebc), X64Word_create(0x431d67c4, 0x9c100d4c),
X64Word_create(0x4cc5d4be, 0xcb3e42b6), X64Word_create(0x597f299c, 0xfc657e2a),
X64Word_create(0x5fcb6fab, 0x3ad6faec), X64Word_create(0x6c44198c, 0x4a475817)
];
// Reusable objects
var W = [];
(function () {
for (var i = 0; i < 80; i++) {
W[i] = X64Word_create();
}
}());
/**
* SHA-512 hash algorithm.
*/
var SHA512 = C_algo.SHA512 = Hasher.extend({
_doReset: function () {
this._hash = new X64WordArray.init([
new X64Word.init(0x6a09e667, 0xf3bcc908), new X64Word.init(0xbb67ae85, 0x84caa73b),
new X64Word.init(0x3c6ef372, 0xfe94f82b), new X64Word.init(0xa54ff53a, 0x5f1d36f1),
new X64Word.init(0x510e527f, 0xade682d1), new X64Word.init(0x9b05688c, 0x2b3e6c1f),
new X64Word.init(0x1f83d9ab, 0xfb41bd6b), new X64Word.init(0x5be0cd19, 0x137e2179)
]);
},
_doProcessBlock: function (M, offset) {
// Shortcuts
var H = this._hash.words;
var H0 = H[0];
var H1 = H[1];
var H2 = H[2];
var H3 = H[3];
var H4 = H[4];
var H5 = H[5];
var H6 = H[6];
var H7 = H[7];
var H0h = H0.high;
var H0l = H0.low;
var H1h = H1.high;
var H1l = H1.low;
var H2h = H2.high;
var H2l = H2.low;
var H3h = H3.high;
var H3l = H3.low;
var H4h = H4.high;
var H4l = H4.low;
var H5h = H5.high;
var H5l = H5.low;
var H6h = H6.high;
var H6l = H6.low;
var H7h = H7.high;
var H7l = H7.low;
// Working variables
var ah = H0h;
var al = H0l;
var bh = H1h;
var bl = H1l;
var ch = H2h;
var cl = H2l;
var dh = H3h;
var dl = H3l;
var eh = H4h;
var el = H4l;
var fh = H5h;
var fl = H5l;
var gh = H6h;
var gl = H6l;
var hh = H7h;
var hl = H7l;
// Rounds
for (var i = 0; i < 80; i++) {
// Shortcut
var Wi = W[i];
// Extend message
if (i < 16) {
var Wih = Wi.high = M[offset + i * 2] | 0;
var Wil = Wi.low = M[offset + i * 2 + 1] | 0;
} else {
// Gamma0
var gamma0x = W[i - 15];
var gamma0xh = gamma0x.high;
var gamma0xl = gamma0x.low;
var gamma0h = ((gamma0xh >>> 1) | (gamma0xl << 31)) ^ ((gamma0xh >>> 8) | (gamma0xl << 24)) ^ (gamma0xh >>> 7);
var gamma0l = ((gamma0xl >>> 1) | (gamma0xh << 31)) ^ ((gamma0xl >>> 8) | (gamma0xh << 24)) ^ ((gamma0xl >>> 7) | (gamma0xh << 25));
// Gamma1
var gamma1x = W[i - 2];
var gamma1xh = gamma1x.high;
var gamma1xl = gamma1x.low;
var gamma1h = ((gamma1xh >>> 19) | (gamma1xl << 13)) ^ ((gamma1xh << 3) | (gamma1xl >>> 29)) ^ (gamma1xh >>> 6);
var gamma1l = ((gamma1xl >>> 19) | (gamma1xh << 13)) ^ ((gamma1xl << 3) | (gamma1xh >>> 29)) ^ ((gamma1xl >>> 6) | (gamma1xh << 26));
// W[i] = gamma0 + W[i - 7] + gamma1 + W[i - 16]
var Wi7 = W[i - 7];
var Wi7h = Wi7.high;
var Wi7l = Wi7.low;
var Wi16 = W[i - 16];
var Wi16h = Wi16.high;
var Wi16l = Wi16.low;
var Wil = gamma0l + Wi7l;
var Wih = gamma0h + Wi7h + ((Wil >>> 0) < (gamma0l >>> 0) ? 1 : 0);
var Wil = Wil + gamma1l;
var Wih = Wih + gamma1h + ((Wil >>> 0) < (gamma1l >>> 0) ? 1 : 0);
var Wil = Wil + Wi16l;
var Wih = Wih + Wi16h + ((Wil >>> 0) < (Wi16l >>> 0) ? 1 : 0);
Wi.high = Wih;
Wi.low = Wil;
}
var chh = (eh & fh) ^ (~eh & gh);
var chl = (el & fl) ^ (~el & gl);
var majh = (ah & bh) ^ (ah & ch) ^ (bh & ch);
var majl = (al & bl) ^ (al & cl) ^ (bl & cl);
var sigma0h = ((ah >>> 28) | (al << 4)) ^ ((ah << 30) | (al >>> 2)) ^ ((ah << 25) | (al >>> 7));
var sigma0l = ((al >>> 28) | (ah << 4)) ^ ((al << 30) | (ah >>> 2)) ^ ((al << 25) | (ah >>> 7));
var sigma1h = ((eh >>> 14) | (el << 18)) ^ ((eh >>> 18) | (el << 14)) ^ ((eh << 23) | (el >>> 9));
var sigma1l = ((el >>> 14) | (eh << 18)) ^ ((el >>> 18) | (eh << 14)) ^ ((el << 23) | (eh >>> 9));
// t1 = h + sigma1 + ch + K[i] + W[i]
var Ki = K[i];
var Kih = Ki.high;
var Kil = Ki.low;
var t1l = hl + sigma1l;
var t1h = hh + sigma1h + ((t1l >>> 0) < (hl >>> 0) ? 1 : 0);
var t1l = t1l + chl;
var t1h = t1h + chh + ((t1l >>> 0) < (chl >>> 0) ? 1 : 0);
var t1l = t1l + Kil;
var t1h = t1h + Kih + ((t1l >>> 0) < (Kil >>> 0) ? 1 : 0);
var t1l = t1l + Wil;
var t1h = t1h + Wih + ((t1l >>> 0) < (Wil >>> 0) ? 1 : 0);
// t2 = sigma0 + maj
var t2l = sigma0l + majl;
var t2h = sigma0h + majh + ((t2l >>> 0) < (sigma0l >>> 0) ? 1 : 0);
// Update working variables
hh = gh;
hl = gl;
gh = fh;
gl = fl;
fh = eh;
fl = el;
el = (dl + t1l) | 0;
eh = (dh + t1h + ((el >>> 0) < (dl >>> 0) ? 1 : 0)) | 0;
dh = ch;
dl = cl;
ch = bh;
cl = bl;
bh = ah;
bl = al;
al = (t1l + t2l) | 0;
ah = (t1h + t2h + ((al >>> 0) < (t1l >>> 0) ? 1 : 0)) | 0;
}
// Intermediate hash value
H0l = H0.low = (H0l + al);
H0.high = (H0h + ah + ((H0l >>> 0) < (al >>> 0) ? 1 : 0));
H1l = H1.low = (H1l + bl);
H1.high = (H1h + bh + ((H1l >>> 0) < (bl >>> 0) ? 1 : 0));
H2l = H2.low = (H2l + cl);
H2.high = (H2h + ch + ((H2l >>> 0) < (cl >>> 0) ? 1 : 0));
H3l = H3.low = (H3l + dl);
H3.high = (H3h + dh + ((H3l >>> 0) < (dl >>> 0) ? 1 : 0));
H4l = H4.low = (H4l + el);
H4.high = (H4h + eh + ((H4l >>> 0) < (el >>> 0) ? 1 : 0));
H5l = H5.low = (H5l + fl);
H5.high = (H5h + fh + ((H5l >>> 0) < (fl >>> 0) ? 1 : 0));
H6l = H6.low = (H6l + gl);
H6.high = (H6h + gh + ((H6l >>> 0) < (gl >>> 0) ? 1 : 0));
H7l = H7.low = (H7l + hl);
H7.high = (H7h + hh + ((H7l >>> 0) < (hl >>> 0) ? 1 : 0));
},
_doFinalize: function () {
// Shortcuts
var data = this._data;
var dataWords = data.words;
var nBitsTotal = this._nDataBytes * 8;
var nBitsLeft = data.sigBytes * 8;
// Add padding
dataWords[nBitsLeft >>> 5] |= 0x80 << (24 - nBitsLeft % 32);
dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 30] = Math.floor(nBitsTotal / 0x100000000);
dataWords[(((nBitsLeft + 128) >>> 10) << 5) + 31] = nBitsTotal;
data.sigBytes = dataWords.length * 4;
// Hash final blocks
this._process();
// Convert hash to 32-bit word array before returning
var hash = this._hash.toX32();
// Return final computed hash
return hash;
},
clone: function () {
var clone = Hasher.clone.call(this);
clone._hash = this._hash.clone();
return clone;
},
blockSize: 1024/32
});
/**
* Shortcut function to the hasher's object interface.
*
* @param {WordArray|string} message The message to hash.
*
* @return {WordArray} The hash.
*
* @static
*
* @example
*
* var hash = CryptoJS.SHA512('message');
* var hash = CryptoJS.SHA512(wordArray);
*/
C.SHA512 = Hasher._createHelper(SHA512);
/**
* Shortcut function to the HMAC's object interface.
*
* @param {WordArray|string} message The message to hash.
* @param {WordArray|string} key The secret key.
*
* @return {WordArray} The HMAC.
*
* @static
*
* @example
*
* var hmac = CryptoJS.HmacSHA512(message, key);
*/
C.HmacSHA512 = Hasher._createHmacHelper(SHA512);
}());
return CryptoJS.SHA512;
}));
},{"./core":42,"./x64-core":73}],72:[function(_dereq_,module,exports){
;(function (root, factory, undef) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"), _dereq_("./enc-base64"), _dereq_("./md5"), _dereq_("./evpkdf"), _dereq_("./cipher-core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core", "./enc-base64", "./md5", "./evpkdf", "./cipher-core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function () {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var WordArray = C_lib.WordArray;
var BlockCipher = C_lib.BlockCipher;
var C_algo = C.algo;
// Permuted Choice 1 constants
var PC1 = [
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
];
// Permuted Choice 2 constants
var PC2 = [
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
];
// Cumulative bit shift constants
var BIT_SHIFTS = [1, 2, 4, 6, 8, 10, 12, 14, 15, 17, 19, 21, 23, 25, 27, 28];
// SBOXes and round permutation constants
var SBOX_P = [
{
0x0: 0x808200,
0x10000000: 0x8000,
0x20000000: 0x808002,
0x30000000: 0x2,
0x40000000: 0x200,
0x50000000: 0x808202,
0x60000000: 0x800202,
0x70000000: 0x800000,
0x80000000: 0x202,
0x90000000: 0x800200,
0xa0000000: 0x8200,
0xb0000000: 0x808000,
0xc0000000: 0x8002,
0xd0000000: 0x800002,
0xe0000000: 0x0,
0xf0000000: 0x8202,
0x8000000: 0x0,
0x18000000: 0x808202,
0x28000000: 0x8202,
0x38000000: 0x8000,
0x48000000: 0x808200,
0x58000000: 0x200,
0x68000000: 0x808002,
0x78000000: 0x2,
0x88000000: 0x800200,
0x98000000: 0x8200,
0xa8000000: 0x808000,
0xb8000000: 0x800202,
0xc8000000: 0x800002,
0xd8000000: 0x8002,
0xe8000000: 0x202,
0xf8000000: 0x800000,
0x1: 0x8000,
0x10000001: 0x2,
0x20000001: 0x808200,
0x30000001: 0x800000,
0x40000001: 0x808002,
0x50000001: 0x8200,
0x60000001: 0x200,
0x70000001: 0x800202,
0x80000001: 0x808202,
0x90000001: 0x808000,
0xa0000001: 0x800002,
0xb0000001: 0x8202,
0xc0000001: 0x202,
0xd0000001: 0x800200,
0xe0000001: 0x8002,
0xf0000001: 0x0,
0x8000001: 0x808202,
0x18000001: 0x808000,
0x28000001: 0x800000,
0x38000001: 0x200,
0x48000001: 0x8000,
0x58000001: 0x800002,
0x68000001: 0x2,
0x78000001: 0x8202,
0x88000001: 0x8002,
0x98000001: 0x800202,
0xa8000001: 0x202,
0xb8000001: 0x808200,
0xc8000001: 0x800200,
0xd8000001: 0x0,
0xe8000001: 0x8200,
0xf8000001: 0x808002
},
{
0x0: 0x40084010,
0x1000000: 0x4000,
0x2000000: 0x80000,
0x3000000: 0x40080010,
0x4000000: 0x40000010,
0x5000000: 0x40084000,
0x6000000: 0x40004000,
0x7000000: 0x10,
0x8000000: 0x84000,
0x9000000: 0x40004010,
0xa000000: 0x40000000,
0xb000000: 0x84010,
0xc000000: 0x80010,
0xd000000: 0x0,
0xe000000: 0x4010,
0xf000000: 0x40080000,
0x800000: 0x40004000,
0x1800000: 0x84010,
0x2800000: 0x10,
0x3800000: 0x40004010,
0x4800000: 0x40084010,
0x5800000: 0x40000000,
0x6800000: 0x80000,
0x7800000: 0x40080010,
0x8800000: 0x80010,
0x9800000: 0x0,
0xa800000: 0x4000,
0xb800000: 0x40080000,
0xc800000: 0x40000010,
0xd800000: 0x84000,
0xe800000: 0x40084000,
0xf800000: 0x4010,
0x10000000: 0x0,
0x11000000: 0x40080010,
0x12000000: 0x40004010,
0x13000000: 0x40084000,
0x14000000: 0x40080000,
0x15000000: 0x10,
0x16000000: 0x84010,
0x17000000: 0x4000,
0x18000000: 0x4010,
0x19000000: 0x80000,
0x1a000000: 0x80010,
0x1b000000: 0x40000010,
0x1c000000: 0x84000,
0x1d000000: 0x40004000,
0x1e000000: 0x40000000,
0x1f000000: 0x40084010,
0x10800000: 0x84010,
0x11800000: 0x80000,
0x12800000: 0x40080000,
0x13800000: 0x4000,
0x14800000: 0x40004000,
0x15800000: 0x40084010,
0x16800000: 0x10,
0x17800000: 0x40000000,
0x18800000: 0x40084000,
0x19800000: 0x40000010,
0x1a800000: 0x40004010,
0x1b800000: 0x80010,
0x1c800000: 0x0,
0x1d800000: 0x4010,
0x1e800000: 0x40080010,
0x1f800000: 0x84000
},
{
0x0: 0x104,
0x100000: 0x0,
0x200000: 0x4000100,
0x300000: 0x10104,
0x400000: 0x10004,
0x500000: 0x4000004,
0x600000: 0x4010104,
0x700000: 0x4010000,
0x800000: 0x4000000,
0x900000: 0x4010100,
0xa00000: 0x10100,
0xb00000: 0x4010004,
0xc00000: 0x4000104,
0xd00000: 0x10000,
0xe00000: 0x4,
0xf00000: 0x100,
0x80000: 0x4010100,
0x180000: 0x4010004,
0x280000: 0x0,
0x380000: 0x4000100,
0x480000: 0x4000004,
0x580000: 0x10000,
0x680000: 0x10004,
0x780000: 0x104,
0x880000: 0x4,
0x980000: 0x100,
0xa80000: 0x4010000,
0xb80000: 0x10104,
0xc80000: 0x10100,
0xd80000: 0x4000104,
0xe80000: 0x4010104,
0xf80000: 0x4000000,
0x1000000: 0x4010100,
0x1100000: 0x10004,
0x1200000: 0x10000,
0x1300000: 0x4000100,
0x1400000: 0x100,
0x1500000: 0x4010104,
0x1600000: 0x4000004,
0x1700000: 0x0,
0x1800000: 0x4000104,
0x1900000: 0x4000000,
0x1a00000: 0x4,
0x1b00000: 0x10100,
0x1c00000: 0x4010000,
0x1d00000: 0x104,
0x1e00000: 0x10104,
0x1f00000: 0x4010004,
0x1080000: 0x4000000,
0x1180000: 0x104,
0x1280000: 0x4010100,
0x1380000: 0x0,
0x1480000: 0x10004,
0x1580000: 0x4000100,
0x1680000: 0x100,
0x1780000: 0x4010004,
0x1880000: 0x10000,
0x1980000: 0x4010104,
0x1a80000: 0x10104,
0x1b80000: 0x4000004,
0x1c80000: 0x4000104,
0x1d80000: 0x4010000,
0x1e80000: 0x4,
0x1f80000: 0x10100
},
{
0x0: 0x80401000,
0x10000: 0x80001040,
0x20000: 0x401040,
0x30000: 0x80400000,
0x40000: 0x0,
0x50000: 0x401000,
0x60000: 0x80000040,
0x70000: 0x400040,
0x80000: 0x80000000,
0x90000: 0x400000,
0xa0000: 0x40,
0xb0000: 0x80001000,
0xc0000: 0x80400040,
0xd0000: 0x1040,
0xe0000: 0x1000,
0xf0000: 0x80401040,
0x8000: 0x80001040,
0x18000: 0x40,
0x28000: 0x80400040,
0x38000: 0x80001000,
0x48000: 0x401000,
0x58000: 0x80401040,
0x68000: 0x0,
0x78000: 0x80400000,
0x88000: 0x1000,
0x98000: 0x80401000,
0xa8000: 0x400000,
0xb8000: 0x1040,
0xc8000: 0x80000000,
0xd8000: 0x400040,
0xe8000: 0x401040,
0xf8000: 0x80000040,
0x100000: 0x400040,
0x110000: 0x401000,
0x120000: 0x80000040,
0x130000: 0x0,
0x140000: 0x1040,
0x150000: 0x80400040,
0x160000: 0x80401000,
0x170000: 0x80001040,
0x180000: 0x80401040,
0x190000: 0x80000000,
0x1a0000: 0x80400000,
0x1b0000: 0x401040,
0x1c0000: 0x80001000,
0x1d0000: 0x400000,
0x1e0000: 0x40,
0x1f0000: 0x1000,
0x108000: 0x80400000,
0x118000: 0x80401040,
0x128000: 0x0,
0x138000: 0x401000,
0x148000: 0x400040,
0x158000: 0x80000000,
0x168000: 0x80001040,
0x178000: 0x40,
0x188000: 0x80000040,
0x198000: 0x1000,
0x1a8000: 0x80001000,
0x1b8000: 0x80400040,
0x1c8000: 0x1040,
0x1d8000: 0x80401000,
0x1e8000: 0x400000,
0x1f8000: 0x401040
},
{
0x0: 0x80,
0x1000: 0x1040000,
0x2000: 0x40000,
0x3000: 0x20000000,
0x4000: 0x20040080,
0x5000: 0x1000080,
0x6000: 0x21000080,
0x7000: 0x40080,
0x8000: 0x1000000,
0x9000: 0x20040000,
0xa000: 0x20000080,
0xb000: 0x21040080,
0xc000: 0x21040000,
0xd000: 0x0,
0xe000: 0x1040080,
0xf000: 0x21000000,
0x800: 0x1040080,
0x1800: 0x21000080,
0x2800: 0x80,
0x3800: 0x1040000,
0x4800: 0x40000,
0x5800: 0x20040080,
0x6800: 0x21040000,
0x7800: 0x20000000,
0x8800: 0x20040000,
0x9800: 0x0,
0xa800: 0x21040080,
0xb800: 0x1000080,
0xc800: 0x20000080,
0xd800: 0x21000000,
0xe800: 0x1000000,
0xf800: 0x40080,
0x10000: 0x40000,
0x11000: 0x80,
0x12000: 0x20000000,
0x13000: 0x21000080,
0x14000: 0x1000080,
0x15000: 0x21040000,
0x16000: 0x20040080,
0x17000: 0x1000000,
0x18000: 0x21040080,
0x19000: 0x21000000,
0x1a000: 0x1040000,
0x1b000: 0x20040000,
0x1c000: 0x40080,
0x1d000: 0x20000080,
0x1e000: 0x0,
0x1f000: 0x1040080,
0x10800: 0x21000080,
0x11800: 0x1000000,
0x12800: 0x1040000,
0x13800: 0x20040080,
0x14800: 0x20000000,
0x15800: 0x1040080,
0x16800: 0x80,
0x17800: 0x21040000,
0x18800: 0x40080,
0x19800: 0x21040080,
0x1a800: 0x0,
0x1b800: 0x21000000,
0x1c800: 0x1000080,
0x1d800: 0x40000,
0x1e800: 0x20040000,
0x1f800: 0x20000080
},
{
0x0: 0x10000008,
0x100: 0x2000,
0x200: 0x10200000,
0x300: 0x10202008,
0x400: 0x10002000,
0x500: 0x200000,
0x600: 0x200008,
0x700: 0x10000000,
0x800: 0x0,
0x900: 0x10002008,
0xa00: 0x202000,
0xb00: 0x8,
0xc00: 0x10200008,
0xd00: 0x202008,
0xe00: 0x2008,
0xf00: 0x10202000,
0x80: 0x10200000,
0x180: 0x10202008,
0x280: 0x8,
0x380: 0x200000,
0x480: 0x202008,
0x580: 0x10000008,
0x680: 0x10002000,
0x780: 0x2008,
0x880: 0x200008,
0x980: 0x2000,
0xa80: 0x10002008,
0xb80: 0x10200008,
0xc80: 0x0,
0xd80: 0x10202000,
0xe80: 0x202000,
0xf80: 0x10000000,
0x1000: 0x10002000,
0x1100: 0x10200008,
0x1200: 0x10202008,
0x1300: 0x2008,
0x1400: 0x200000,
0x1500: 0x10000000,
0x1600: 0x10000008,
0x1700: 0x202000,
0x1800: 0x202008,
0x1900: 0x0,
0x1a00: 0x8,
0x1b00: 0x10200000,
0x1c00: 0x2000,
0x1d00: 0x10002008,
0x1e00: 0x10202000,
0x1f00: 0x200008,
0x1080: 0x8,
0x1180: 0x202000,
0x1280: 0x200000,
0x1380: 0x10000008,
0x1480: 0x10002000,
0x1580: 0x2008,
0x1680: 0x10202008,
0x1780: 0x10200000,
0x1880: 0x10202000,
0x1980: 0x10200008,
0x1a80: 0x2000,
0x1b80: 0x202008,
0x1c80: 0x200008,
0x1d80: 0x0,
0x1e80: 0x10000000,
0x1f80: 0x10002008
},
{
0x0: 0x100000,
0x10: 0x2000401,
0x20: 0x400,
0x30: 0x100401,
0x40: 0x2100401,
0x50: 0x0,
0x60: 0x1,
0x70: 0x2100001,
0x80: 0x2000400,
0x90: 0x100001,
0xa0: 0x2000001,
0xb0: 0x2100400,
0xc0: 0x2100000,
0xd0: 0x401,
0xe0: 0x100400,
0xf0: 0x2000000,
0x8: 0x2100001,
0x18: 0x0,
0x28: 0x2000401,
0x38: 0x2100400,
0x48: 0x100000,
0x58: 0x2000001,
0x68: 0x2000000,
0x78: 0x401,
0x88: 0x100401,
0x98: 0x2000400,
0xa8: 0x2100000,
0xb8: 0x100001,
0xc8: 0x400,
0xd8: 0x2100401,
0xe8: 0x1,
0xf8: 0x100400,
0x100: 0x2000000,
0x110: 0x100000,
0x120: 0x2000401,
0x130: 0x2100001,
0x140: 0x100001,
0x150: 0x2000400,
0x160: 0x2100400,
0x170: 0x100401,
0x180: 0x401,
0x190: 0x2100401,
0x1a0: 0x100400,
0x1b0: 0x1,
0x1c0: 0x0,
0x1d0: 0x2100000,
0x1e0: 0x2000001,
0x1f0: 0x400,
0x108: 0x100400,
0x118: 0x2000401,
0x128: 0x2100001,
0x138: 0x1,
0x148: 0x2000000,
0x158: 0x100000,
0x168: 0x401,
0x178: 0x2100400,
0x188: 0x2000001,
0x198: 0x2100000,
0x1a8: 0x0,
0x1b8: 0x2100401,
0x1c8: 0x100401,
0x1d8: 0x400,
0x1e8: 0x2000400,
0x1f8: 0x100001
},
{
0x0: 0x8000820,
0x1: 0x20000,
0x2: 0x8000000,
0x3: 0x20,
0x4: 0x20020,
0x5: 0x8020820,
0x6: 0x8020800,
0x7: 0x800,
0x8: 0x8020000,
0x9: 0x8000800,
0xa: 0x20800,
0xb: 0x8020020,
0xc: 0x820,
0xd: 0x0,
0xe: 0x8000020,
0xf: 0x20820,
0x80000000: 0x800,
0x80000001: 0x8020820,
0x80000002: 0x8000820,
0x80000003: 0x8000000,
0x80000004: 0x8020000,
0x80000005: 0x20800,
0x80000006: 0x20820,
0x80000007: 0x20,
0x80000008: 0x8000020,
0x80000009: 0x820,
0x8000000a: 0x20020,
0x8000000b: 0x8020800,
0x8000000c: 0x0,
0x8000000d: 0x8020020,
0x8000000e: 0x8000800,
0x8000000f: 0x20000,
0x10: 0x20820,
0x11: 0x8020800,
0x12: 0x20,
0x13: 0x800,
0x14: 0x8000800,
0x15: 0x8000020,
0x16: 0x8020020,
0x17: 0x20000,
0x18: 0x0,
0x19: 0x20020,
0x1a: 0x8020000,
0x1b: 0x8000820,
0x1c: 0x8020820,
0x1d: 0x20800,
0x1e: 0x820,
0x1f: 0x8000000,
0x80000010: 0x20000,
0x80000011: 0x800,
0x80000012: 0x8020020,
0x80000013: 0x20820,
0x80000014: 0x20,
0x80000015: 0x8020000,
0x80000016: 0x8000000,
0x80000017: 0x8000820,
0x80000018: 0x8020820,
0x80000019: 0x8000020,
0x8000001a: 0x8000800,
0x8000001b: 0x0,
0x8000001c: 0x20800,
0x8000001d: 0x820,
0x8000001e: 0x20020,
0x8000001f: 0x8020800
}
];
// Masks that select the SBOX input
var SBOX_MASK = [
0xf8000001, 0x1f800000, 0x01f80000, 0x001f8000,
0x0001f800, 0x00001f80, 0x000001f8, 0x8000001f
];
/**
* DES block cipher algorithm.
*/
var DES = C_algo.DES = BlockCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
// Select 56 bits according to PC1
var keyBits = [];
for (var i = 0; i < 56; i++) {
var keyBitPos = PC1[i] - 1;
keyBits[i] = (keyWords[keyBitPos >>> 5] >>> (31 - keyBitPos % 32)) & 1;
}
// Assemble 16 subkeys
var subKeys = this._subKeys = [];
for (var nSubKey = 0; nSubKey < 16; nSubKey++) {
// Create subkey
var subKey = subKeys[nSubKey] = [];
// Shortcut
var bitShift = BIT_SHIFTS[nSubKey];
// Select 48 bits according to PC2
for (var i = 0; i < 24; i++) {
// Select from the left 28 key bits
subKey[(i / 6) | 0] |= keyBits[((PC2[i] - 1) + bitShift) % 28] << (31 - i % 6);
// Select from the right 28 key bits
subKey[4 + ((i / 6) | 0)] |= keyBits[28 + (((PC2[i + 24] - 1) + bitShift) % 28)] << (31 - i % 6);
}
// Since each subkey is applied to an expanded 32-bit input,
// the subkey can be broken into 8 values scaled to 32-bits,
// which allows the key to be used without expansion
subKey[0] = (subKey[0] << 1) | (subKey[0] >>> 31);
for (var i = 1; i < 7; i++) {
subKey[i] = subKey[i] >>> ((i - 1) * 4 + 3);
}
subKey[7] = (subKey[7] << 5) | (subKey[7] >>> 27);
}
// Compute inverse subkeys
var invSubKeys = this._invSubKeys = [];
for (var i = 0; i < 16; i++) {
invSubKeys[i] = subKeys[15 - i];
}
},
encryptBlock: function (M, offset) {
this._doCryptBlock(M, offset, this._subKeys);
},
decryptBlock: function (M, offset) {
this._doCryptBlock(M, offset, this._invSubKeys);
},
_doCryptBlock: function (M, offset, subKeys) {
// Get input
this._lBlock = M[offset];
this._rBlock = M[offset + 1];
// Initial permutation
exchangeLR.call(this, 4, 0x0f0f0f0f);
exchangeLR.call(this, 16, 0x0000ffff);
exchangeRL.call(this, 2, 0x33333333);
exchangeRL.call(this, 8, 0x00ff00ff);
exchangeLR.call(this, 1, 0x55555555);
// Rounds
for (var round = 0; round < 16; round++) {
// Shortcuts
var subKey = subKeys[round];
var lBlock = this._lBlock;
var rBlock = this._rBlock;
// Feistel function
var f = 0;
for (var i = 0; i < 8; i++) {
f |= SBOX_P[i][((rBlock ^ subKey[i]) & SBOX_MASK[i]) >>> 0];
}
this._lBlock = rBlock;
this._rBlock = lBlock ^ f;
}
// Undo swap from last round
var t = this._lBlock;
this._lBlock = this._rBlock;
this._rBlock = t;
// Final permutation
exchangeLR.call(this, 1, 0x55555555);
exchangeRL.call(this, 8, 0x00ff00ff);
exchangeRL.call(this, 2, 0x33333333);
exchangeLR.call(this, 16, 0x0000ffff);
exchangeLR.call(this, 4, 0x0f0f0f0f);
// Set output
M[offset] = this._lBlock;
M[offset + 1] = this._rBlock;
},
keySize: 64/32,
ivSize: 64/32,
blockSize: 64/32
});
// Swap bits across the left and right words
function exchangeLR(offset, mask) {
var t = ((this._lBlock >>> offset) ^ this._rBlock) & mask;
this._rBlock ^= t;
this._lBlock ^= t << offset;
}
function exchangeRL(offset, mask) {
var t = ((this._rBlock >>> offset) ^ this._lBlock) & mask;
this._lBlock ^= t;
this._rBlock ^= t << offset;
}
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.DES.encrypt(message, key, cfg);
* var plaintext = CryptoJS.DES.decrypt(ciphertext, key, cfg);
*/
C.DES = BlockCipher._createHelper(DES);
/**
* Triple-DES block cipher algorithm.
*/
var TripleDES = C_algo.TripleDES = BlockCipher.extend({
_doReset: function () {
// Shortcuts
var key = this._key;
var keyWords = key.words;
// Create DES instances
this._des1 = DES.createEncryptor(WordArray.create(keyWords.slice(0, 2)));
this._des2 = DES.createEncryptor(WordArray.create(keyWords.slice(2, 4)));
this._des3 = DES.createEncryptor(WordArray.create(keyWords.slice(4, 6)));
},
encryptBlock: function (M, offset) {
this._des1.encryptBlock(M, offset);
this._des2.decryptBlock(M, offset);
this._des3.encryptBlock(M, offset);
},
decryptBlock: function (M, offset) {
this._des3.decryptBlock(M, offset);
this._des2.encryptBlock(M, offset);
this._des1.decryptBlock(M, offset);
},
keySize: 192/32,
ivSize: 64/32,
blockSize: 64/32
});
/**
* Shortcut functions to the cipher's object interface.
*
* @example
*
* var ciphertext = CryptoJS.TripleDES.encrypt(message, key, cfg);
* var plaintext = CryptoJS.TripleDES.decrypt(ciphertext, key, cfg);
*/
C.TripleDES = BlockCipher._createHelper(TripleDES);
}());
return CryptoJS.TripleDES;
}));
},{"./cipher-core":41,"./core":42,"./enc-base64":43,"./evpkdf":45,"./md5":50}],73:[function(_dereq_,module,exports){
;(function (root, factory) {
if (typeof exports === "object") {
// CommonJS
module.exports = exports = factory(_dereq_("./core"));
}
else if (typeof define === "function" && define.amd) {
// AMD
define(["./core"], factory);
}
else {
// Global (browser)
factory(root.CryptoJS);
}
}(this, function (CryptoJS) {
(function (undefined) {
// Shortcuts
var C = CryptoJS;
var C_lib = C.lib;
var Base = C_lib.Base;
var X32WordArray = C_lib.WordArray;
/**
* x64 namespace.
*/
var C_x64 = C.x64 = {};
/**
* A 64-bit word.
*/
var X64Word = C_x64.Word = Base.extend({
/**
* Initializes a newly created 64-bit word.
*
* @param {number} high The high 32 bits.
* @param {number} low The low 32 bits.
*
* @example
*
* var x64Word = CryptoJS.x64.Word.create(0x00010203, 0x04050607);
*/
init: function (high, low) {
this.high = high;
this.low = low;
}
/**
* Bitwise NOTs this word.
*
* @return {X64Word} A new x64-Word object after negating.
*
* @example
*
* var negated = x64Word.not();
*/
// not: function () {
// var high = ~this.high;
// var low = ~this.low;
// return X64Word.create(high, low);
// },
/**
* Bitwise ANDs this word with the passed word.
*
* @param {X64Word} word The x64-Word to AND with this word.
*
* @return {X64Word} A new x64-Word object after ANDing.
*
* @example
*
* var anded = x64Word.and(anotherX64Word);
*/
// and: function (word) {
// var high = this.high & word.high;
// var low = this.low & word.low;
// return X64Word.create(high, low);
// },
/**
* Bitwise ORs this word with the passed word.
*
* @param {X64Word} word The x64-Word to OR with this word.
*
* @return {X64Word} A new x64-Word object after ORing.
*
* @example
*
* var ored = x64Word.or(anotherX64Word);
*/
// or: function (word) {
// var high = this.high | word.high;
// var low = this.low | word.low;
// return X64Word.create(high, low);
// },
/**
* Bitwise XORs this word with the passed word.
*
* @param {X64Word} word The x64-Word to XOR with this word.
*
* @return {X64Word} A new x64-Word object after XORing.
*
* @example
*
* var xored = x64Word.xor(anotherX64Word);
*/
// xor: function (word) {
// var high = this.high ^ word.high;
// var low = this.low ^ word.low;
// return X64Word.create(high, low);
// },
/**
* Shifts this word n bits to the left.
*
* @param {number} n The number of bits to shift.
*
* @return {X64Word} A new x64-Word object after shifting.
*
* @example
*
* var shifted = x64Word.shiftL(25);
*/
// shiftL: function (n) {
// if (n < 32) {
// var high = (this.high << n) | (this.low >>> (32 - n));
// var low = this.low << n;
// } else {
// var high = this.low << (n - 32);
// var low = 0;
// }
// return X64Word.create(high, low);
// },
/**
* Shifts this word n bits to the right.
*
* @param {number} n The number of bits to shift.
*
* @return {X64Word} A new x64-Word object after shifting.
*
* @example
*
* var shifted = x64Word.shiftR(7);
*/
// shiftR: function (n) {
// if (n < 32) {
// var low = (this.low >>> n) | (this.high << (32 - n));
// var high = this.high >>> n;
// } else {
// var low = this.high >>> (n - 32);
// var high = 0;
// }
// return X64Word.create(high, low);
// },
/**
* Rotates this word n bits to the left.
*
* @param {number} n The number of bits to rotate.
*
* @return {X64Word} A new x64-Word object after rotating.
*
* @example
*
* var rotated = x64Word.rotL(25);
*/
// rotL: function (n) {
// return this.shiftL(n).or(this.shiftR(64 - n));
// },
/**
* Rotates this word n bits to the right.
*
* @param {number} n The number of bits to rotate.
*
* @return {X64Word} A new x64-Word object after rotating.
*
* @example
*
* var rotated = x64Word.rotR(7);
*/
// rotR: function (n) {
// return this.shiftR(n).or(this.shiftL(64 - n));
// },
/**
* Adds this word with the passed word.
*
* @param {X64Word} word The x64-Word to add with this word.
*
* @return {X64Word} A new x64-Word object after adding.
*
* @example
*
* var added = x64Word.add(anotherX64Word);
*/
// add: function (word) {
// var low = (this.low + word.low) | 0;
// var carry = (low >>> 0) < (this.low >>> 0) ? 1 : 0;
// var high = (this.high + word.high + carry) | 0;
// return X64Word.create(high, low);
// }
});
/**
* An array of 64-bit words.
*
* @property {Array} words The array of CryptoJS.x64.Word objects.
* @property {number} sigBytes The number of significant bytes in this word array.
*/
var X64WordArray = C_x64.WordArray = Base.extend({
/**
* Initializes a newly created word array.
*
* @param {Array} words (Optional) An array of CryptoJS.x64.Word objects.
* @param {number} sigBytes (Optional) The number of significant bytes in the words.
*
* @example
*
* var wordArray = CryptoJS.x64.WordArray.create();
*
* var wordArray = CryptoJS.x64.WordArray.create([
* CryptoJS.x64.Word.create(0x00010203, 0x04050607),
* CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
* ]);
*
* var wordArray = CryptoJS.x64.WordArray.create([
* CryptoJS.x64.Word.create(0x00010203, 0x04050607),
* CryptoJS.x64.Word.create(0x18191a1b, 0x1c1d1e1f)
* ], 10);
*/
init: function (words, sigBytes) {
words = this.words = words || [];
if (sigBytes != undefined) {
this.sigBytes = sigBytes;
} else {
this.sigBytes = words.length * 8;
}
},
/**
* Converts this 64-bit word array to a 32-bit word array.
*
* @return {CryptoJS.lib.WordArray} This word array's data as a 32-bit word array.
*
* @example
*
* var x32WordArray = x64WordArray.toX32();
*/
toX32: function () {
// Shortcuts
var x64Words = this.words;
var x64WordsLength = x64Words.length;
// Convert
var x32Words = [];
for (var i = 0; i < x64WordsLength; i++) {
var x64Word = x64Words[i];
x32Words.push(x64Word.high);
x32Words.push(x64Word.low);
}
return X32WordArray.create(x32Words, this.sigBytes);
},
/**
* Creates a copy of this word array.
*
* @return {X64WordArray} The clone.
*
* @example
*
* var clone = x64WordArray.clone();
*/
clone: function () {
var clone = Base.clone.call(this);
// Clone "words" array
var words = clone.words = this.words.slice(0);
// Clone each X64Word object
var wordsLength = words.length;
for (var i = 0; i < wordsLength; i++) {
words[i] = words[i].clone();
}
return clone;
}
});
}());
return CryptoJS;
}));
},{"./core":42}],74:[function(_dereq_,module,exports){
// shim for using process in browser
var process = module.exports = {};
var queue = [];
var draining = false;
var currentQueue;
var queueIndex = -1;
function cleanUpNextTick() {
draining = false;
if (currentQueue.length) {
queue = currentQueue.concat(queue);
} else {
queueIndex = -1;
}
if (queue.length) {
drainQueue();
}
}
function drainQueue() {
if (draining) {
return;
}
var timeout = setTimeout(cleanUpNextTick);
draining = true;
var len = queue.length;
while(len) {
currentQueue = queue;
queue = [];
while (++queueIndex < len) {
if (currentQueue) {
currentQueue[queueIndex].run();
}
}
queueIndex = -1;
len = queue.length;
}
currentQueue = null;
draining = false;
clearTimeout(timeout);
}
process.nextTick = function (fun) {
var args = new Array(arguments.length - 1);
if (arguments.length > 1) {
for (var i = 1; i < arguments.length; i++) {
args[i - 1] = arguments[i];
}
}
queue.push(new Item(fun, args));
if (queue.length === 1 && !draining) {
setTimeout(drainQueue, 0);
}
};
// v8 likes predictible objects
function Item(fun, array) {
this.fun = fun;
this.array = array;
}
Item.prototype.run = function () {
this.fun.apply(null, this.array);
};
process.title = 'browser';
process.browser = true;
process.env = {};
process.argv = [];
process.version = ''; // empty string to avoid regexp issues
process.versions = {};
function noop() {}
process.on = noop;
process.addListener = noop;
process.once = noop;
process.off = noop;
process.removeListener = noop;
process.removeAllListeners = noop;
process.emit = noop;
process.binding = function (name) {
throw new Error('process.binding is not supported');
};
process.cwd = function () { return '/' };
process.chdir = function (dir) {
throw new Error('process.chdir is not supported');
};
process.umask = function() { return 0; };
},{}],75:[function(_dereq_,module,exports){
'use strict';
var asap = _dereq_('asap')
module.exports = Promise
function Promise(fn) {
if (typeof this !== 'object') throw new TypeError('Promises must be constructed via new')
if (typeof fn !== 'function') throw new TypeError('not a function')
var state = null
var value = null
var deferreds = []
var self = this
this.then = function(onFulfilled, onRejected) {
return new Promise(function(resolve, reject) {
handle(new Handler(onFulfilled, onRejected, resolve, reject))
})
}
function handle(deferred) {
if (state === null) {
deferreds.push(deferred)
return
}
asap(function() {
var cb = state ? deferred.onFulfilled : deferred.onRejected
if (cb === null) {
(state ? deferred.resolve : deferred.reject)(value)
return
}
var ret
try {
ret = cb(value)
}
catch (e) {
deferred.reject(e)
return
}
deferred.resolve(ret)
})
}
function resolve(newValue) {
try { //Promise Resolution Procedure: https://github.com/promises-aplus/promises-spec#the-promise-resolution-procedure
if (newValue === self) throw new TypeError('A promise cannot be resolved with itself.')
if (newValue && (typeof newValue === 'object' || typeof newValue === 'function')) {
var then = newValue.then
if (typeof then === 'function') {
doResolve(then.bind(newValue), resolve, reject)
return
}
}
state = true
value = newValue
finale()
} catch (e) { reject(e) }
}
function reject(newValue) {
state = false
value = newValue
finale()
}
function finale() {
for (var i = 0, len = deferreds.length; i < len; i++)
handle(deferreds[i])
deferreds = null
}
doResolve(fn, resolve, reject)
}
function Handler(onFulfilled, onRejected, resolve, reject){
this.onFulfilled = typeof onFulfilled === 'function' ? onFulfilled : null
this.onRejected = typeof onRejected === 'function' ? onRejected : null
this.resolve = resolve
this.reject = reject
}
/**
* Take a potentially misbehaving resolver function and make sure
* onFulfilled and onRejected are only called once.
*
* Makes no guarantees about asynchrony.
*/
function doResolve(fn, onFulfilled, onRejected) {
var done = false;
try {
fn(function (value) {
if (done) return
done = true
onFulfilled(value)
}, function (reason) {
if (done) return
done = true
onRejected(reason)
})
} catch (ex) {
if (done) return
done = true
onRejected(ex)
}
}
},{"asap":77}],76:[function(_dereq_,module,exports){
'use strict';
//This file contains then/promise specific extensions to the core promise API
var Promise = _dereq_('./core.js')
var asap = _dereq_('asap')
module.exports = Promise
/* Static Functions */
function ValuePromise(value) {
this.then = function (onFulfilled) {
if (typeof onFulfilled !== 'function') return this
return new Promise(function (resolve, reject) {
asap(function () {
try {
resolve(onFulfilled(value))
} catch (ex) {
reject(ex);
}
})
})
}
}
ValuePromise.prototype = Object.create(Promise.prototype)
var TRUE = new ValuePromise(true)
var FALSE = new ValuePromise(false)
var NULL = new ValuePromise(null)
var UNDEFINED = new ValuePromise(undefined)
var ZERO = new ValuePromise(0)
var EMPTYSTRING = new ValuePromise('')
Promise.resolve = function (value) {
if (value instanceof Promise) return value
if (value === null) return NULL
if (value === undefined) return UNDEFINED
if (value === true) return TRUE
if (value === false) return FALSE
if (value === 0) return ZERO
if (value === '') return EMPTYSTRING
if (typeof value === 'object' || typeof value === 'function') {
try {
var then = value.then
if (typeof then === 'function') {
return new Promise(then.bind(value))
}
} catch (ex) {
return new Promise(function (resolve, reject) {
reject(ex)
})
}
}
return new ValuePromise(value)
}
Promise.from = Promise.cast = function (value) {
var err = new Error('Promise.from and Promise.cast are deprecated, use Promise.resolve instead')
err.name = 'Warning'
console.warn(err.stack)
return Promise.resolve(value)
}
Promise.denodeify = function (fn, argumentCount) {
argumentCount = argumentCount || Infinity
return function () {
var self = this
var args = Array.prototype.slice.call(arguments)
return new Promise(function (resolve, reject) {
while (args.length && args.length > argumentCount) {
args.pop()
}
args.push(function (err, res) {
if (err) reject(err)
else resolve(res)
})
fn.apply(self, args)
})
}
}
Promise.nodeify = function (fn) {
return function () {
var args = Array.prototype.slice.call(arguments)
var callback = typeof args[args.length - 1] === 'function' ? args.pop() : null
try {
return fn.apply(this, arguments).nodeify(callback)
} catch (ex) {
if (callback === null || typeof callback == 'undefined') {
return new Promise(function (resolve, reject) { reject(ex) })
} else {
asap(function () {
callback(ex)
})
}
}
}
}
Promise.all = function () {
var calledWithArray = arguments.length === 1 && Array.isArray(arguments[0])
var args = Array.prototype.slice.call(calledWithArray ? arguments[0] : arguments)
if (!calledWithArray) {
var err = new Error('Promise.all should be called with a single array, calling it with multiple arguments is deprecated')
err.name = 'Warning'
console.warn(err.stack)
}
return new Promise(function (resolve, reject) {
if (args.length === 0) return resolve([])
var remaining = args.length
function res(i, val) {
try {
if (val && (typeof val === 'object' || typeof val === 'function')) {
var then = val.then
if (typeof then === 'function') {
then.call(val, function (val) { res(i, val) }, reject)
return
}
}
args[i] = val
if (--remaining === 0) {
resolve(args);
}
} catch (ex) {
reject(ex)
}
}
for (var i = 0; i < args.length; i++) {
res(i, args[i])
}
})
}
Promise.reject = function (value) {
return new Promise(function (resolve, reject) {
reject(value);
});
}
Promise.race = function (values) {
return new Promise(function (resolve, reject) {
values.forEach(function(value){
Promise.resolve(value).then(resolve, reject);
})
});
}
/* Prototype Methods */
Promise.prototype.done = function (onFulfilled, onRejected) {
var self = arguments.length ? this.then.apply(this, arguments) : this
self.then(null, function (err) {
asap(function () {
throw err
})
})
}
Promise.prototype.nodeify = function (callback) {
if (typeof callback != 'function') return this
this.then(function (value) {
asap(function () {
callback(null, value)
})
}, function (err) {
asap(function () {
callback(err)
})
})
}
Promise.prototype['catch'] = function (onRejected) {
return this.then(null, onRejected);
}
},{"./core.js":75,"asap":77}],77:[function(_dereq_,module,exports){
(function (process){
// Use the fastest possible means to execute a task in a future turn
// of the event loop.
// linked list of tasks (single, with head node)
var head = {task: void 0, next: null};
var tail = head;
var flushing = false;
var requestFlush = void 0;
var isNodeJS = false;
function flush() {
/* jshint loopfunc: true */
while (head.next) {
head = head.next;
var task = head.task;
head.task = void 0;
var domain = head.domain;
if (domain) {
head.domain = void 0;
domain.enter();
}
try {
task();
} catch (e) {
if (isNodeJS) {
// In node, uncaught exceptions are considered fatal errors.
// Re-throw them synchronously to interrupt flushing!
// Ensure continuation if the uncaught exception is suppressed
// listening "uncaughtException" events (as domains does).
// Continue in next event to avoid tick recursion.
if (domain) {
domain.exit();
}
setTimeout(flush, 0);
if (domain) {
domain.enter();
}
throw e;
} else {
// In browsers, uncaught exceptions are not fatal.
// Re-throw them asynchronously to avoid slow-downs.
setTimeout(function() {
throw e;
}, 0);
}
}
if (domain) {
domain.exit();
}
}
flushing = false;
}
if (typeof process !== "undefined" && process.nextTick) {
// Node.js before 0.9. Note that some fake-Node environments, like the
// Mocha test runner, introduce a `process` global without a `nextTick`.
isNodeJS = true;
requestFlush = function () {
process.nextTick(flush);
};
} else if (typeof setImmediate === "function") {
// In IE10, Node.js 0.9+, or https://github.com/NobleJS/setImmediate
if (typeof window !== "undefined") {
requestFlush = setImmediate.bind(window, flush);
} else {
requestFlush = function () {
setImmediate(flush);
};
}
} else if (typeof MessageChannel !== "undefined") {
// modern browsers
// http://www.nonblocking.io/2011/06/windownexttick.html
var channel = new MessageChannel();
channel.port1.onmessage = flush;
requestFlush = function () {
channel.port2.postMessage(0);
};
} else {
// old browsers
requestFlush = function () {
setTimeout(flush, 0);
};
}
function asap(task) {
tail = tail.next = {
task: task,
domain: isNodeJS && process.domain,
next: null
};
if (!flushing) {
flushing = true;
requestFlush();
}
};
module.exports = asap;
}).call(this,_dereq_('_process'))
},{"_process":74}],78:[function(_dereq_,module,exports){
// Some code originally from async_storage.js in
// [Gaia](https://github.com/mozilla-b2g/gaia).
(function() {
'use strict';
// Originally found in https://github.com/mozilla-b2g/gaia/blob/e8f624e4cc9ea945727278039b3bc9bcb9f8667a/shared/js/async_storage.js
// Promises!
var Promise = (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') ?
_dereq_('promise') : this.Promise;
// Initialize IndexedDB; fall back to vendor-prefixed versions if needed.
var indexedDB = indexedDB || this.indexedDB || this.webkitIndexedDB ||
this.mozIndexedDB || this.OIndexedDB ||
this.msIndexedDB;
// If IndexedDB isn't available, we get outta here!
if (!indexedDB) {
return;
}
var DETECT_BLOB_SUPPORT_STORE = 'local-forage-detect-blob-support';
var supportsBlobs;
// Abstracts constructing a Blob object, so it also works in older
// browsers that don't support the native Blob constructor. (i.e.
// old QtWebKit versions, at least).
function _createBlob(parts, properties) {
parts = parts || [];
properties = properties || {};
try {
return new Blob(parts, properties);
} catch (e) {
if (e.name !== 'TypeError') {
throw e;
}
var BlobBuilder = window.BlobBuilder ||
window.MSBlobBuilder ||
window.MozBlobBuilder ||
window.WebKitBlobBuilder;
var builder = new BlobBuilder();
for (var i = 0; i < parts.length; i += 1) {
builder.append(parts[i]);
}
return builder.getBlob(properties.type);
}
}
// Transform a binary string to an array buffer, because otherwise
// weird stuff happens when you try to work with the binary string directly.
// It is known.
// From http://stackoverflow.com/questions/14967647/ (continues on next line)
// encode-decode-image-with-base64-breaks-image (2013-04-21)
function _binStringToArrayBuffer(bin) {
var length = bin.length;
var buf = new ArrayBuffer(length);
var arr = new Uint8Array(buf);
for (var i = 0; i < length; i++) {
arr[i] = bin.charCodeAt(i);
}
return buf;
}
// Fetch a blob using ajax. This reveals bugs in Chrome < 43.
// For details on all this junk:
// https://github.com/nolanlawson/state-of-binary-data-in-the-browser#readme
function _blobAjax(url) {
return new Promise(function(resolve, reject) {
var xhr = new XMLHttpRequest();
xhr.open('GET', url);
xhr.withCredentials = true;
xhr.responseType = 'arraybuffer';
xhr.onreadystatechange = function() {
if (xhr.readyState !== 4) {
return;
}
if (xhr.status === 200) {
return resolve({
response: xhr.response,
type: xhr.getResponseHeader('Content-Type')
});
}
reject({status: xhr.status, response: xhr.response});
};
xhr.send();
});
}
//
// Detect blob support. Chrome didn't support it until version 38.
// In version 37 they had a broken version where PNGs (and possibly
// other binary types) aren't stored correctly, because when you fetch
// them, the content type is always null.
//
// Furthermore, they have some outstanding bugs where blobs occasionally
// are read by FileReader as null, or by ajax as 404s.
//
// Sadly we use the 404 bug to detect the FileReader bug, so if they
// get fixed independently and released in different versions of Chrome,
// then the bug could come back. So it's worthwhile to watch these issues:
// 404 bug: https://code.google.com/p/chromium/issues/detail?id=447916
// FileReader bug: https://code.google.com/p/chromium/issues/detail?id=447836
//
function _checkBlobSupportWithoutCaching(idb) {
return new Promise(function(resolve, reject) {
var blob = _createBlob([''], {type: 'image/png'});
var txn = idb.transaction([DETECT_BLOB_SUPPORT_STORE], 'readwrite');
txn.objectStore(DETECT_BLOB_SUPPORT_STORE).put(blob, 'key');
txn.oncomplete = function() {
// have to do it in a separate transaction, else the correct
// content type is always returned
var blobTxn = idb.transaction([DETECT_BLOB_SUPPORT_STORE],
'readwrite');
var getBlobReq = blobTxn.objectStore(
DETECT_BLOB_SUPPORT_STORE).get('key');
getBlobReq.onerror = reject;
getBlobReq.onsuccess = function(e) {
var storedBlob = e.target.result;
var url = URL.createObjectURL(storedBlob);
_blobAjax(url).then(function(res) {
resolve(!!(res && res.type === 'image/png'));
}, function() {
resolve(false);
}).then(function() {
URL.revokeObjectURL(url);
});
};
};
})['catch'](function() {
return false; // error, so assume unsupported
});
}
function _checkBlobSupport(idb) {
if (typeof supportsBlobs === 'boolean') {
return Promise.resolve(supportsBlobs);
}
return _checkBlobSupportWithoutCaching(idb).then(function(value) {
supportsBlobs = value;
return supportsBlobs;
});
}
// encode a blob for indexeddb engines that don't support blobs
function _encodeBlob(blob) {
return new Promise(function(resolve, reject) {
var reader = new FileReader();
reader.onerror = reject;
reader.onloadend = function(e) {
var base64 = btoa(e.target.result || '');
resolve({
__local_forage_encoded_blob: true,
data: base64,
type: blob.type
});
};
reader.readAsBinaryString(blob);
});
}
// decode an encoded blob
function _decodeBlob(encodedBlob) {
var arrayBuff = _binStringToArrayBuffer(atob(encodedBlob.data));
return _createBlob([arrayBuff], { type: encodedBlob.type});
}
// is this one of our fancy encoded blobs?
function _isEncodedBlob(value) {
return value && value.__local_forage_encoded_blob;
}
// Open the IndexedDB database (automatically creates one if one didn't
// previously exist), using any options set in the config.
function _initStorage(options) {
var self = this;
var dbInfo = {
db: null
};
if (options) {
for (var i in options) {
dbInfo[i] = options[i];
}
}
return new Promise(function(resolve, reject) {
var openreq = indexedDB.open(dbInfo.name, dbInfo.version);
openreq.onerror = function() {
reject(openreq.error);
};
openreq.onupgradeneeded = function(e) {
// First time setup: create an empty object store
openreq.result.createObjectStore(dbInfo.storeName);
if (e.oldVersion <= 1) {
// added when support for blob shims was added
openreq.result.createObjectStore(DETECT_BLOB_SUPPORT_STORE);
}
};
openreq.onsuccess = function() {
dbInfo.db = openreq.result;
self._dbInfo = dbInfo;
resolve();
};
});
}
function getItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly')
.objectStore(dbInfo.storeName);
var req = store.get(key);
req.onsuccess = function() {
var value = req.result;
if (value === undefined) {
value = null;
}
if (_isEncodedBlob(value)) {
value = _decodeBlob(value);
}
resolve(value);
};
req.onerror = function() {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
// Iterate over all items stored in database.
function iterate(iterator, callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly')
.objectStore(dbInfo.storeName);
var req = store.openCursor();
var iterationNumber = 1;
req.onsuccess = function() {
var cursor = req.result;
if (cursor) {
var value = cursor.value;
if (_isEncodedBlob(value)) {
value = _decodeBlob(value);
}
var result = iterator(value, cursor.key, iterationNumber++);
if (result !== void(0)) {
resolve(result);
} else {
cursor['continue']();
}
} else {
resolve();
}
};
req.onerror = function() {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function setItem(key, value, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function(resolve, reject) {
var dbInfo;
self.ready().then(function() {
dbInfo = self._dbInfo;
return _checkBlobSupport(dbInfo.db);
}).then(function(blobSupport) {
if (!blobSupport && value instanceof Blob) {
return _encodeBlob(value);
}
return value;
}).then(function(value) {
var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite');
var store = transaction.objectStore(dbInfo.storeName);
// The reason we don't _save_ null is because IE 10 does
// not support saving the `null` type in IndexedDB. How
// ironic, given the bug below!
// See: https://github.com/mozilla/localForage/issues/161
if (value === null) {
value = undefined;
}
var req = store.put(value, key);
transaction.oncomplete = function() {
// Cast to undefined so the value passed to
// callback/promise is the same as what one would get out
// of `getItem()` later. This leads to some weirdness
// (setItem('foo', undefined) will return `null`), but
// it's not my fault localStorage is our baseline and that
// it's weird.
if (value === undefined) {
value = null;
}
resolve(value);
};
transaction.onabort = transaction.onerror = function() {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function removeItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite');
var store = transaction.objectStore(dbInfo.storeName);
// We use a Grunt task to make this safe for IE and some
// versions of Android (including those used by Cordova).
// Normally IE won't like `['delete']()` and will insist on
// using `['delete']()`, but we have a build step that
// fixes this for us now.
var req = store['delete'](key);
transaction.oncomplete = function() {
resolve();
};
transaction.onerror = function() {
reject(req.error);
};
// The request will be also be aborted if we've exceeded our storage
// space.
transaction.onabort = function() {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function clear(callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
var transaction = dbInfo.db.transaction(dbInfo.storeName, 'readwrite');
var store = transaction.objectStore(dbInfo.storeName);
var req = store.clear();
transaction.oncomplete = function() {
resolve();
};
transaction.onabort = transaction.onerror = function() {
var err = req.error ? req.error : req.transaction.error;
reject(err);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function length(callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly')
.objectStore(dbInfo.storeName);
var req = store.count();
req.onsuccess = function() {
resolve(req.result);
};
req.onerror = function() {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function key(n, callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
if (n < 0) {
resolve(null);
return;
}
self.ready().then(function() {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly')
.objectStore(dbInfo.storeName);
var advanced = false;
var req = store.openCursor();
req.onsuccess = function() {
var cursor = req.result;
if (!cursor) {
// this means there weren't enough keys
resolve(null);
return;
}
if (n === 0) {
// We have the first key, return it if that's what they
// wanted.
resolve(cursor.key);
} else {
if (!advanced) {
// Otherwise, ask the cursor to skip ahead n
// records.
advanced = true;
cursor.advance(n);
} else {
// When we get here, we've got the nth key.
resolve(cursor.key);
}
}
};
req.onerror = function() {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function keys(callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
var store = dbInfo.db.transaction(dbInfo.storeName, 'readonly')
.objectStore(dbInfo.storeName);
var req = store.openCursor();
var keys = [];
req.onsuccess = function() {
var cursor = req.result;
if (!cursor) {
resolve(keys);
return;
}
keys.push(cursor.key);
cursor['continue']();
};
req.onerror = function() {
reject(req.error);
};
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function executeCallback(promise, callback) {
if (callback) {
promise.then(function(result) {
callback(null, result);
}, function(error) {
callback(error);
});
}
}
var asyncStorage = {
_driver: 'asyncStorage',
_initStorage: _initStorage,
iterate: iterate,
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
length: length,
key: key,
keys: keys
};
if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') {
module.exports = asyncStorage;
} else if (typeof define === 'function' && define.amd) {
define('asyncStorage', function() {
return asyncStorage;
});
} else {
this.asyncStorage = asyncStorage;
}
}).call(window);
},{"promise":76}],79:[function(_dereq_,module,exports){
// If IndexedDB isn't available, we'll fall back to localStorage.
// Note that this will have considerable performance and storage
// side-effects (all data will be serialized on save and only data that
// can be converted to a string via `JSON.stringify()` will be saved).
(function() {
'use strict';
// Promises!
var Promise = (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') ?
_dereq_('promise') : this.Promise;
var globalObject = this;
var serializer = null;
var localStorage = null;
// If the app is running inside a Google Chrome packaged webapp, or some
// other context where localStorage isn't available, we don't use
// localStorage. This feature detection is preferred over the old
// `if (window.chrome && window.chrome.runtime)` code.
// See: https://github.com/mozilla/localForage/issues/68
try {
// If localStorage isn't available, we get outta here!
// This should be inside a try catch
if (!this.localStorage || !('setItem' in this.localStorage)) {
return;
}
// Initialize localStorage and create a variable to use throughout
// the code.
localStorage = this.localStorage;
} catch (e) {
return;
}
var ModuleType = {
DEFINE: 1,
EXPORT: 2,
WINDOW: 3
};
// Attaching to window (i.e. no module loader) is the assumed,
// simple default.
var moduleType = ModuleType.WINDOW;
// Find out what kind of module setup we have; if none, we'll just attach
// localForage to the main window.
if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') {
moduleType = ModuleType.EXPORT;
} else if (typeof define === 'function' && define.amd) {
moduleType = ModuleType.DEFINE;
}
// Config the localStorage backend, using options set in the config.
function _initStorage(options) {
var self = this;
var dbInfo = {};
if (options) {
for (var i in options) {
dbInfo[i] = options[i];
}
}
dbInfo.keyPrefix = dbInfo.name + '/';
self._dbInfo = dbInfo;
var serializerPromise = new Promise(function(resolve/*, reject*/) {
// We allow localForage to be declared as a module or as a
// library available without AMD/require.js.
if (moduleType === ModuleType.DEFINE) {
_dereq_(['localforageSerializer'], resolve);
} else if (moduleType === ModuleType.EXPORT) {
// Making it browserify friendly
resolve(_dereq_('./../utils/serializer'));
} else {
resolve(globalObject.localforageSerializer);
}
});
return serializerPromise.then(function(lib) {
serializer = lib;
return Promise.resolve();
});
}
// Remove all keys from the datastore, effectively destroying all data in
// the app's key/value store!
function clear(callback) {
var self = this;
var promise = self.ready().then(function() {
var keyPrefix = self._dbInfo.keyPrefix;
for (var i = localStorage.length - 1; i >= 0; i--) {
var key = localStorage.key(i);
if (key.indexOf(keyPrefix) === 0) {
localStorage.removeItem(key);
}
}
});
executeCallback(promise, callback);
return promise;
}
// Retrieve an item from the store. Unlike the original async_storage
// library in Gaia, we don't modify return values at all. If a key's value
// is `undefined`, we pass that value to the callback function.
function getItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = self.ready().then(function() {
var dbInfo = self._dbInfo;
var result = localStorage.getItem(dbInfo.keyPrefix + key);
// If a result was found, parse it from the serialized
// string into a JS object. If result isn't truthy, the key
// is likely undefined and we'll pass it straight to the
// callback.
if (result) {
result = serializer.deserialize(result);
}
return result;
});
executeCallback(promise, callback);
return promise;
}
// Iterate over all items in the store.
function iterate(iterator, callback) {
var self = this;
var promise = self.ready().then(function() {
var keyPrefix = self._dbInfo.keyPrefix;
var keyPrefixLength = keyPrefix.length;
var length = localStorage.length;
for (var i = 0; i < length; i++) {
var key = localStorage.key(i);
var value = localStorage.getItem(key);
// If a result was found, parse it from the serialized
// string into a JS object. If result isn't truthy, the
// key is likely undefined and we'll pass it straight
// to the iterator.
if (value) {
value = serializer.deserialize(value);
}
value = iterator(value, key.substring(keyPrefixLength), i + 1);
if (value !== void(0)) {
return value;
}
}
});
executeCallback(promise, callback);
return promise;
}
// Same as localStorage's key() method, except takes a callback.
function key(n, callback) {
var self = this;
var promise = self.ready().then(function() {
var dbInfo = self._dbInfo;
var result;
try {
result = localStorage.key(n);
} catch (error) {
result = null;
}
// Remove the prefix from the key, if a key is found.
if (result) {
result = result.substring(dbInfo.keyPrefix.length);
}
return result;
});
executeCallback(promise, callback);
return promise;
}
function keys(callback) {
var self = this;
var promise = self.ready().then(function() {
var dbInfo = self._dbInfo;
var length = localStorage.length;
var keys = [];
for (var i = 0; i < length; i++) {
if (localStorage.key(i).indexOf(dbInfo.keyPrefix) === 0) {
keys.push(localStorage.key(i).substring(dbInfo.keyPrefix.length));
}
}
return keys;
});
executeCallback(promise, callback);
return promise;
}
// Supply the number of keys in the datastore to the callback function.
function length(callback) {
var self = this;
var promise = self.keys().then(function(keys) {
return keys.length;
});
executeCallback(promise, callback);
return promise;
}
// Remove an item from the store, nice and simple.
function removeItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = self.ready().then(function() {
var dbInfo = self._dbInfo;
localStorage.removeItem(dbInfo.keyPrefix + key);
});
executeCallback(promise, callback);
return promise;
}
// Set a key's value and run an optional callback once the value is set.
// Unlike Gaia's implementation, the callback function is passed the value,
// in case you want to operate on that value only after you're sure it
// saved, or something like that.
function setItem(key, value, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = self.ready().then(function() {
// Convert undefined values to null.
// https://github.com/mozilla/localForage/pull/42
if (value === undefined) {
value = null;
}
// Save the original value to pass to the callback.
var originalValue = value;
return new Promise(function(resolve, reject) {
serializer.serialize(value, function(value, error) {
if (error) {
reject(error);
} else {
try {
var dbInfo = self._dbInfo;
localStorage.setItem(dbInfo.keyPrefix + key, value);
resolve(originalValue);
} catch (e) {
// localStorage capacity exceeded.
// TODO: Make this a specific error/event.
if (e.name === 'QuotaExceededError' ||
e.name === 'NS_ERROR_DOM_QUOTA_REACHED') {
reject(e);
}
reject(e);
}
}
});
});
});
executeCallback(promise, callback);
return promise;
}
function executeCallback(promise, callback) {
if (callback) {
promise.then(function(result) {
callback(null, result);
}, function(error) {
callback(error);
});
}
}
var localStorageWrapper = {
_driver: 'localStorageWrapper',
_initStorage: _initStorage,
// Default API, from Gaia/localStorage.
iterate: iterate,
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
length: length,
key: key,
keys: keys
};
if (moduleType === ModuleType.EXPORT) {
module.exports = localStorageWrapper;
} else if (moduleType === ModuleType.DEFINE) {
define('localStorageWrapper', function() {
return localStorageWrapper;
});
} else {
this.localStorageWrapper = localStorageWrapper;
}
}).call(window);
},{"./../utils/serializer":82,"promise":76}],80:[function(_dereq_,module,exports){
/*
* Includes code from:
*
* base64-arraybuffer
* https://github.com/niklasvh/base64-arraybuffer
*
* Copyright (c) 2012 Niklas von Hertzen
* Licensed under the MIT license.
*/
(function() {
'use strict';
// Promises!
var Promise = (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') ?
_dereq_('promise') : this.Promise;
var globalObject = this;
var serializer = null;
var openDatabase = this.openDatabase;
// If WebSQL methods aren't available, we can stop now.
if (!openDatabase) {
return;
}
var ModuleType = {
DEFINE: 1,
EXPORT: 2,
WINDOW: 3
};
// Attaching to window (i.e. no module loader) is the assumed,
// simple default.
var moduleType = ModuleType.WINDOW;
// Find out what kind of module setup we have; if none, we'll just attach
// localForage to the main window.
if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') {
moduleType = ModuleType.EXPORT;
} else if (typeof define === 'function' && define.amd) {
moduleType = ModuleType.DEFINE;
}
// Open the WebSQL database (automatically creates one if one didn't
// previously exist), using any options set in the config.
function _initStorage(options) {
var self = this;
var dbInfo = {
db: null
};
if (options) {
for (var i in options) {
dbInfo[i] = typeof(options[i]) !== 'string' ?
options[i].toString() : options[i];
}
}
var serializerPromise = new Promise(function(resolve/*, reject*/) {
// We allow localForage to be declared as a module or as a
// library available without AMD/require.js.
if (moduleType === ModuleType.DEFINE) {
_dereq_(['localforageSerializer'], resolve);
} else if (moduleType === ModuleType.EXPORT) {
// Making it browserify friendly
resolve(_dereq_('./../utils/serializer'));
} else {
resolve(globalObject.localforageSerializer);
}
});
var dbInfoPromise = new Promise(function(resolve, reject) {
// Open the database; the openDatabase API will automatically
// create it for us if it doesn't exist.
try {
dbInfo.db = openDatabase(dbInfo.name, String(dbInfo.version),
dbInfo.description, dbInfo.size);
} catch (e) {
return self.setDriver(self.LOCALSTORAGE).then(function() {
return self._initStorage(options);
}).then(resolve)['catch'](reject);
}
// Create our key/value table if it doesn't exist.
dbInfo.db.transaction(function(t) {
t.executeSql('CREATE TABLE IF NOT EXISTS ' + dbInfo.storeName +
' (id INTEGER PRIMARY KEY, key unique, value)', [],
function() {
self._dbInfo = dbInfo;
resolve();
}, function(t, error) {
reject(error);
});
});
});
return serializerPromise.then(function(lib) {
serializer = lib;
return dbInfoPromise;
});
}
function getItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('SELECT * FROM ' + dbInfo.storeName +
' WHERE key = ? LIMIT 1', [key],
function(t, results) {
var result = results.rows.length ?
results.rows.item(0).value : null;
// Check to see if this is serialized content we need to
// unpack.
if (result) {
result = serializer.deserialize(result);
}
resolve(result);
}, function(t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function iterate(iterator, callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('SELECT * FROM ' + dbInfo.storeName, [],
function(t, results) {
var rows = results.rows;
var length = rows.length;
for (var i = 0; i < length; i++) {
var item = rows.item(i);
var result = item.value;
// Check to see if this is serialized content
// we need to unpack.
if (result) {
result = serializer.deserialize(result);
}
result = iterator(result, item.key, i + 1);
// void(0) prevents problems with redefinition
// of `undefined`.
if (result !== void(0)) {
resolve(result);
return;
}
}
resolve();
}, function(t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function setItem(key, value, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
// The localStorage API doesn't return undefined values in an
// "expected" way, so undefined is always cast to null in all
// drivers. See: https://github.com/mozilla/localForage/pull/42
if (value === undefined) {
value = null;
}
// Save the original value to pass to the callback.
var originalValue = value;
serializer.serialize(value, function(value, error) {
if (error) {
reject(error);
} else {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('INSERT OR REPLACE INTO ' +
dbInfo.storeName +
' (key, value) VALUES (?, ?)',
[key, value], function() {
resolve(originalValue);
}, function(t, error) {
reject(error);
});
}, function(sqlError) {
// The transaction failed; check
// to see if it's a quota error.
if (sqlError.code === sqlError.QUOTA_ERR) {
// We reject the callback outright for now, but
// it's worth trying to re-run the transaction.
// Even if the user accepts the prompt to use
// more storage on Safari, this error will
// be called.
//
// TODO: Try to re-run the transaction.
reject(sqlError);
}
});
}
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function removeItem(key, callback) {
var self = this;
// Cast the key to a string, as that's all we can set as a key.
if (typeof key !== 'string') {
window.console.warn(key +
' used as a key, but it is not a string.');
key = String(key);
}
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('DELETE FROM ' + dbInfo.storeName +
' WHERE key = ?', [key],
function() {
resolve();
}, function(t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
// Deletes every item in the table.
// TODO: Find out if this resets the AUTO_INCREMENT number.
function clear(callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('DELETE FROM ' + dbInfo.storeName, [],
function() {
resolve();
}, function(t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
// Does a simple `COUNT(key)` to get the number of items stored in
// localForage.
function length(callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
// Ahhh, SQL makes this one soooooo easy.
t.executeSql('SELECT COUNT(key) as c FROM ' +
dbInfo.storeName, [], function(t, results) {
var result = results.rows.item(0).c;
resolve(result);
}, function(t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
// Return the key located at key index X; essentially gets the key from a
// `WHERE id = ?`. This is the most efficient way I can think to implement
// this rarely-used (in my experience) part of the API, but it can seem
// inconsistent, because we do `INSERT OR REPLACE INTO` on `setItem()`, so
// the ID of each key will change every time it's updated. Perhaps a stored
// procedure for the `setItem()` SQL would solve this problem?
// TODO: Don't change ID on `setItem()`.
function key(n, callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('SELECT key FROM ' + dbInfo.storeName +
' WHERE id = ? LIMIT 1', [n + 1],
function(t, results) {
var result = results.rows.length ?
results.rows.item(0).key : null;
resolve(result);
}, function(t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function keys(callback) {
var self = this;
var promise = new Promise(function(resolve, reject) {
self.ready().then(function() {
var dbInfo = self._dbInfo;
dbInfo.db.transaction(function(t) {
t.executeSql('SELECT key FROM ' + dbInfo.storeName, [],
function(t, results) {
var keys = [];
for (var i = 0; i < results.rows.length; i++) {
keys.push(results.rows.item(i).key);
}
resolve(keys);
}, function(t, error) {
reject(error);
});
});
})['catch'](reject);
});
executeCallback(promise, callback);
return promise;
}
function executeCallback(promise, callback) {
if (callback) {
promise.then(function(result) {
callback(null, result);
}, function(error) {
callback(error);
});
}
}
var webSQLStorage = {
_driver: 'webSQLStorage',
_initStorage: _initStorage,
iterate: iterate,
getItem: getItem,
setItem: setItem,
removeItem: removeItem,
clear: clear,
length: length,
key: key,
keys: keys
};
if (moduleType === ModuleType.DEFINE) {
define('webSQLStorage', function() {
return webSQLStorage;
});
} else if (moduleType === ModuleType.EXPORT) {
module.exports = webSQLStorage;
} else {
this.webSQLStorage = webSQLStorage;
}
}).call(window);
},{"./../utils/serializer":82,"promise":76}],81:[function(_dereq_,module,exports){
(function() {
'use strict';
// Promises!
var Promise = (typeof module !== 'undefined' && module.exports &&
typeof _dereq_ !== 'undefined') ?
_dereq_('promise') : this.Promise;
// Custom drivers are stored here when `defineDriver()` is called.
// They are shared across all instances of localForage.
var CustomDrivers = {};
var DriverType = {
INDEXEDDB: 'asyncStorage',
LOCALSTORAGE: 'localStorageWrapper',
WEBSQL: 'webSQLStorage'
};
var DefaultDriverOrder = [
DriverType.INDEXEDDB,
DriverType.WEBSQL,
DriverType.LOCALSTORAGE
];
var LibraryMethods = [
'clear',
'getItem',
'iterate',
'key',
'keys',
'length',
'removeItem',
'setItem'
];
var ModuleType = {
DEFINE: 1,
EXPORT: 2,
WINDOW: 3
};
var DefaultConfig = {
description: '',
driver: DefaultDriverOrder.slice(),
name: 'localforage',
// Default DB size is _JUST UNDER_ 5MB, as it's the highest size
// we can use without a prompt.
size: 4980736,
storeName: 'keyvaluepairs',
version: 1.0
};
// Attaching to window (i.e. no module loader) is the assumed,
// simple default.
var moduleType = ModuleType.WINDOW;
// Find out what kind of module setup we have; if none, we'll just attach
// localForage to the main window.
if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') {
moduleType = ModuleType.EXPORT;
} else if (typeof define === 'function' && define.amd) {
moduleType = ModuleType.DEFINE;
}
// Check to see if IndexedDB is available and if it is the latest
// implementation; it's our preferred backend library. We use "_spec_test"
// as the name of the database because it's not the one we'll operate on,
// but it's useful to make sure its using the right spec.
// See: https://github.com/mozilla/localForage/issues/128
var driverSupport = (function(self) {
// Initialize IndexedDB; fall back to vendor-prefixed versions
// if needed.
var indexedDB = indexedDB || self.indexedDB || self.webkitIndexedDB ||
self.mozIndexedDB || self.OIndexedDB ||
self.msIndexedDB;
var result = {};
result[DriverType.WEBSQL] = !!self.openDatabase;
result[DriverType.INDEXEDDB] = !!(function() {
// We mimic PouchDB here; just UA test for Safari (which, as of
// iOS 8/Yosemite, doesn't properly support IndexedDB).
// IndexedDB support is broken and different from Blink's.
// This is faster than the test case (and it's sync), so we just
// do this. *SIGH*
// http://bl.ocks.org/nolanlawson/raw/c83e9039edf2278047e9/
//
// We test for openDatabase because IE Mobile identifies itself
// as Safari. Oh the lulz...
if (typeof self.openDatabase !== 'undefined' && self.navigator &&
self.navigator.userAgent &&
/Safari/.test(self.navigator.userAgent) &&
!/Chrome/.test(self.navigator.userAgent)) {
return false;
}
try {
return indexedDB &&
typeof indexedDB.open === 'function' &&
// Some Samsung/HTC Android 4.0-4.3 devices
// have older IndexedDB specs; if this isn't available
// their IndexedDB is too old for us to use.
// (Replaces the onupgradeneeded test.)
typeof self.IDBKeyRange !== 'undefined';
} catch (e) {
return false;
}
})();
result[DriverType.LOCALSTORAGE] = !!(function() {
try {
return (self.localStorage &&
('setItem' in self.localStorage) &&
(self.localStorage.setItem));
} catch (e) {
return false;
}
})();
return result;
})(this);
var isArray = Array.isArray || function(arg) {
return Object.prototype.toString.call(arg) === '[object Array]';
};
function callWhenReady(localForageInstance, libraryMethod) {
localForageInstance[libraryMethod] = function() {
var _args = arguments;
return localForageInstance.ready().then(function() {
return localForageInstance[libraryMethod].apply(localForageInstance, _args);
});
};
}
function extend() {
for (var i = 1; i < arguments.length; i++) {
var arg = arguments[i];
if (arg) {
for (var key in arg) {
if (arg.hasOwnProperty(key)) {
if (isArray(arg[key])) {
arguments[0][key] = arg[key].slice();
} else {
arguments[0][key] = arg[key];
}
}
}
}
}
return arguments[0];
}
function isLibraryDriver(driverName) {
for (var driver in DriverType) {
if (DriverType.hasOwnProperty(driver) &&
DriverType[driver] === driverName) {
return true;
}
}
return false;
}
var globalObject = this;
function LocalForage(options) {
this._config = extend({}, DefaultConfig, options);
this._driverSet = null;
this._ready = false;
this._dbInfo = null;
// Add a stub for each driver API method that delays the call to the
// corresponding driver method until localForage is ready. These stubs
// will be replaced by the driver methods as soon as the driver is
// loaded, so there is no performance impact.
for (var i = 0; i < LibraryMethods.length; i++) {
callWhenReady(this, LibraryMethods[i]);
}
this.setDriver(this._config.driver);
}
LocalForage.prototype.INDEXEDDB = DriverType.INDEXEDDB;
LocalForage.prototype.LOCALSTORAGE = DriverType.LOCALSTORAGE;
LocalForage.prototype.WEBSQL = DriverType.WEBSQL;
// Set any config values for localForage; can be called anytime before
// the first API call (e.g. `getItem`, `setItem`).
// We loop through options so we don't overwrite existing config
// values.
LocalForage.prototype.config = function(options) {
// If the options argument is an object, we use it to set values.
// Otherwise, we return either a specified config value or all
// config values.
if (typeof(options) === 'object') {
// If localforage is ready and fully initialized, we can't set
// any new configuration values. Instead, we return an error.
if (this._ready) {
return new Error("Can't call config() after localforage " +
'has been used.');
}
for (var i in options) {
if (i === 'storeName') {
options[i] = options[i].replace(/\W/g, '_');
}
this._config[i] = options[i];
}
// after all config options are set and
// the driver option is used, try setting it
if ('driver' in options && options.driver) {
this.setDriver(this._config.driver);
}
return true;
} else if (typeof(options) === 'string') {
return this._config[options];
} else {
return this._config;
}
};
// Used to define a custom driver, shared across all instances of
// localForage.
LocalForage.prototype.defineDriver = function(driverObject, callback,
errorCallback) {
var defineDriver = new Promise(function(resolve, reject) {
try {
var driverName = driverObject._driver;
var complianceError = new Error(
'Custom driver not compliant; see ' +
'https://mozilla.github.io/localForage/#definedriver'
);
var namingError = new Error(
'Custom driver name already in use: ' + driverObject._driver
);
// A driver name should be defined and not overlap with the
// library-defined, default drivers.
if (!driverObject._driver) {
reject(complianceError);
return;
}
if (isLibraryDriver(driverObject._driver)) {
reject(namingError);
return;
}
var customDriverMethods = LibraryMethods.concat('_initStorage');
for (var i = 0; i < customDriverMethods.length; i++) {
var customDriverMethod = customDriverMethods[i];
if (!customDriverMethod ||
!driverObject[customDriverMethod] ||
typeof driverObject[customDriverMethod] !== 'function') {
reject(complianceError);
return;
}
}
var supportPromise = Promise.resolve(true);
if ('_support' in driverObject) {
if (driverObject._support && typeof driverObject._support === 'function') {
supportPromise = driverObject._support();
} else {
supportPromise = Promise.resolve(!!driverObject._support);
}
}
supportPromise.then(function(supportResult) {
driverSupport[driverName] = supportResult;
CustomDrivers[driverName] = driverObject;
resolve();
}, reject);
} catch (e) {
reject(e);
}
});
defineDriver.then(callback, errorCallback);
return defineDriver;
};
LocalForage.prototype.driver = function() {
return this._driver || null;
};
LocalForage.prototype.ready = function(callback) {
var self = this;
var ready = new Promise(function(resolve, reject) {
self._driverSet.then(function() {
if (self._ready === null) {
self._ready = self._initStorage(self._config);
}
self._ready.then(resolve, reject);
})['catch'](reject);
});
ready.then(callback, callback);
return ready;
};
LocalForage.prototype.setDriver = function(drivers, callback,
errorCallback) {
var self = this;
if (typeof drivers === 'string') {
drivers = [drivers];
}
this._driverSet = new Promise(function(resolve, reject) {
var driverName = self._getFirstSupportedDriver(drivers);
var error = new Error('No available storage method found.');
if (!driverName) {
self._driverSet = Promise.reject(error);
reject(error);
return;
}
self._dbInfo = null;
self._ready = null;
if (isLibraryDriver(driverName)) {
var driverPromise = new Promise(function(resolve/*, reject*/) {
// We allow localForage to be declared as a module or as a
// library available without AMD/require.js.
if (moduleType === ModuleType.DEFINE) {
_dereq_([driverName], resolve);
} else if (moduleType === ModuleType.EXPORT) {
// Making it browserify friendly
switch (driverName) {
case self.INDEXEDDB:
resolve(_dereq_('./drivers/indexeddb'));
break;
case self.LOCALSTORAGE:
resolve(_dereq_('./drivers/localstorage'));
break;
case self.WEBSQL:
resolve(_dereq_('./drivers/websql'));
break;
}
} else {
resolve(globalObject[driverName]);
}
});
driverPromise.then(function(driver) {
self._extend(driver);
resolve();
});
} else if (CustomDrivers[driverName]) {
self._extend(CustomDrivers[driverName]);
resolve();
} else {
self._driverSet = Promise.reject(error);
reject(error);
}
});
function setDriverToConfig() {
self._config.driver = self.driver();
}
this._driverSet.then(setDriverToConfig, setDriverToConfig);
this._driverSet.then(callback, errorCallback);
return this._driverSet;
};
LocalForage.prototype.supports = function(driverName) {
return !!driverSupport[driverName];
};
LocalForage.prototype._extend = function(libraryMethodsAndProperties) {
extend(this, libraryMethodsAndProperties);
};
// Used to determine which driver we should use as the backend for this
// instance of localForage.
LocalForage.prototype._getFirstSupportedDriver = function(drivers) {
if (drivers && isArray(drivers)) {
for (var i = 0; i < drivers.length; i++) {
var driver = drivers[i];
if (this.supports(driver)) {
return driver;
}
}
}
return null;
};
LocalForage.prototype.createInstance = function(options) {
return new LocalForage(options);
};
// The actual localForage object that we expose as a module or via a
// global. It's extended by pulling in one of our other libraries.
var localForage = new LocalForage();
// We allow localForage to be declared as a module or as a library
// available without AMD/require.js.
if (moduleType === ModuleType.DEFINE) {
define('localforage', function() {
return localForage;
});
} else if (moduleType === ModuleType.EXPORT) {
module.exports = localForage;
} else {
this.localforage = localForage;
}
}).call(window);
},{"./drivers/indexeddb":78,"./drivers/localstorage":79,"./drivers/websql":80,"promise":76}],82:[function(_dereq_,module,exports){
(function() {
'use strict';
// Sadly, the best way to save binary data in WebSQL/localStorage is serializing
// it to Base64, so this is how we store it to prevent very strange errors with less
// verbose ways of binary <-> string data storage.
var BASE_CHARS = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/';
var BLOB_TYPE_PREFIX = '~~local_forage_type~';
var BLOB_TYPE_PREFIX_REGEX = /^~~local_forage_type~([^~]+)~/;
var SERIALIZED_MARKER = '__lfsc__:';
var SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER.length;
// OMG the serializations!
var TYPE_ARRAYBUFFER = 'arbf';
var TYPE_BLOB = 'blob';
var TYPE_INT8ARRAY = 'si08';
var TYPE_UINT8ARRAY = 'ui08';
var TYPE_UINT8CLAMPEDARRAY = 'uic8';
var TYPE_INT16ARRAY = 'si16';
var TYPE_INT32ARRAY = 'si32';
var TYPE_UINT16ARRAY = 'ur16';
var TYPE_UINT32ARRAY = 'ui32';
var TYPE_FLOAT32ARRAY = 'fl32';
var TYPE_FLOAT64ARRAY = 'fl64';
var TYPE_SERIALIZED_MARKER_LENGTH = SERIALIZED_MARKER_LENGTH +
TYPE_ARRAYBUFFER.length;
// Get out of our habit of using `window` inline, at least.
var globalObject = this;
// Abstracts constructing a Blob object, so it also works in older
// browsers that don't support the native Blob constructor. (i.e.
// old QtWebKit versions, at least).
function _createBlob(parts, properties) {
parts = parts || [];
properties = properties || {};
try {
return new Blob(parts, properties);
} catch (err) {
if (err.name !== 'TypeError') {
throw err;
}
var BlobBuilder = globalObject.BlobBuilder ||
globalObject.MSBlobBuilder ||
globalObject.MozBlobBuilder ||
globalObject.WebKitBlobBuilder;
var builder = new BlobBuilder();
for (var i = 0; i < parts.length; i += 1) {
builder.append(parts[i]);
}
return builder.getBlob(properties.type);
}
}
// Serialize a value, afterwards executing a callback (which usually
// instructs the `setItem()` callback/promise to be executed). This is how
// we store binary data with localStorage.
function serialize(value, callback) {
var valueString = '';
if (value) {
valueString = value.toString();
}
// Cannot use `value instanceof ArrayBuffer` or such here, as these
// checks fail when running the tests using casper.js...
//
// TODO: See why those tests fail and use a better solution.
if (value && (value.toString() === '[object ArrayBuffer]' ||
value.buffer &&
value.buffer.toString() === '[object ArrayBuffer]')) {
// Convert binary arrays to a string and prefix the string with
// a special marker.
var buffer;
var marker = SERIALIZED_MARKER;
if (value instanceof ArrayBuffer) {
buffer = value;
marker += TYPE_ARRAYBUFFER;
} else {
buffer = value.buffer;
if (valueString === '[object Int8Array]') {
marker += TYPE_INT8ARRAY;
} else if (valueString === '[object Uint8Array]') {
marker += TYPE_UINT8ARRAY;
} else if (valueString === '[object Uint8ClampedArray]') {
marker += TYPE_UINT8CLAMPEDARRAY;
} else if (valueString === '[object Int16Array]') {
marker += TYPE_INT16ARRAY;
} else if (valueString === '[object Uint16Array]') {
marker += TYPE_UINT16ARRAY;
} else if (valueString === '[object Int32Array]') {
marker += TYPE_INT32ARRAY;
} else if (valueString === '[object Uint32Array]') {
marker += TYPE_UINT32ARRAY;
} else if (valueString === '[object Float32Array]') {
marker += TYPE_FLOAT32ARRAY;
} else if (valueString === '[object Float64Array]') {
marker += TYPE_FLOAT64ARRAY;
} else {
callback(new Error('Failed to get type for BinaryArray'));
}
}
callback(marker + bufferToString(buffer));
} else if (valueString === '[object Blob]') {
// Conver the blob to a binaryArray and then to a string.
var fileReader = new FileReader();
fileReader.onload = function() {
// Backwards-compatible prefix for the blob type.
var str = BLOB_TYPE_PREFIX + value.type + '~' +
bufferToString(this.result);
callback(SERIALIZED_MARKER + TYPE_BLOB + str);
};
fileReader.readAsArrayBuffer(value);
} else {
try {
callback(JSON.stringify(value));
} catch (e) {
console.error("Couldn't convert value into a JSON string: ",
value);
callback(null, e);
}
}
}
// Deserialize data we've inserted into a value column/field. We place
// special markers into our strings to mark them as encoded; this isn't
// as nice as a meta field, but it's the only sane thing we can do whilst
// keeping localStorage support intact.
//
// Oftentimes this will just deserialize JSON content, but if we have a
// special marker (SERIALIZED_MARKER, defined above), we will extract
// some kind of arraybuffer/binary data/typed array out of the string.
function deserialize(value) {
// If we haven't marked this string as being specially serialized (i.e.
// something other than serialized JSON), we can just return it and be
// done with it.
if (value.substring(0,
SERIALIZED_MARKER_LENGTH) !== SERIALIZED_MARKER) {
return JSON.parse(value);
}
// The following code deals with deserializing some kind of Blob or
// TypedArray. First we separate out the type of data we're dealing
// with from the data itself.
var serializedString = value.substring(TYPE_SERIALIZED_MARKER_LENGTH);
var type = value.substring(SERIALIZED_MARKER_LENGTH,
TYPE_SERIALIZED_MARKER_LENGTH);
var blobType;
// Backwards-compatible blob type serialization strategy.
// DBs created with older versions of localForage will simply not have the blob type.
if (type === TYPE_BLOB && BLOB_TYPE_PREFIX_REGEX.test(serializedString)) {
var matcher = serializedString.match(BLOB_TYPE_PREFIX_REGEX);
blobType = matcher[1];
serializedString = serializedString.substring(matcher[0].length);
}
var buffer = stringToBuffer(serializedString);
// Return the right type based on the code/type set during
// serialization.
switch (type) {
case TYPE_ARRAYBUFFER:
return buffer;
case TYPE_BLOB:
return _createBlob([buffer], {type: blobType});
case TYPE_INT8ARRAY:
return new Int8Array(buffer);
case TYPE_UINT8ARRAY:
return new Uint8Array(buffer);
case TYPE_UINT8CLAMPEDARRAY:
return new Uint8ClampedArray(buffer);
case TYPE_INT16ARRAY:
return new Int16Array(buffer);
case TYPE_UINT16ARRAY:
return new Uint16Array(buffer);
case TYPE_INT32ARRAY:
return new Int32Array(buffer);
case TYPE_UINT32ARRAY:
return new Uint32Array(buffer);
case TYPE_FLOAT32ARRAY:
return new Float32Array(buffer);
case TYPE_FLOAT64ARRAY:
return new Float64Array(buffer);
default:
throw new Error('Unkown type: ' + type);
}
}
function stringToBuffer(serializedString) {
// Fill the string into a ArrayBuffer.
var bufferLength = serializedString.length * 0.75;
var len = serializedString.length;
var i;
var p = 0;
var encoded1, encoded2, encoded3, encoded4;
if (serializedString[serializedString.length - 1] === '=') {
bufferLength--;
if (serializedString[serializedString.length - 2] === '=') {
bufferLength--;
}
}
var buffer = new ArrayBuffer(bufferLength);
var bytes = new Uint8Array(buffer);
for (i = 0; i < len; i+=4) {
encoded1 = BASE_CHARS.indexOf(serializedString[i]);
encoded2 = BASE_CHARS.indexOf(serializedString[i+1]);
encoded3 = BASE_CHARS.indexOf(serializedString[i+2]);
encoded4 = BASE_CHARS.indexOf(serializedString[i+3]);
/*jslint bitwise: true */
bytes[p++] = (encoded1 << 2) | (encoded2 >> 4);
bytes[p++] = ((encoded2 & 15) << 4) | (encoded3 >> 2);
bytes[p++] = ((encoded3 & 3) << 6) | (encoded4 & 63);
}
return buffer;
}
// Converts a buffer to a string to store, serialized, in the backend
// storage library.
function bufferToString(buffer) {
// base64-arraybuffer
var bytes = new Uint8Array(buffer);
var base64String = '';
var i;
for (i = 0; i < bytes.length; i += 3) {
/*jslint bitwise: true */
base64String += BASE_CHARS[bytes[i] >> 2];
base64String += BASE_CHARS[((bytes[i] & 3) << 4) | (bytes[i + 1] >> 4)];
base64String += BASE_CHARS[((bytes[i + 1] & 15) << 2) | (bytes[i + 2] >> 6)];
base64String += BASE_CHARS[bytes[i + 2] & 63];
}
if ((bytes.length % 3) === 2) {
base64String = base64String.substring(0, base64String.length - 1) + '=';
} else if (bytes.length % 3 === 1) {
base64String = base64String.substring(0, base64String.length - 2) + '==';
}
return base64String;
}
var localforageSerializer = {
serialize: serialize,
deserialize: deserialize,
stringToBuffer: stringToBuffer,
bufferToString: bufferToString
};
if (typeof module !== 'undefined' && module.exports && typeof _dereq_ !== 'undefined') {
module.exports = localforageSerializer;
} else if (typeof define === 'function' && define.amd) {
define('localforageSerializer', function() {
return localforageSerializer;
});
} else {
this.localforageSerializer = localforageSerializer;
}
}).call(window);
},{}],83:[function(_dereq_,module,exports){
// Top level file is just a mixin of submodules & constants
'use strict';
var assign = _dereq_('./lib/utils/common').assign;
var deflate = _dereq_('./lib/deflate');
var inflate = _dereq_('./lib/inflate');
var constants = _dereq_('./lib/zlib/constants');
var pako = {};
assign(pako, deflate, inflate, constants);
module.exports = pako;
},{"./lib/deflate":84,"./lib/inflate":85,"./lib/utils/common":86,"./lib/zlib/constants":89}],84:[function(_dereq_,module,exports){
'use strict';
var zlib_deflate = _dereq_('./zlib/deflate.js');
var utils = _dereq_('./utils/common');
var strings = _dereq_('./utils/strings');
var msg = _dereq_('./zlib/messages');
var zstream = _dereq_('./zlib/zstream');
var toString = Object.prototype.toString;
/* Public constants ==========================================================*/
/* ===========================================================================*/
var Z_NO_FLUSH = 0;
var Z_FINISH = 4;
var Z_OK = 0;
var Z_STREAM_END = 1;
var Z_SYNC_FLUSH = 2;
var Z_DEFAULT_COMPRESSION = -1;
var Z_DEFAULT_STRATEGY = 0;
var Z_DEFLATED = 8;
/* ===========================================================================*/
/**
* class Deflate
*
* Generic JS-style wrapper for zlib calls. If you don't need
* streaming behaviour - use more simple functions: [[deflate]],
* [[deflateRaw]] and [[gzip]].
**/
/* internal
* Deflate.chunks -> Array
*
* Chunks of output data, if [[Deflate#onData]] not overriden.
**/
/**
* Deflate.result -> Uint8Array|Array
*
* Compressed result, generated by default [[Deflate#onData]]
* and [[Deflate#onEnd]] handlers. Filled after you push last chunk
* (call [[Deflate#push]] with `Z_FINISH` / `true` param) or if you
* push a chunk with explicit flush (call [[Deflate#push]] with
* `Z_SYNC_FLUSH` param).
**/
/**
* Deflate.err -> Number
*
* Error code after deflate finished. 0 (Z_OK) on success.
* You will not need it in real life, because deflate errors
* are possible only on wrong options or bad `onData` / `onEnd`
* custom handlers.
**/
/**
* Deflate.msg -> String
*
* Error message, if [[Deflate.err]] != 0
**/
/**
* new Deflate(options)
* - options (Object): zlib deflate options.
*
* Creates new deflator instance with specified params. Throws exception
* on bad params. Supported options:
*
* - `level`
* - `windowBits`
* - `memLevel`
* - `strategy`
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information on these.
*
* Additional options, for internal needs:
*
* - `chunkSize` - size of generated data chunks (16K by default)
* - `raw` (Boolean) - do raw deflate
* - `gzip` (Boolean) - create gzip wrapper
* - `to` (String) - if equal to 'string', then result will be "binary string"
* (each char code [0..255])
* - `header` (Object) - custom header for gzip
* - `text` (Boolean) - true if compressed data believed to be text
* - `time` (Number) - modification time, unix timestamp
* - `os` (Number) - operation system code
* - `extra` (Array) - array of bytes with extra data (max 65536)
* - `name` (String) - file name (binary string)
* - `comment` (String) - comment (binary string)
* - `hcrc` (Boolean) - true if header crc should be added
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
* , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
*
* var deflate = new pako.Deflate({ level: 3});
*
* deflate.push(chunk1, false);
* deflate.push(chunk2, true); // true -> last chunk
*
* if (deflate.err) { throw new Error(deflate.err); }
*
* console.log(deflate.result);
* ```
**/
var Deflate = function(options) {
this.options = utils.assign({
level: Z_DEFAULT_COMPRESSION,
method: Z_DEFLATED,
chunkSize: 16384,
windowBits: 15,
memLevel: 8,
strategy: Z_DEFAULT_STRATEGY,
to: ''
}, options || {});
var opt = this.options;
if (opt.raw && (opt.windowBits > 0)) {
opt.windowBits = -opt.windowBits;
}
else if (opt.gzip && (opt.windowBits > 0) && (opt.windowBits < 16)) {
opt.windowBits += 16;
}
this.err = 0; // error code, if happens (0 = Z_OK)
this.msg = ''; // error message
this.ended = false; // used to avoid multiple onEnd() calls
this.chunks = []; // chunks of compressed data
this.strm = new zstream();
this.strm.avail_out = 0;
var status = zlib_deflate.deflateInit2(
this.strm,
opt.level,
opt.method,
opt.windowBits,
opt.memLevel,
opt.strategy
);
if (status !== Z_OK) {
throw new Error(msg[status]);
}
if (opt.header) {
zlib_deflate.deflateSetHeader(this.strm, opt.header);
}
};
/**
* Deflate#push(data[, mode]) -> Boolean
* - data (Uint8Array|Array|ArrayBuffer|String): input data. Strings will be
* converted to utf8 byte sequence.
* - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
* See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
*
* Sends input data to deflate pipe, generating [[Deflate#onData]] calls with
* new compressed chunks. Returns `true` on success. The last data block must have
* mode Z_FINISH (or `true`). That will flush internal pending buffers and call
* [[Deflate#onEnd]]. For interim explicit flushes (without ending the stream) you
* can use mode Z_SYNC_FLUSH, keeping the compression context.
*
* On fail call [[Deflate#onEnd]] with error code and return false.
*
* We strongly recommend to use `Uint8Array` on input for best speed (output
* array format is detected automatically). Also, don't skip last param and always
* use the same type in your code (boolean or number). That will improve JS speed.
*
* For regular `Array`-s make sure all elements are [0..255].
*
* ##### Example
*
* ```javascript
* push(chunk, false); // push one of data chunks
* ...
* push(chunk, true); // push last chunk
* ```
**/
Deflate.prototype.push = function(data, mode) {
var strm = this.strm;
var chunkSize = this.options.chunkSize;
var status, _mode;
if (this.ended) { return false; }
_mode = (mode === ~~mode) ? mode : ((mode === true) ? Z_FINISH : Z_NO_FLUSH);
// Convert data if needed
if (typeof data === 'string') {
// If we need to compress text, change encoding to utf8.
strm.input = strings.string2buf(data);
} else if (toString.call(data) === '[object ArrayBuffer]') {
strm.input = new Uint8Array(data);
} else {
strm.input = data;
}
strm.next_in = 0;
strm.avail_in = strm.input.length;
do {
if (strm.avail_out === 0) {
strm.output = new utils.Buf8(chunkSize);
strm.next_out = 0;
strm.avail_out = chunkSize;
}
status = zlib_deflate.deflate(strm, _mode); /* no bad return value */
if (status !== Z_STREAM_END && status !== Z_OK) {
this.onEnd(status);
this.ended = true;
return false;
}
if (strm.avail_out === 0 || (strm.avail_in === 0 && (_mode === Z_FINISH || _mode === Z_SYNC_FLUSH))) {
if (this.options.to === 'string') {
this.onData(strings.buf2binstring(utils.shrinkBuf(strm.output, strm.next_out)));
} else {
this.onData(utils.shrinkBuf(strm.output, strm.next_out));
}
}
} while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== Z_STREAM_END);
// Finalize on the last chunk.
if (_mode === Z_FINISH) {
status = zlib_deflate.deflateEnd(this.strm);
this.onEnd(status);
this.ended = true;
return status === Z_OK;
}
// callback interim results if Z_SYNC_FLUSH.
if (_mode === Z_SYNC_FLUSH) {
this.onEnd(Z_OK);
strm.avail_out = 0;
return true;
}
return true;
};
/**
* Deflate#onData(chunk) -> Void
* - chunk (Uint8Array|Array|String): ouput data. Type of array depends
* on js engine support. When string output requested, each chunk
* will be string.
*
* By default, stores data blocks in `chunks[]` property and glue
* those in `onEnd`. Override this handler, if you need another behaviour.
**/
Deflate.prototype.onData = function(chunk) {
this.chunks.push(chunk);
};
/**
* Deflate#onEnd(status) -> Void
* - status (Number): deflate status. 0 (Z_OK) on success,
* other if not.
*
* Called once after you tell deflate that the input stream is
* complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
* or if an error happened. By default - join collected chunks,
* free memory and fill `results` / `err` properties.
**/
Deflate.prototype.onEnd = function(status) {
// On success - join
if (status === Z_OK) {
if (this.options.to === 'string') {
this.result = this.chunks.join('');
} else {
this.result = utils.flattenChunks(this.chunks);
}
}
this.chunks = [];
this.err = status;
this.msg = this.strm.msg;
};
/**
* deflate(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to compress.
* - options (Object): zlib deflate options.
*
* Compress `data` with deflate alrorythm and `options`.
*
* Supported options are:
*
* - level
* - windowBits
* - memLevel
* - strategy
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information on these.
*
* Sugar (options):
*
* - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
* negative windowBits implicitly.
* - `to` (String) - if equal to 'string', then result will be "binary string"
* (each char code [0..255])
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , data = Uint8Array([1,2,3,4,5,6,7,8,9]);
*
* console.log(pako.deflate(data));
* ```
**/
function deflate(input, options) {
var deflator = new Deflate(options);
deflator.push(input, true);
// That will never happens, if you don't cheat with options :)
if (deflator.err) { throw deflator.msg; }
return deflator.result;
}
/**
* deflateRaw(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to compress.
* - options (Object): zlib deflate options.
*
* The same as [[deflate]], but creates raw data, without wrapper
* (header and adler32 crc).
**/
function deflateRaw(input, options) {
options = options || {};
options.raw = true;
return deflate(input, options);
}
/**
* gzip(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to compress.
* - options (Object): zlib deflate options.
*
* The same as [[deflate]], but create gzip wrapper instead of
* deflate one.
**/
function gzip(input, options) {
options = options || {};
options.gzip = true;
return deflate(input, options);
}
exports.Deflate = Deflate;
exports.deflate = deflate;
exports.deflateRaw = deflateRaw;
exports.gzip = gzip;
},{"./utils/common":86,"./utils/strings":87,"./zlib/deflate.js":91,"./zlib/messages":96,"./zlib/zstream":98}],85:[function(_dereq_,module,exports){
'use strict';
var zlib_inflate = _dereq_('./zlib/inflate.js');
var utils = _dereq_('./utils/common');
var strings = _dereq_('./utils/strings');
var c = _dereq_('./zlib/constants');
var msg = _dereq_('./zlib/messages');
var zstream = _dereq_('./zlib/zstream');
var gzheader = _dereq_('./zlib/gzheader');
var toString = Object.prototype.toString;
/**
* class Inflate
*
* Generic JS-style wrapper for zlib calls. If you don't need
* streaming behaviour - use more simple functions: [[inflate]]
* and [[inflateRaw]].
**/
/* internal
* inflate.chunks -> Array
*
* Chunks of output data, if [[Inflate#onData]] not overriden.
**/
/**
* Inflate.result -> Uint8Array|Array|String
*
* Uncompressed result, generated by default [[Inflate#onData]]
* and [[Inflate#onEnd]] handlers. Filled after you push last chunk
* (call [[Inflate#push]] with `Z_FINISH` / `true` param) or if you
* push a chunk with explicit flush (call [[Inflate#push]] with
* `Z_SYNC_FLUSH` param).
**/
/**
* Inflate.err -> Number
*
* Error code after inflate finished. 0 (Z_OK) on success.
* Should be checked if broken data possible.
**/
/**
* Inflate.msg -> String
*
* Error message, if [[Inflate.err]] != 0
**/
/**
* new Inflate(options)
* - options (Object): zlib inflate options.
*
* Creates new inflator instance with specified params. Throws exception
* on bad params. Supported options:
*
* - `windowBits`
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information on these.
*
* Additional options, for internal needs:
*
* - `chunkSize` - size of generated data chunks (16K by default)
* - `raw` (Boolean) - do raw inflate
* - `to` (String) - if equal to 'string', then result will be converted
* from utf8 to utf16 (javascript) string. When string output requested,
* chunk length can differ from `chunkSize`, depending on content.
*
* By default, when no options set, autodetect deflate/gzip data format via
* wrapper header.
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , chunk1 = Uint8Array([1,2,3,4,5,6,7,8,9])
* , chunk2 = Uint8Array([10,11,12,13,14,15,16,17,18,19]);
*
* var inflate = new pako.Inflate({ level: 3});
*
* inflate.push(chunk1, false);
* inflate.push(chunk2, true); // true -> last chunk
*
* if (inflate.err) { throw new Error(inflate.err); }
*
* console.log(inflate.result);
* ```
**/
var Inflate = function(options) {
this.options = utils.assign({
chunkSize: 16384,
windowBits: 0,
to: ''
}, options || {});
var opt = this.options;
// Force window size for `raw` data, if not set directly,
// because we have no header for autodetect.
if (opt.raw && (opt.windowBits >= 0) && (opt.windowBits < 16)) {
opt.windowBits = -opt.windowBits;
if (opt.windowBits === 0) { opt.windowBits = -15; }
}
// If `windowBits` not defined (and mode not raw) - set autodetect flag for gzip/deflate
if ((opt.windowBits >= 0) && (opt.windowBits < 16) &&
!(options && options.windowBits)) {
opt.windowBits += 32;
}
// Gzip header has no info about windows size, we can do autodetect only
// for deflate. So, if window size not set, force it to max when gzip possible
if ((opt.windowBits > 15) && (opt.windowBits < 48)) {
// bit 3 (16) -> gzipped data
// bit 4 (32) -> autodetect gzip/deflate
if ((opt.windowBits & 15) === 0) {
opt.windowBits |= 15;
}
}
this.err = 0; // error code, if happens (0 = Z_OK)
this.msg = ''; // error message
this.ended = false; // used to avoid multiple onEnd() calls
this.chunks = []; // chunks of compressed data
this.strm = new zstream();
this.strm.avail_out = 0;
var status = zlib_inflate.inflateInit2(
this.strm,
opt.windowBits
);
if (status !== c.Z_OK) {
throw new Error(msg[status]);
}
this.header = new gzheader();
zlib_inflate.inflateGetHeader(this.strm, this.header);
};
/**
* Inflate#push(data[, mode]) -> Boolean
* - data (Uint8Array|Array|ArrayBuffer|String): input data
* - mode (Number|Boolean): 0..6 for corresponding Z_NO_FLUSH..Z_TREE modes.
* See constants. Skipped or `false` means Z_NO_FLUSH, `true` meansh Z_FINISH.
*
* Sends input data to inflate pipe, generating [[Inflate#onData]] calls with
* new output chunks. Returns `true` on success. The last data block must have
* mode Z_FINISH (or `true`). That will flush internal pending buffers and call
* [[Inflate#onEnd]]. For interim explicit flushes (without ending the stream) you
* can use mode Z_SYNC_FLUSH, keeping the decompression context.
*
* On fail call [[Inflate#onEnd]] with error code and return false.
*
* We strongly recommend to use `Uint8Array` on input for best speed (output
* format is detected automatically). Also, don't skip last param and always
* use the same type in your code (boolean or number). That will improve JS speed.
*
* For regular `Array`-s make sure all elements are [0..255].
*
* ##### Example
*
* ```javascript
* push(chunk, false); // push one of data chunks
* ...
* push(chunk, true); // push last chunk
* ```
**/
Inflate.prototype.push = function(data, mode) {
var strm = this.strm;
var chunkSize = this.options.chunkSize;
var status, _mode;
var next_out_utf8, tail, utf8str;
// Flag to properly process Z_BUF_ERROR on testing inflate call
// when we check that all output data was flushed.
var allowBufError = false;
if (this.ended) { return false; }
_mode = (mode === ~~mode) ? mode : ((mode === true) ? c.Z_FINISH : c.Z_NO_FLUSH);
// Convert data if needed
if (typeof data === 'string') {
// Only binary strings can be decompressed on practice
strm.input = strings.binstring2buf(data);
} else if (toString.call(data) === '[object ArrayBuffer]') {
strm.input = new Uint8Array(data);
} else {
strm.input = data;
}
strm.next_in = 0;
strm.avail_in = strm.input.length;
do {
if (strm.avail_out === 0) {
strm.output = new utils.Buf8(chunkSize);
strm.next_out = 0;
strm.avail_out = chunkSize;
}
status = zlib_inflate.inflate(strm, c.Z_NO_FLUSH); /* no bad return value */
if (status === c.Z_BUF_ERROR && allowBufError === true) {
status = c.Z_OK;
allowBufError = false;
}
if (status !== c.Z_STREAM_END && status !== c.Z_OK) {
this.onEnd(status);
this.ended = true;
return false;
}
if (strm.next_out) {
if (strm.avail_out === 0 || status === c.Z_STREAM_END || (strm.avail_in === 0 && (_mode === c.Z_FINISH || _mode === c.Z_SYNC_FLUSH))) {
if (this.options.to === 'string') {
next_out_utf8 = strings.utf8border(strm.output, strm.next_out);
tail = strm.next_out - next_out_utf8;
utf8str = strings.buf2string(strm.output, next_out_utf8);
// move tail
strm.next_out = tail;
strm.avail_out = chunkSize - tail;
if (tail) { utils.arraySet(strm.output, strm.output, next_out_utf8, tail, 0); }
this.onData(utf8str);
} else {
this.onData(utils.shrinkBuf(strm.output, strm.next_out));
}
}
}
// When no more input data, we should check that internal inflate buffers
// are flushed. The only way to do it when avail_out = 0 - run one more
// inflate pass. But if output data not exists, inflate return Z_BUF_ERROR.
// Here we set flag to process this error properly.
//
// NOTE. Deflate does not return error in this case and does not needs such
// logic.
if (strm.avail_in === 0 && strm.avail_out === 0) {
allowBufError = true;
}
} while ((strm.avail_in > 0 || strm.avail_out === 0) && status !== c.Z_STREAM_END);
if (status === c.Z_STREAM_END) {
_mode = c.Z_FINISH;
}
// Finalize on the last chunk.
if (_mode === c.Z_FINISH) {
status = zlib_inflate.inflateEnd(this.strm);
this.onEnd(status);
this.ended = true;
return status === c.Z_OK;
}
// callback interim results if Z_SYNC_FLUSH.
if (_mode === c.Z_SYNC_FLUSH) {
this.onEnd(c.Z_OK);
strm.avail_out = 0;
return true;
}
return true;
};
/**
* Inflate#onData(chunk) -> Void
* - chunk (Uint8Array|Array|String): ouput data. Type of array depends
* on js engine support. When string output requested, each chunk
* will be string.
*
* By default, stores data blocks in `chunks[]` property and glue
* those in `onEnd`. Override this handler, if you need another behaviour.
**/
Inflate.prototype.onData = function(chunk) {
this.chunks.push(chunk);
};
/**
* Inflate#onEnd(status) -> Void
* - status (Number): inflate status. 0 (Z_OK) on success,
* other if not.
*
* Called either after you tell inflate that the input stream is
* complete (Z_FINISH) or should be flushed (Z_SYNC_FLUSH)
* or if an error happened. By default - join collected chunks,
* free memory and fill `results` / `err` properties.
**/
Inflate.prototype.onEnd = function(status) {
// On success - join
if (status === c.Z_OK) {
if (this.options.to === 'string') {
// Glue & convert here, until we teach pako to send
// utf8 alligned strings to onData
this.result = this.chunks.join('');
} else {
this.result = utils.flattenChunks(this.chunks);
}
}
this.chunks = [];
this.err = status;
this.msg = this.strm.msg;
};
/**
* inflate(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to decompress.
* - options (Object): zlib inflate options.
*
* Decompress `data` with inflate/ungzip and `options`. Autodetect
* format via wrapper header by default. That's why we don't provide
* separate `ungzip` method.
*
* Supported options are:
*
* - windowBits
*
* [http://zlib.net/manual.html#Advanced](http://zlib.net/manual.html#Advanced)
* for more information.
*
* Sugar (options):
*
* - `raw` (Boolean) - say that we work with raw stream, if you don't wish to specify
* negative windowBits implicitly.
* - `to` (String) - if equal to 'string', then result will be converted
* from utf8 to utf16 (javascript) string. When string output requested,
* chunk length can differ from `chunkSize`, depending on content.
*
*
* ##### Example:
*
* ```javascript
* var pako = require('pako')
* , input = pako.deflate([1,2,3,4,5,6,7,8,9])
* , output;
*
* try {
* output = pako.inflate(input);
* } catch (err)
* console.log(err);
* }
* ```
**/
function inflate(input, options) {
var inflator = new Inflate(options);
inflator.push(input, true);
// That will never happens, if you don't cheat with options :)
if (inflator.err) { throw inflator.msg; }
return inflator.result;
}
/**
* inflateRaw(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to decompress.
* - options (Object): zlib inflate options.
*
* The same as [[inflate]], but creates raw data, without wrapper
* (header and adler32 crc).
**/
function inflateRaw(input, options) {
options = options || {};
options.raw = true;
return inflate(input, options);
}
/**
* ungzip(data[, options]) -> Uint8Array|Array|String
* - data (Uint8Array|Array|String): input data to decompress.
* - options (Object): zlib inflate options.
*
* Just shortcut to [[inflate]], because it autodetects format
* by header.content. Done for convenience.
**/
exports.Inflate = Inflate;
exports.inflate = inflate;
exports.inflateRaw = inflateRaw;
exports.ungzip = inflate;
},{"./utils/common":86,"./utils/strings":87,"./zlib/constants":89,"./zlib/gzheader":92,"./zlib/inflate.js":94,"./zlib/messages":96,"./zlib/zstream":98}],86:[function(_dereq_,module,exports){
'use strict';
var TYPED_OK = (typeof Uint8Array !== 'undefined') &&
(typeof Uint16Array !== 'undefined') &&
(typeof Int32Array !== 'undefined');
exports.assign = function (obj /*from1, from2, from3, ...*/) {
var sources = Array.prototype.slice.call(arguments, 1);
while (sources.length) {
var source = sources.shift();
if (!source) { continue; }
if (typeof source !== 'object') {
throw new TypeError(source + 'must be non-object');
}
for (var p in source) {
if (source.hasOwnProperty(p)) {
obj[p] = source[p];
}
}
}
return obj;
};
// reduce buffer size, avoiding mem copy
exports.shrinkBuf = function (buf, size) {
if (buf.length === size) { return buf; }
if (buf.subarray) { return buf.subarray(0, size); }
buf.length = size;
return buf;
};
var fnTyped = {
arraySet: function (dest, src, src_offs, len, dest_offs) {
if (src.subarray && dest.subarray) {
dest.set(src.subarray(src_offs, src_offs+len), dest_offs);
return;
}
// Fallback to ordinary array
for (var i=0; i<len; i++) {
dest[dest_offs + i] = src[src_offs + i];
}
},
// Join array of chunks to single array.
flattenChunks: function(chunks) {
var i, l, len, pos, chunk, result;
// calculate data length
len = 0;
for (i=0, l=chunks.length; i<l; i++) {
len += chunks[i].length;
}
// join chunks
result = new Uint8Array(len);
pos = 0;
for (i=0, l=chunks.length; i<l; i++) {
chunk = chunks[i];
result.set(chunk, pos);
pos += chunk.length;
}
return result;
}
};
var fnUntyped = {
arraySet: function (dest, src, src_offs, len, dest_offs) {
for (var i=0; i<len; i++) {
dest[dest_offs + i] = src[src_offs + i];
}
},
// Join array of chunks to single array.
flattenChunks: function(chunks) {
return [].concat.apply([], chunks);
}
};
// Enable/Disable typed arrays use, for testing
//
exports.setTyped = function (on) {
if (on) {
exports.Buf8 = Uint8Array;
exports.Buf16 = Uint16Array;
exports.Buf32 = Int32Array;
exports.assign(exports, fnTyped);
} else {
exports.Buf8 = Array;
exports.Buf16 = Array;
exports.Buf32 = Array;
exports.assign(exports, fnUntyped);
}
};
exports.setTyped(TYPED_OK);
},{}],87:[function(_dereq_,module,exports){
// String encode/decode helpers
'use strict';
var utils = _dereq_('./common');
// Quick check if we can use fast array to bin string conversion
//
// - apply(Array) can fail on Android 2.2
// - apply(Uint8Array) can fail on iOS 5.1 Safary
//
var STR_APPLY_OK = true;
var STR_APPLY_UIA_OK = true;
try { String.fromCharCode.apply(null, [0]); } catch(__) { STR_APPLY_OK = false; }
try { String.fromCharCode.apply(null, new Uint8Array(1)); } catch(__) { STR_APPLY_UIA_OK = false; }
// Table with utf8 lengths (calculated by first byte of sequence)
// Note, that 5 & 6-byte values and some 4-byte values can not be represented in JS,
// because max possible codepoint is 0x10ffff
var _utf8len = new utils.Buf8(256);
for (var q=0; q<256; q++) {
_utf8len[q] = (q >= 252 ? 6 : q >= 248 ? 5 : q >= 240 ? 4 : q >= 224 ? 3 : q >= 192 ? 2 : 1);
}
_utf8len[254]=_utf8len[254]=1; // Invalid sequence start
// convert string to array (typed, when possible)
exports.string2buf = function (str) {
var buf, c, c2, m_pos, i, str_len = str.length, buf_len = 0;
// count binary size
for (m_pos = 0; m_pos < str_len; m_pos++) {
c = str.charCodeAt(m_pos);
if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
c2 = str.charCodeAt(m_pos+1);
if ((c2 & 0xfc00) === 0xdc00) {
c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
m_pos++;
}
}
buf_len += c < 0x80 ? 1 : c < 0x800 ? 2 : c < 0x10000 ? 3 : 4;
}
// allocate buffer
buf = new utils.Buf8(buf_len);
// convert
for (i=0, m_pos = 0; i < buf_len; m_pos++) {
c = str.charCodeAt(m_pos);
if ((c & 0xfc00) === 0xd800 && (m_pos+1 < str_len)) {
c2 = str.charCodeAt(m_pos+1);
if ((c2 & 0xfc00) === 0xdc00) {
c = 0x10000 + ((c - 0xd800) << 10) + (c2 - 0xdc00);
m_pos++;
}
}
if (c < 0x80) {
/* one byte */
buf[i++] = c;
} else if (c < 0x800) {
/* two bytes */
buf[i++] = 0xC0 | (c >>> 6);
buf[i++] = 0x80 | (c & 0x3f);
} else if (c < 0x10000) {
/* three bytes */
buf[i++] = 0xE0 | (c >>> 12);
buf[i++] = 0x80 | (c >>> 6 & 0x3f);
buf[i++] = 0x80 | (c & 0x3f);
} else {
/* four bytes */
buf[i++] = 0xf0 | (c >>> 18);
buf[i++] = 0x80 | (c >>> 12 & 0x3f);
buf[i++] = 0x80 | (c >>> 6 & 0x3f);
buf[i++] = 0x80 | (c & 0x3f);
}
}
return buf;
};
// Helper (used in 2 places)
function buf2binstring(buf, len) {
// use fallback for big arrays to avoid stack overflow
if (len < 65537) {
if ((buf.subarray && STR_APPLY_UIA_OK) || (!buf.subarray && STR_APPLY_OK)) {
return String.fromCharCode.apply(null, utils.shrinkBuf(buf, len));
}
}
var result = '';
for (var i=0; i < len; i++) {
result += String.fromCharCode(buf[i]);
}
return result;
}
// Convert byte array to binary string
exports.buf2binstring = function(buf) {
return buf2binstring(buf, buf.length);
};
// Convert binary string (typed, when possible)
exports.binstring2buf = function(str) {
var buf = new utils.Buf8(str.length);
for (var i=0, len=buf.length; i < len; i++) {
buf[i] = str.charCodeAt(i);
}
return buf;
};
// convert array to string
exports.buf2string = function (buf, max) {
var i, out, c, c_len;
var len = max || buf.length;
// Reserve max possible length (2 words per char)
// NB: by unknown reasons, Array is significantly faster for
// String.fromCharCode.apply than Uint16Array.
var utf16buf = new Array(len*2);
for (out=0, i=0; i<len;) {
c = buf[i++];
// quick process ascii
if (c < 0x80) { utf16buf[out++] = c; continue; }
c_len = _utf8len[c];
// skip 5 & 6 byte codes
if (c_len > 4) { utf16buf[out++] = 0xfffd; i += c_len-1; continue; }
// apply mask on first byte
c &= c_len === 2 ? 0x1f : c_len === 3 ? 0x0f : 0x07;
// join the rest
while (c_len > 1 && i < len) {
c = (c << 6) | (buf[i++] & 0x3f);
c_len--;
}
// terminated by end of string?
if (c_len > 1) { utf16buf[out++] = 0xfffd; continue; }
if (c < 0x10000) {
utf16buf[out++] = c;
} else {
c -= 0x10000;
utf16buf[out++] = 0xd800 | ((c >> 10) & 0x3ff);
utf16buf[out++] = 0xdc00 | (c & 0x3ff);
}
}
return buf2binstring(utf16buf, out);
};
// Calculate max possible position in utf8 buffer,
// that will not break sequence. If that's not possible
// - (very small limits) return max size as is.
//
// buf[] - utf8 bytes array
// max - length limit (mandatory);
exports.utf8border = function(buf, max) {
var pos;
max = max || buf.length;
if (max > buf.length) { max = buf.length; }
// go back from last position, until start of sequence found
pos = max-1;
while (pos >= 0 && (buf[pos] & 0xC0) === 0x80) { pos--; }
// Fuckup - very small and broken sequence,
// return max, because we should return something anyway.
if (pos < 0) { return max; }
// If we came to start of buffer - that means vuffer is too small,
// return max too.
if (pos === 0) { return max; }
return (pos + _utf8len[buf[pos]] > max) ? pos : max;
};
},{"./common":86}],88:[function(_dereq_,module,exports){
'use strict';
// Note: adler32 takes 12% for level 0 and 2% for level 6.
// It doesn't worth to make additional optimizationa as in original.
// Small size is preferable.
function adler32(adler, buf, len, pos) {
var s1 = (adler & 0xffff) |0,
s2 = ((adler >>> 16) & 0xffff) |0,
n = 0;
while (len !== 0) {
// Set limit ~ twice less than 5552, to keep
// s2 in 31-bits, because we force signed ints.
// in other case %= will fail.
n = len > 2000 ? 2000 : len;
len -= n;
do {
s1 = (s1 + buf[pos++]) |0;
s2 = (s2 + s1) |0;
} while (--n);
s1 %= 65521;
s2 %= 65521;
}
return (s1 | (s2 << 16)) |0;
}
module.exports = adler32;
},{}],89:[function(_dereq_,module,exports){
module.exports = {
/* Allowed flush values; see deflate() and inflate() below for details */
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,
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
Z_OK: 0,
Z_STREAM_END: 1,
Z_NEED_DICT: 2,
Z_ERRNO: -1,
Z_STREAM_ERROR: -2,
Z_DATA_ERROR: -3,
//Z_MEM_ERROR: -4,
Z_BUF_ERROR: -5,
//Z_VERSION_ERROR: -6,
/* compression levels */
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,
/* Possible values of the data_type field (though see inflate()) */
Z_BINARY: 0,
Z_TEXT: 1,
//Z_ASCII: 1, // = Z_TEXT (deprecated)
Z_UNKNOWN: 2,
/* The deflate compression method */
Z_DEFLATED: 8
//Z_NULL: null // Use -1 or null inline, depending on var type
};
},{}],90:[function(_dereq_,module,exports){
'use strict';
// Note: we can't get significant speed boost here.
// So write code to minimize size - no pregenerated tables
// and array tools dependencies.
// Use ordinary array, since untyped makes no boost here
function makeTable() {
var c, table = [];
for (var n =0; n < 256; n++) {
c = n;
for (var k =0; k < 8; k++) {
c = ((c&1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1));
}
table[n] = c;
}
return table;
}
// Create table on load. Just 255 signed longs. Not a problem.
var crcTable = makeTable();
function crc32(crc, buf, len, pos) {
var t = crcTable,
end = pos + len;
crc = crc ^ (-1);
for (var i = pos; i < end; i++) {
crc = (crc >>> 8) ^ t[(crc ^ buf[i]) & 0xFF];
}
return (crc ^ (-1)); // >>> 0;
}
module.exports = crc32;
},{}],91:[function(_dereq_,module,exports){
'use strict';
var utils = _dereq_('../utils/common');
var trees = _dereq_('./trees');
var adler32 = _dereq_('./adler32');
var crc32 = _dereq_('./crc32');
var msg = _dereq_('./messages');
/* Public constants ==========================================================*/
/* ===========================================================================*/
/* Allowed flush values; see deflate() and inflate() below for details */
var Z_NO_FLUSH = 0;
var Z_PARTIAL_FLUSH = 1;
//var Z_SYNC_FLUSH = 2;
var Z_FULL_FLUSH = 3;
var Z_FINISH = 4;
var Z_BLOCK = 5;
//var Z_TREES = 6;
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
var Z_OK = 0;
var Z_STREAM_END = 1;
//var Z_NEED_DICT = 2;
//var Z_ERRNO = -1;
var Z_STREAM_ERROR = -2;
var Z_DATA_ERROR = -3;
//var Z_MEM_ERROR = -4;
var Z_BUF_ERROR = -5;
//var Z_VERSION_ERROR = -6;
/* compression levels */
//var Z_NO_COMPRESSION = 0;
//var Z_BEST_SPEED = 1;
//var Z_BEST_COMPRESSION = 9;
var Z_DEFAULT_COMPRESSION = -1;
var Z_FILTERED = 1;
var Z_HUFFMAN_ONLY = 2;
var Z_RLE = 3;
var Z_FIXED = 4;
var Z_DEFAULT_STRATEGY = 0;
/* Possible values of the data_type field (though see inflate()) */
//var Z_BINARY = 0;
//var Z_TEXT = 1;
//var Z_ASCII = 1; // = Z_TEXT
var Z_UNKNOWN = 2;
/* The deflate compression method */
var Z_DEFLATED = 8;
/*============================================================================*/
var MAX_MEM_LEVEL = 9;
/* Maximum value for memLevel in deflateInit2 */
var MAX_WBITS = 15;
/* 32K LZ77 window */
var DEF_MEM_LEVEL = 8;
var LENGTH_CODES = 29;
/* number of length codes, not counting the special END_BLOCK code */
var LITERALS = 256;
/* number of literal bytes 0..255 */
var L_CODES = LITERALS + 1 + LENGTH_CODES;
/* number of Literal or Length codes, including the END_BLOCK code */
var D_CODES = 30;
/* number of distance codes */
var BL_CODES = 19;
/* number of codes used to transfer the bit lengths */
var HEAP_SIZE = 2*L_CODES + 1;
/* maximum heap size */
var MAX_BITS = 15;
/* All codes must not exceed MAX_BITS bits */
var MIN_MATCH = 3;
var MAX_MATCH = 258;
var MIN_LOOKAHEAD = (MAX_MATCH + MIN_MATCH + 1);
var PRESET_DICT = 0x20;
var INIT_STATE = 42;
var EXTRA_STATE = 69;
var NAME_STATE = 73;
var COMMENT_STATE = 91;
var HCRC_STATE = 103;
var BUSY_STATE = 113;
var FINISH_STATE = 666;
var BS_NEED_MORE = 1; /* block not completed, need more input or more output */
var BS_BLOCK_DONE = 2; /* block flush performed */
var BS_FINISH_STARTED = 3; /* finish started, need only more output at next deflate */
var BS_FINISH_DONE = 4; /* finish done, accept no more input or output */
var OS_CODE = 0x03; // Unix :) . Don't detect, use this default.
function err(strm, errorCode) {
strm.msg = msg[errorCode];
return errorCode;
}
function rank(f) {
return ((f) << 1) - ((f) > 4 ? 9 : 0);
}
function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
/* =========================================================================
* Flush as much pending output as possible. All deflate() output goes
* through this function so some applications may wish to modify it
* to avoid allocating a large strm->output buffer and copying into it.
* (See also read_buf()).
*/
function flush_pending(strm) {
var s = strm.state;
//_tr_flush_bits(s);
var len = s.pending;
if (len > strm.avail_out) {
len = strm.avail_out;
}
if (len === 0) { return; }
utils.arraySet(strm.output, s.pending_buf, s.pending_out, len, strm.next_out);
strm.next_out += len;
s.pending_out += len;
strm.total_out += len;
strm.avail_out -= len;
s.pending -= len;
if (s.pending === 0) {
s.pending_out = 0;
}
}
function flush_block_only (s, last) {
trees._tr_flush_block(s, (s.block_start >= 0 ? s.block_start : -1), s.strstart - s.block_start, last);
s.block_start = s.strstart;
flush_pending(s.strm);
}
function put_byte(s, b) {
s.pending_buf[s.pending++] = b;
}
/* =========================================================================
* Put a short in the pending buffer. The 16-bit value is put in MSB order.
* IN assertion: the stream state is correct and there is enough room in
* pending_buf.
*/
function putShortMSB(s, b) {
// put_byte(s, (Byte)(b >> 8));
// put_byte(s, (Byte)(b & 0xff));
s.pending_buf[s.pending++] = (b >>> 8) & 0xff;
s.pending_buf[s.pending++] = b & 0xff;
}
/* ===========================================================================
* Read a new buffer from the current input stream, update the adler32
* and total number of bytes read. All deflate() input goes through
* this function so some applications may wish to modify it to avoid
* allocating a large strm->input buffer and copying from it.
* (See also flush_pending()).
*/
function read_buf(strm, buf, start, size) {
var len = strm.avail_in;
if (len > size) { len = size; }
if (len === 0) { return 0; }
strm.avail_in -= len;
utils.arraySet(buf, strm.input, strm.next_in, len, start);
if (strm.state.wrap === 1) {
strm.adler = adler32(strm.adler, buf, len, start);
}
else if (strm.state.wrap === 2) {
strm.adler = crc32(strm.adler, buf, len, start);
}
strm.next_in += len;
strm.total_in += len;
return len;
}
/* ===========================================================================
* Set match_start to the longest match starting at the given string and
* return its length. Matches shorter or equal to prev_length are discarded,
* in which case the result is equal to prev_length and match_start is
* garbage.
* IN assertions: cur_match is the head of the hash chain for the current
* string (strstart) and its distance is <= MAX_DIST, and prev_length >= 1
* OUT assertion: the match length is not greater than s->lookahead.
*/
function longest_match(s, cur_match) {
var chain_length = s.max_chain_length; /* max hash chain length */
var scan = s.strstart; /* current string */
var match; /* matched string */
var len; /* length of current match */
var best_len = s.prev_length; /* best match length so far */
var nice_match = s.nice_match; /* stop if match long enough */
var limit = (s.strstart > (s.w_size - MIN_LOOKAHEAD)) ?
s.strstart - (s.w_size - MIN_LOOKAHEAD) : 0/*NIL*/;
var _win = s.window; // shortcut
var wmask = s.w_mask;
var prev = s.prev;
/* Stop when cur_match becomes <= limit. To simplify the code,
* we prevent matches with the string of window index 0.
*/
var strend = s.strstart + MAX_MATCH;
var scan_end1 = _win[scan + best_len - 1];
var scan_end = _win[scan + best_len];
/* The code is optimized for HASH_BITS >= 8 and MAX_MATCH-2 multiple of 16.
* It is easy to get rid of this optimization if necessary.
*/
// Assert(s->hash_bits >= 8 && MAX_MATCH == 258, "Code too clever");
/* Do not waste too much time if we already have a good match: */
if (s.prev_length >= s.good_match) {
chain_length >>= 2;
}
/* Do not look for matches beyond the end of the input. This is necessary
* to make deflate deterministic.
*/
if (nice_match > s.lookahead) { nice_match = s.lookahead; }
// Assert((ulg)s->strstart <= s->window_size-MIN_LOOKAHEAD, "need lookahead");
do {
// Assert(cur_match < s->strstart, "no future");
match = cur_match;
/* Skip to next match if the match length cannot increase
* or if the match length is less than 2. Note that the checks below
* for insufficient lookahead only occur occasionally for performance
* reasons. Therefore uninitialized memory will be accessed, and
* conditional jumps will be made that depend on those values.
* However the length of the match is limited to the lookahead, so
* the output of deflate is not affected by the uninitialized values.
*/
if (_win[match + best_len] !== scan_end ||
_win[match + best_len - 1] !== scan_end1 ||
_win[match] !== _win[scan] ||
_win[++match] !== _win[scan + 1]) {
continue;
}
/* The check at best_len-1 can be removed because it will be made
* again later. (This heuristic is not always a win.)
* It is not necessary to compare scan[2] and match[2] since they
* are always equal when the other bytes match, given that
* the hash keys are equal and that HASH_BITS >= 8.
*/
scan += 2;
match++;
// Assert(*scan == *match, "match[2]?");
/* We check for insufficient lookahead only every 8th comparison;
* the 256th check will be made at strstart+258.
*/
do {
/*jshint noempty:false*/
} while (_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
_win[++scan] === _win[++match] && _win[++scan] === _win[++match] &&
scan < strend);
// Assert(scan <= s->window+(unsigned)(s->window_size-1), "wild scan");
len = MAX_MATCH - (strend - scan);
scan = strend - MAX_MATCH;
if (len > best_len) {
s.match_start = cur_match;
best_len = len;
if (len >= nice_match) {
break;
}
scan_end1 = _win[scan + best_len - 1];
scan_end = _win[scan + best_len];
}
} while ((cur_match = prev[cur_match & wmask]) > limit && --chain_length !== 0);
if (best_len <= s.lookahead) {
return best_len;
}
return s.lookahead;
}
/* ===========================================================================
* Fill the window when the lookahead becomes insufficient.
* Updates strstart and lookahead.
*
* IN assertion: lookahead < MIN_LOOKAHEAD
* OUT assertions: strstart <= window_size-MIN_LOOKAHEAD
* At least one byte has been read, or avail_in == 0; reads are
* performed for at least two bytes (required for the zip translate_eol
* option -- not supported here).
*/
function fill_window(s) {
var _w_size = s.w_size;
var p, n, m, more, str;
//Assert(s->lookahead < MIN_LOOKAHEAD, "already enough lookahead");
do {
more = s.window_size - s.lookahead - s.strstart;
// JS ints have 32 bit, block below not needed
/* Deal with !@#$% 64K limit: */
//if (sizeof(int) <= 2) {
// if (more == 0 && s->strstart == 0 && s->lookahead == 0) {
// more = wsize;
//
// } else if (more == (unsigned)(-1)) {
// /* Very unlikely, but possible on 16 bit machine if
// * strstart == 0 && lookahead == 1 (input done a byte at time)
// */
// more--;
// }
//}
/* If the window is almost full and there is insufficient lookahead,
* move the upper half to the lower one to make room in the upper half.
*/
if (s.strstart >= _w_size + (_w_size - MIN_LOOKAHEAD)) {
utils.arraySet(s.window, s.window, _w_size, _w_size, 0);
s.match_start -= _w_size;
s.strstart -= _w_size;
/* we now have strstart >= MAX_DIST */
s.block_start -= _w_size;
/* Slide the hash table (could be avoided with 32 bit values
at the expense of memory usage). We slide even when level == 0
to keep the hash table consistent if we switch back to level > 0
later. (Using level 0 permanently is not an optimal usage of
zlib, so we don't care about this pathological case.)
*/
n = s.hash_size;
p = n;
do {
m = s.head[--p];
s.head[p] = (m >= _w_size ? m - _w_size : 0);
} while (--n);
n = _w_size;
p = n;
do {
m = s.prev[--p];
s.prev[p] = (m >= _w_size ? m - _w_size : 0);
/* If n is not on any hash chain, prev[n] is garbage but
* its value will never be used.
*/
} while (--n);
more += _w_size;
}
if (s.strm.avail_in === 0) {
break;
}
/* If there was no sliding:
* strstart <= WSIZE+MAX_DIST-1 && lookahead <= MIN_LOOKAHEAD - 1 &&
* more == window_size - lookahead - strstart
* => more >= window_size - (MIN_LOOKAHEAD-1 + WSIZE + MAX_DIST-1)
* => more >= window_size - 2*WSIZE + 2
* In the BIG_MEM or MMAP case (not yet supported),
* window_size == input_size + MIN_LOOKAHEAD &&
* strstart + s->lookahead <= input_size => more >= MIN_LOOKAHEAD.
* Otherwise, window_size == 2*WSIZE so more >= 2.
* If there was sliding, more >= WSIZE. So in all cases, more >= 2.
*/
//Assert(more >= 2, "more < 2");
n = read_buf(s.strm, s.window, s.strstart + s.lookahead, more);
s.lookahead += n;
/* Initialize the hash value now that we have some input: */
if (s.lookahead + s.insert >= MIN_MATCH) {
str = s.strstart - s.insert;
s.ins_h = s.window[str];
/* UPDATE_HASH(s, s->ins_h, s->window[str + 1]); */
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + 1]) & s.hash_mask;
//#if MIN_MATCH != 3
// Call update_hash() MIN_MATCH-3 more times
//#endif
while (s.insert) {
/* UPDATE_HASH(s, s->ins_h, s->window[str + MIN_MATCH-1]); */
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[str + MIN_MATCH-1]) & s.hash_mask;
s.prev[str & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = str;
str++;
s.insert--;
if (s.lookahead + s.insert < MIN_MATCH) {
break;
}
}
}
/* If the whole input has less than MIN_MATCH bytes, ins_h is garbage,
* but this is not important since only literal bytes will be emitted.
*/
} while (s.lookahead < MIN_LOOKAHEAD && s.strm.avail_in !== 0);
/* If the WIN_INIT bytes after the end of the current data have never been
* written, then zero those bytes in order to avoid memory check reports of
* the use of uninitialized (or uninitialised as Julian writes) bytes by
* the longest match routines. Update the high water mark for the next
* time through here. WIN_INIT is set to MAX_MATCH since the longest match
* routines allow scanning to strstart + MAX_MATCH, ignoring lookahead.
*/
// if (s.high_water < s.window_size) {
// var curr = s.strstart + s.lookahead;
// var init = 0;
//
// if (s.high_water < curr) {
// /* Previous high water mark below current data -- zero WIN_INIT
// * bytes or up to end of window, whichever is less.
// */
// init = s.window_size - curr;
// if (init > WIN_INIT)
// init = WIN_INIT;
// zmemzero(s->window + curr, (unsigned)init);
// s->high_water = curr + init;
// }
// else if (s->high_water < (ulg)curr + WIN_INIT) {
// /* High water mark at or above current data, but below current data
// * plus WIN_INIT -- zero out to current data plus WIN_INIT, or up
// * to end of window, whichever is less.
// */
// init = (ulg)curr + WIN_INIT - s->high_water;
// if (init > s->window_size - s->high_water)
// init = s->window_size - s->high_water;
// zmemzero(s->window + s->high_water, (unsigned)init);
// s->high_water += init;
// }
// }
//
// Assert((ulg)s->strstart <= s->window_size - MIN_LOOKAHEAD,
// "not enough room for search");
}
/* ===========================================================================
* Copy without compression as much as possible from the input stream, return
* the current block state.
* This function does not insert new strings in the dictionary since
* uncompressible data is probably not useful. This function is used
* only for the level=0 compression option.
* NOTE: this function should be optimized to avoid extra copying from
* window to pending_buf.
*/
function deflate_stored(s, flush) {
/* Stored blocks are limited to 0xffff bytes, pending_buf is limited
* to pending_buf_size, and each stored block has a 5 byte header:
*/
var max_block_size = 0xffff;
if (max_block_size > s.pending_buf_size - 5) {
max_block_size = s.pending_buf_size - 5;
}
/* Copy as much as possible from input to output: */
for (;;) {
/* Fill the window as much as possible: */
if (s.lookahead <= 1) {
//Assert(s->strstart < s->w_size+MAX_DIST(s) ||
// s->block_start >= (long)s->w_size, "slide too late");
// if (!(s.strstart < s.w_size + (s.w_size - MIN_LOOKAHEAD) ||
// s.block_start >= s.w_size)) {
// throw new Error("slide too late");
// }
fill_window(s);
if (s.lookahead === 0 && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) {
break;
}
/* flush the current block */
}
//Assert(s->block_start >= 0L, "block gone");
// if (s.block_start < 0) throw new Error("block gone");
s.strstart += s.lookahead;
s.lookahead = 0;
/* Emit a stored block if pending_buf will be full: */
var max_start = s.block_start + max_block_size;
if (s.strstart === 0 || s.strstart >= max_start) {
/* strstart == 0 is possible when wraparound on 16-bit machine */
s.lookahead = s.strstart - max_start;
s.strstart = max_start;
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
/* Flush if we may have to slide, otherwise block_start may become
* negative and the data will be gone:
*/
if (s.strstart - s.block_start >= (s.w_size - MIN_LOOKAHEAD)) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.strstart > s.block_start) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_NEED_MORE;
}
/* ===========================================================================
* Compress as much as possible from the input stream, return the current
* block state.
* This function does not perform lazy evaluation of matches and inserts
* new strings in the dictionary only for unmatched strings or for short
* matches. It is used only for the fast compression options.
*/
function deflate_fast(s, flush) {
var hash_head; /* head of the hash chain */
var bflush; /* set if current block must be flushed */
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the next match, plus MIN_MATCH bytes to insert the
* string following the next match.
*/
if (s.lookahead < MIN_LOOKAHEAD) {
fill_window(s);
if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) {
break; /* flush the current block */
}
}
/* Insert the string window[strstart .. strstart+2] in the
* dictionary, and set hash_head to the head of the hash chain:
*/
hash_head = 0/*NIL*/;
if (s.lookahead >= MIN_MATCH) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
/* Find the longest match, discarding those <= prev_length.
* At this point we have always match_length < MIN_MATCH
*/
if (hash_head !== 0/*NIL*/ && ((s.strstart - hash_head) <= (s.w_size - MIN_LOOKAHEAD))) {
/* To simplify the code, we prevent matches with the string
* of window index 0 (in particular we have to avoid a match
* of the string with itself at the start of the input file).
*/
s.match_length = longest_match(s, hash_head);
/* longest_match() sets match_start */
}
if (s.match_length >= MIN_MATCH) {
// check_match(s, s.strstart, s.match_start, s.match_length); // for debug only
/*** _tr_tally_dist(s, s.strstart - s.match_start,
s.match_length - MIN_MATCH, bflush); ***/
bflush = trees._tr_tally(s, s.strstart - s.match_start, s.match_length - MIN_MATCH);
s.lookahead -= s.match_length;
/* Insert new strings in the hash table only if the match length
* is not too large. This saves time but degrades compression.
*/
if (s.match_length <= s.max_lazy_match/*max_insert_length*/ && s.lookahead >= MIN_MATCH) {
s.match_length--; /* string at strstart already in table */
do {
s.strstart++;
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
/* strstart never exceeds WSIZE-MAX_MATCH, so there are
* always MIN_MATCH bytes ahead.
*/
} while (--s.match_length !== 0);
s.strstart++;
} else
{
s.strstart += s.match_length;
s.match_length = 0;
s.ins_h = s.window[s.strstart];
/* UPDATE_HASH(s, s.ins_h, s.window[s.strstart+1]); */
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + 1]) & s.hash_mask;
//#if MIN_MATCH != 3
// Call UPDATE_HASH() MIN_MATCH-3 more times
//#endif
/* If lookahead < MIN_MATCH, ins_h is garbage, but it does not
* matter since it will be recomputed at next deflate call.
*/
}
} else {
/* No match, output a literal byte */
//Tracevv((stderr,"%c", s.window[s.strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
}
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = ((s.strstart < (MIN_MATCH-1)) ? s.strstart : MIN_MATCH-1);
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* ===========================================================================
* Same as above, but achieves better compression. We use a lazy
* evaluation for matches: a match is finally adopted only if there is
* no better match at the next window position.
*/
function deflate_slow(s, flush) {
var hash_head; /* head of hash chain */
var bflush; /* set if current block must be flushed */
var max_insert;
/* Process the input block. */
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the next match, plus MIN_MATCH bytes to insert the
* string following the next match.
*/
if (s.lookahead < MIN_LOOKAHEAD) {
fill_window(s);
if (s.lookahead < MIN_LOOKAHEAD && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) { break; } /* flush the current block */
}
/* Insert the string window[strstart .. strstart+2] in the
* dictionary, and set hash_head to the head of the hash chain:
*/
hash_head = 0/*NIL*/;
if (s.lookahead >= MIN_MATCH) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
/* Find the longest match, discarding those <= prev_length.
*/
s.prev_length = s.match_length;
s.prev_match = s.match_start;
s.match_length = MIN_MATCH-1;
if (hash_head !== 0/*NIL*/ && s.prev_length < s.max_lazy_match &&
s.strstart - hash_head <= (s.w_size-MIN_LOOKAHEAD)/*MAX_DIST(s)*/) {
/* To simplify the code, we prevent matches with the string
* of window index 0 (in particular we have to avoid a match
* of the string with itself at the start of the input file).
*/
s.match_length = longest_match(s, hash_head);
/* longest_match() sets match_start */
if (s.match_length <= 5 &&
(s.strategy === Z_FILTERED || (s.match_length === MIN_MATCH && s.strstart - s.match_start > 4096/*TOO_FAR*/))) {
/* If prev_match is also MIN_MATCH, match_start is garbage
* but we will ignore the current match anyway.
*/
s.match_length = MIN_MATCH-1;
}
}
/* If there was a match at the previous step and the current
* match is not better, output the previous match:
*/
if (s.prev_length >= MIN_MATCH && s.match_length <= s.prev_length) {
max_insert = s.strstart + s.lookahead - MIN_MATCH;
/* Do not insert strings in hash table beyond this. */
//check_match(s, s.strstart-1, s.prev_match, s.prev_length);
/***_tr_tally_dist(s, s.strstart - 1 - s.prev_match,
s.prev_length - MIN_MATCH, bflush);***/
bflush = trees._tr_tally(s, s.strstart - 1- s.prev_match, s.prev_length - MIN_MATCH);
/* Insert in hash table all strings up to the end of the match.
* strstart-1 and strstart are already inserted. If there is not
* enough lookahead, the last two strings are not inserted in
* the hash table.
*/
s.lookahead -= s.prev_length-1;
s.prev_length -= 2;
do {
if (++s.strstart <= max_insert) {
/*** INSERT_STRING(s, s.strstart, hash_head); ***/
s.ins_h = ((s.ins_h << s.hash_shift) ^ s.window[s.strstart + MIN_MATCH - 1]) & s.hash_mask;
hash_head = s.prev[s.strstart & s.w_mask] = s.head[s.ins_h];
s.head[s.ins_h] = s.strstart;
/***/
}
} while (--s.prev_length !== 0);
s.match_available = 0;
s.match_length = MIN_MATCH-1;
s.strstart++;
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
} else if (s.match_available) {
/* If there was no match at the previous position, output a
* single literal. If there was a match but the current match
* is longer, truncate the previous match to a single literal.
*/
//Tracevv((stderr,"%c", s->window[s->strstart-1]));
/*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
if (bflush) {
/*** FLUSH_BLOCK_ONLY(s, 0) ***/
flush_block_only(s, false);
/***/
}
s.strstart++;
s.lookahead--;
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
} else {
/* There is no previous match to compare with, wait for
* the next step to decide.
*/
s.match_available = 1;
s.strstart++;
s.lookahead--;
}
}
//Assert (flush != Z_NO_FLUSH, "no flush?");
if (s.match_available) {
//Tracevv((stderr,"%c", s->window[s->strstart-1]));
/*** _tr_tally_lit(s, s.window[s.strstart-1], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart-1]);
s.match_available = 0;
}
s.insert = s.strstart < MIN_MATCH-1 ? s.strstart : MIN_MATCH-1;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* ===========================================================================
* For Z_RLE, simply look for runs of bytes, generate matches only of distance
* one. Do not maintain a hash table. (It will be regenerated if this run of
* deflate switches away from Z_RLE.)
*/
function deflate_rle(s, flush) {
var bflush; /* set if current block must be flushed */
var prev; /* byte at distance one to match */
var scan, strend; /* scan goes up to strend for length of run */
var _win = s.window;
for (;;) {
/* Make sure that we always have enough lookahead, except
* at the end of the input file. We need MAX_MATCH bytes
* for the longest run, plus one for the unrolled loop.
*/
if (s.lookahead <= MAX_MATCH) {
fill_window(s);
if (s.lookahead <= MAX_MATCH && flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
if (s.lookahead === 0) { break; } /* flush the current block */
}
/* See how many times the previous byte repeats */
s.match_length = 0;
if (s.lookahead >= MIN_MATCH && s.strstart > 0) {
scan = s.strstart - 1;
prev = _win[scan];
if (prev === _win[++scan] && prev === _win[++scan] && prev === _win[++scan]) {
strend = s.strstart + MAX_MATCH;
do {
/*jshint noempty:false*/
} while (prev === _win[++scan] && prev === _win[++scan] &&
prev === _win[++scan] && prev === _win[++scan] &&
prev === _win[++scan] && prev === _win[++scan] &&
prev === _win[++scan] && prev === _win[++scan] &&
scan < strend);
s.match_length = MAX_MATCH - (strend - scan);
if (s.match_length > s.lookahead) {
s.match_length = s.lookahead;
}
}
//Assert(scan <= s->window+(uInt)(s->window_size-1), "wild scan");
}
/* Emit match if have run of MIN_MATCH or longer, else emit literal */
if (s.match_length >= MIN_MATCH) {
//check_match(s, s.strstart, s.strstart - 1, s.match_length);
/*** _tr_tally_dist(s, 1, s.match_length - MIN_MATCH, bflush); ***/
bflush = trees._tr_tally(s, 1, s.match_length - MIN_MATCH);
s.lookahead -= s.match_length;
s.strstart += s.match_length;
s.match_length = 0;
} else {
/* No match, output a literal byte */
//Tracevv((stderr,"%c", s->window[s->strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
}
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* ===========================================================================
* For Z_HUFFMAN_ONLY, do not look for matches. Do not maintain a hash table.
* (It will be regenerated if this run of deflate switches away from Huffman.)
*/
function deflate_huff(s, flush) {
var bflush; /* set if current block must be flushed */
for (;;) {
/* Make sure that we have a literal to write. */
if (s.lookahead === 0) {
fill_window(s);
if (s.lookahead === 0) {
if (flush === Z_NO_FLUSH) {
return BS_NEED_MORE;
}
break; /* flush the current block */
}
}
/* Output a literal byte */
s.match_length = 0;
//Tracevv((stderr,"%c", s->window[s->strstart]));
/*** _tr_tally_lit(s, s.window[s.strstart], bflush); ***/
bflush = trees._tr_tally(s, 0, s.window[s.strstart]);
s.lookahead--;
s.strstart++;
if (bflush) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
}
s.insert = 0;
if (flush === Z_FINISH) {
/*** FLUSH_BLOCK(s, 1); ***/
flush_block_only(s, true);
if (s.strm.avail_out === 0) {
return BS_FINISH_STARTED;
}
/***/
return BS_FINISH_DONE;
}
if (s.last_lit) {
/*** FLUSH_BLOCK(s, 0); ***/
flush_block_only(s, false);
if (s.strm.avail_out === 0) {
return BS_NEED_MORE;
}
/***/
}
return BS_BLOCK_DONE;
}
/* Values for max_lazy_match, good_match and max_chain_length, depending on
* the desired pack level (0..9). The values given below have been tuned to
* exclude worst case performance for pathological files. Better values may be
* found for specific files.
*/
var Config = function (good_length, max_lazy, nice_length, max_chain, func) {
this.good_length = good_length;
this.max_lazy = max_lazy;
this.nice_length = nice_length;
this.max_chain = max_chain;
this.func = func;
};
var configuration_table;
configuration_table = [
/* good lazy nice chain */
new Config(0, 0, 0, 0, deflate_stored), /* 0 store only */
new Config(4, 4, 8, 4, deflate_fast), /* 1 max speed, no lazy matches */
new Config(4, 5, 16, 8, deflate_fast), /* 2 */
new Config(4, 6, 32, 32, deflate_fast), /* 3 */
new Config(4, 4, 16, 16, deflate_slow), /* 4 lazy matches */
new Config(8, 16, 32, 32, deflate_slow), /* 5 */
new Config(8, 16, 128, 128, deflate_slow), /* 6 */
new Config(8, 32, 128, 256, deflate_slow), /* 7 */
new Config(32, 128, 258, 1024, deflate_slow), /* 8 */
new Config(32, 258, 258, 4096, deflate_slow) /* 9 max compression */
];
/* ===========================================================================
* Initialize the "longest match" routines for a new zlib stream
*/
function lm_init(s) {
s.window_size = 2 * s.w_size;
/*** CLEAR_HASH(s); ***/
zero(s.head); // Fill with NIL (= 0);
/* Set the default configuration parameters:
*/
s.max_lazy_match = configuration_table[s.level].max_lazy;
s.good_match = configuration_table[s.level].good_length;
s.nice_match = configuration_table[s.level].nice_length;
s.max_chain_length = configuration_table[s.level].max_chain;
s.strstart = 0;
s.block_start = 0;
s.lookahead = 0;
s.insert = 0;
s.match_length = s.prev_length = MIN_MATCH - 1;
s.match_available = 0;
s.ins_h = 0;
}
function DeflateState() {
this.strm = null; /* pointer back to this zlib stream */
this.status = 0; /* as the name implies */
this.pending_buf = null; /* output still pending */
this.pending_buf_size = 0; /* size of pending_buf */
this.pending_out = 0; /* next pending byte to output to the stream */
this.pending = 0; /* nb of bytes in the pending buffer */
this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
this.gzhead = null; /* gzip header information to write */
this.gzindex = 0; /* where in extra, name, or comment */
this.method = Z_DEFLATED; /* can only be DEFLATED */
this.last_flush = -1; /* value of flush param for previous deflate call */
this.w_size = 0; /* LZ77 window size (32K by default) */
this.w_bits = 0; /* log2(w_size) (8..16) */
this.w_mask = 0; /* w_size - 1 */
this.window = null;
/* Sliding window. Input bytes are read into the second half of the window,
* and move to the first half later to keep a dictionary of at least wSize
* bytes. With this organization, matches are limited to a distance of
* wSize-MAX_MATCH bytes, but this ensures that IO is always
* performed with a length multiple of the block size.
*/
this.window_size = 0;
/* Actual size of window: 2*wSize, except when the user input buffer
* is directly used as sliding window.
*/
this.prev = null;
/* Link to older string with same hash index. To limit the size of this
* array to 64K, this link is maintained only for the last 32K strings.
* An index in this array is thus a window index modulo 32K.
*/
this.head = null; /* Heads of the hash chains or NIL. */
this.ins_h = 0; /* hash index of string to be inserted */
this.hash_size = 0; /* number of elements in hash table */
this.hash_bits = 0; /* log2(hash_size) */
this.hash_mask = 0; /* hash_size-1 */
this.hash_shift = 0;
/* Number of bits by which ins_h must be shifted at each input
* step. It must be such that after MIN_MATCH steps, the oldest
* byte no longer takes part in the hash key, that is:
* hash_shift * MIN_MATCH >= hash_bits
*/
this.block_start = 0;
/* Window position at the beginning of the current output block. Gets
* negative when the window is moved backwards.
*/
this.match_length = 0; /* length of best match */
this.prev_match = 0; /* previous match */
this.match_available = 0; /* set if previous match exists */
this.strstart = 0; /* start of string to insert */
this.match_start = 0; /* start of matching string */
this.lookahead = 0; /* number of valid bytes ahead in window */
this.prev_length = 0;
/* Length of the best match at previous step. Matches not greater than this
* are discarded. This is used in the lazy match evaluation.
*/
this.max_chain_length = 0;
/* To speed up deflation, hash chains are never searched beyond this
* length. A higher limit improves compression ratio but degrades the
* speed.
*/
this.max_lazy_match = 0;
/* Attempt to find a better match only when the current match is strictly
* smaller than this value. This mechanism is used only for compression
* levels >= 4.
*/
// That's alias to max_lazy_match, don't use directly
//this.max_insert_length = 0;
/* Insert new strings in the hash table only if the match length is not
* greater than this length. This saves time but degrades compression.
* max_insert_length is used only for compression levels <= 3.
*/
this.level = 0; /* compression level (1..9) */
this.strategy = 0; /* favor or force Huffman coding*/
this.good_match = 0;
/* Use a faster search when the previous match is longer than this */
this.nice_match = 0; /* Stop searching when current match exceeds this */
/* used by trees.c: */
/* Didn't use ct_data typedef below to suppress compiler warning */
// struct ct_data_s dyn_ltree[HEAP_SIZE]; /* literal and length tree */
// struct ct_data_s dyn_dtree[2*D_CODES+1]; /* distance tree */
// struct ct_data_s bl_tree[2*BL_CODES+1]; /* Huffman tree for bit lengths */
// Use flat array of DOUBLE size, with interleaved fata,
// because JS does not support effective
this.dyn_ltree = new utils.Buf16(HEAP_SIZE * 2);
this.dyn_dtree = new utils.Buf16((2*D_CODES+1) * 2);
this.bl_tree = new utils.Buf16((2*BL_CODES+1) * 2);
zero(this.dyn_ltree);
zero(this.dyn_dtree);
zero(this.bl_tree);
this.l_desc = null; /* desc. for literal tree */
this.d_desc = null; /* desc. for distance tree */
this.bl_desc = null; /* desc. for bit length tree */
//ush bl_count[MAX_BITS+1];
this.bl_count = new utils.Buf16(MAX_BITS+1);
/* number of codes at each bit length for an optimal tree */
//int heap[2*L_CODES+1]; /* heap used to build the Huffman trees */
this.heap = new utils.Buf16(2*L_CODES+1); /* heap used to build the Huffman trees */
zero(this.heap);
this.heap_len = 0; /* number of elements in the heap */
this.heap_max = 0; /* element of largest frequency */
/* The sons of heap[n] are heap[2*n] and heap[2*n+1]. heap[0] is not used.
* The same heap array is used to build all trees.
*/
this.depth = new utils.Buf16(2*L_CODES+1); //uch depth[2*L_CODES+1];
zero(this.depth);
/* Depth of each subtree used as tie breaker for trees of equal frequency
*/
this.l_buf = 0; /* buffer index for literals or lengths */
this.lit_bufsize = 0;
/* Size of match buffer for literals/lengths. There are 4 reasons for
* limiting lit_bufsize to 64K:
* - frequencies can be kept in 16 bit counters
* - if compression is not successful for the first block, all input
* data is still in the window so we can still emit a stored block even
* when input comes from standard input. (This can also be done for
* all blocks if lit_bufsize is not greater than 32K.)
* - if compression is not successful for a file smaller than 64K, we can
* even emit a stored file instead of a stored block (saving 5 bytes).
* This is applicable only for zip (not gzip or zlib).
* - creating new Huffman trees less frequently may not provide fast
* adaptation to changes in the input data statistics. (Take for
* example a binary file with poorly compressible code followed by
* a highly compressible string table.) Smaller buffer sizes give
* fast adaptation but have of course the overhead of transmitting
* trees more frequently.
* - I can't count above 4
*/
this.last_lit = 0; /* running index in l_buf */
this.d_buf = 0;
/* Buffer index for distances. To simplify the code, d_buf and l_buf have
* the same number of elements. To use different lengths, an extra flag
* array would be necessary.
*/
this.opt_len = 0; /* bit length of current block with optimal trees */
this.static_len = 0; /* bit length of current block with static trees */
this.matches = 0; /* number of string matches in current block */
this.insert = 0; /* bytes at end of window left to insert */
this.bi_buf = 0;
/* Output buffer. bits are inserted starting at the bottom (least
* significant bits).
*/
this.bi_valid = 0;
/* Number of valid bits in bi_buf. All bits above the last valid bit
* are always zero.
*/
// Used for window memory init. We safely ignore it for JS. That makes
// sense only for pointers and memory check tools.
//this.high_water = 0;
/* High water mark offset in window for initialized bytes -- bytes above
* this are set to zero in order to avoid memory check warnings when
* longest match routines access bytes past the input. This is then
* updated to the new high water mark.
*/
}
function deflateResetKeep(strm) {
var s;
if (!strm || !strm.state) {
return err(strm, Z_STREAM_ERROR);
}
strm.total_in = strm.total_out = 0;
strm.data_type = Z_UNKNOWN;
s = strm.state;
s.pending = 0;
s.pending_out = 0;
if (s.wrap < 0) {
s.wrap = -s.wrap;
/* was made negative by deflate(..., Z_FINISH); */
}
s.status = (s.wrap ? INIT_STATE : BUSY_STATE);
strm.adler = (s.wrap === 2) ?
0 // crc32(0, Z_NULL, 0)
:
1; // adler32(0, Z_NULL, 0)
s.last_flush = Z_NO_FLUSH;
trees._tr_init(s);
return Z_OK;
}
function deflateReset(strm) {
var ret = deflateResetKeep(strm);
if (ret === Z_OK) {
lm_init(strm.state);
}
return ret;
}
function deflateSetHeader(strm, head) {
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
if (strm.state.wrap !== 2) { return Z_STREAM_ERROR; }
strm.state.gzhead = head;
return Z_OK;
}
function deflateInit2(strm, level, method, windowBits, memLevel, strategy) {
if (!strm) { // === Z_NULL
return Z_STREAM_ERROR;
}
var wrap = 1;
if (level === Z_DEFAULT_COMPRESSION) {
level = 6;
}
if (windowBits < 0) { /* suppress zlib wrapper */
wrap = 0;
windowBits = -windowBits;
}
else if (windowBits > 15) {
wrap = 2; /* write gzip wrapper instead */
windowBits -= 16;
}
if (memLevel < 1 || memLevel > MAX_MEM_LEVEL || method !== Z_DEFLATED ||
windowBits < 8 || windowBits > 15 || level < 0 || level > 9 ||
strategy < 0 || strategy > Z_FIXED) {
return err(strm, Z_STREAM_ERROR);
}
if (windowBits === 8) {
windowBits = 9;
}
/* until 256-byte window bug fixed */
var s = new DeflateState();
strm.state = s;
s.strm = strm;
s.wrap = wrap;
s.gzhead = null;
s.w_bits = windowBits;
s.w_size = 1 << s.w_bits;
s.w_mask = s.w_size - 1;
s.hash_bits = memLevel + 7;
s.hash_size = 1 << s.hash_bits;
s.hash_mask = s.hash_size - 1;
s.hash_shift = ~~((s.hash_bits + MIN_MATCH - 1) / MIN_MATCH);
s.window = new utils.Buf8(s.w_size * 2);
s.head = new utils.Buf16(s.hash_size);
s.prev = new utils.Buf16(s.w_size);
// Don't need mem init magic for JS.
//s.high_water = 0; /* nothing written to s->window yet */
s.lit_bufsize = 1 << (memLevel + 6); /* 16K elements by default */
s.pending_buf_size = s.lit_bufsize * 4;
s.pending_buf = new utils.Buf8(s.pending_buf_size);
s.d_buf = s.lit_bufsize >> 1;
s.l_buf = (1 + 2) * s.lit_bufsize;
s.level = level;
s.strategy = strategy;
s.method = method;
return deflateReset(strm);
}
function deflateInit(strm, level) {
return deflateInit2(strm, level, Z_DEFLATED, MAX_WBITS, DEF_MEM_LEVEL, Z_DEFAULT_STRATEGY);
}
function deflate(strm, flush) {
var old_flush, s;
var beg, val; // for gzip header write only
if (!strm || !strm.state ||
flush > Z_BLOCK || flush < 0) {
return strm ? err(strm, Z_STREAM_ERROR) : Z_STREAM_ERROR;
}
s = strm.state;
if (!strm.output ||
(!strm.input && strm.avail_in !== 0) ||
(s.status === FINISH_STATE && flush !== Z_FINISH)) {
return err(strm, (strm.avail_out === 0) ? Z_BUF_ERROR : Z_STREAM_ERROR);
}
s.strm = strm; /* just in case */
old_flush = s.last_flush;
s.last_flush = flush;
/* Write the header */
if (s.status === INIT_STATE) {
if (s.wrap === 2) { // GZIP header
strm.adler = 0; //crc32(0L, Z_NULL, 0);
put_byte(s, 31);
put_byte(s, 139);
put_byte(s, 8);
if (!s.gzhead) { // s->gzhead == Z_NULL
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, 0);
put_byte(s, s.level === 9 ? 2 :
(s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
4 : 0));
put_byte(s, OS_CODE);
s.status = BUSY_STATE;
}
else {
put_byte(s, (s.gzhead.text ? 1 : 0) +
(s.gzhead.hcrc ? 2 : 0) +
(!s.gzhead.extra ? 0 : 4) +
(!s.gzhead.name ? 0 : 8) +
(!s.gzhead.comment ? 0 : 16)
);
put_byte(s, s.gzhead.time & 0xff);
put_byte(s, (s.gzhead.time >> 8) & 0xff);
put_byte(s, (s.gzhead.time >> 16) & 0xff);
put_byte(s, (s.gzhead.time >> 24) & 0xff);
put_byte(s, s.level === 9 ? 2 :
(s.strategy >= Z_HUFFMAN_ONLY || s.level < 2 ?
4 : 0));
put_byte(s, s.gzhead.os & 0xff);
if (s.gzhead.extra && s.gzhead.extra.length) {
put_byte(s, s.gzhead.extra.length & 0xff);
put_byte(s, (s.gzhead.extra.length >> 8) & 0xff);
}
if (s.gzhead.hcrc) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending, 0);
}
s.gzindex = 0;
s.status = EXTRA_STATE;
}
}
else // DEFLATE header
{
var header = (Z_DEFLATED + ((s.w_bits - 8) << 4)) << 8;
var level_flags = -1;
if (s.strategy >= Z_HUFFMAN_ONLY || s.level < 2) {
level_flags = 0;
} else if (s.level < 6) {
level_flags = 1;
} else if (s.level === 6) {
level_flags = 2;
} else {
level_flags = 3;
}
header |= (level_flags << 6);
if (s.strstart !== 0) { header |= PRESET_DICT; }
header += 31 - (header % 31);
s.status = BUSY_STATE;
putShortMSB(s, header);
/* Save the adler32 of the preset dictionary: */
if (s.strstart !== 0) {
putShortMSB(s, strm.adler >>> 16);
putShortMSB(s, strm.adler & 0xffff);
}
strm.adler = 1; // adler32(0L, Z_NULL, 0);
}
}
//#ifdef GZIP
if (s.status === EXTRA_STATE) {
if (s.gzhead.extra/* != Z_NULL*/) {
beg = s.pending; /* start of bytes to update crc */
while (s.gzindex < (s.gzhead.extra.length & 0xffff)) {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
break;
}
}
put_byte(s, s.gzhead.extra[s.gzindex] & 0xff);
s.gzindex++;
}
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (s.gzindex === s.gzhead.extra.length) {
s.gzindex = 0;
s.status = NAME_STATE;
}
}
else {
s.status = NAME_STATE;
}
}
if (s.status === NAME_STATE) {
if (s.gzhead.name/* != Z_NULL*/) {
beg = s.pending; /* start of bytes to update crc */
//int val;
do {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
val = 1;
break;
}
}
// JS specific: little magic to add zero terminator to end of string
if (s.gzindex < s.gzhead.name.length) {
val = s.gzhead.name.charCodeAt(s.gzindex++) & 0xff;
} else {
val = 0;
}
put_byte(s, val);
} while (val !== 0);
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (val === 0) {
s.gzindex = 0;
s.status = COMMENT_STATE;
}
}
else {
s.status = COMMENT_STATE;
}
}
if (s.status === COMMENT_STATE) {
if (s.gzhead.comment/* != Z_NULL*/) {
beg = s.pending; /* start of bytes to update crc */
//int val;
do {
if (s.pending === s.pending_buf_size) {
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
flush_pending(strm);
beg = s.pending;
if (s.pending === s.pending_buf_size) {
val = 1;
break;
}
}
// JS specific: little magic to add zero terminator to end of string
if (s.gzindex < s.gzhead.comment.length) {
val = s.gzhead.comment.charCodeAt(s.gzindex++) & 0xff;
} else {
val = 0;
}
put_byte(s, val);
} while (val !== 0);
if (s.gzhead.hcrc && s.pending > beg) {
strm.adler = crc32(strm.adler, s.pending_buf, s.pending - beg, beg);
}
if (val === 0) {
s.status = HCRC_STATE;
}
}
else {
s.status = HCRC_STATE;
}
}
if (s.status === HCRC_STATE) {
if (s.gzhead.hcrc) {
if (s.pending + 2 > s.pending_buf_size) {
flush_pending(strm);
}
if (s.pending + 2 <= s.pending_buf_size) {
put_byte(s, strm.adler & 0xff);
put_byte(s, (strm.adler >> 8) & 0xff);
strm.adler = 0; //crc32(0L, Z_NULL, 0);
s.status = BUSY_STATE;
}
}
else {
s.status = BUSY_STATE;
}
}
//#endif
/* Flush as much pending output as possible */
if (s.pending !== 0) {
flush_pending(strm);
if (strm.avail_out === 0) {
/* Since avail_out is 0, deflate will be called again with
* more output space, but possibly with both pending and
* avail_in equal to zero. There won't be anything to do,
* but this is not an error situation so make sure we
* return OK instead of BUF_ERROR at next call of deflate:
*/
s.last_flush = -1;
return Z_OK;
}
/* Make sure there is something to do and avoid duplicate consecutive
* flushes. For repeated and useless calls with Z_FINISH, we keep
* returning Z_STREAM_END instead of Z_BUF_ERROR.
*/
} else if (strm.avail_in === 0 && rank(flush) <= rank(old_flush) &&
flush !== Z_FINISH) {
return err(strm, Z_BUF_ERROR);
}
/* User must not provide more input after the first FINISH: */
if (s.status === FINISH_STATE && strm.avail_in !== 0) {
return err(strm, Z_BUF_ERROR);
}
/* Start a new block or continue the current one.
*/
if (strm.avail_in !== 0 || s.lookahead !== 0 ||
(flush !== Z_NO_FLUSH && s.status !== FINISH_STATE)) {
var bstate = (s.strategy === Z_HUFFMAN_ONLY) ? deflate_huff(s, flush) :
(s.strategy === Z_RLE ? deflate_rle(s, flush) :
configuration_table[s.level].func(s, flush));
if (bstate === BS_FINISH_STARTED || bstate === BS_FINISH_DONE) {
s.status = FINISH_STATE;
}
if (bstate === BS_NEED_MORE || bstate === BS_FINISH_STARTED) {
if (strm.avail_out === 0) {
s.last_flush = -1;
/* avoid BUF_ERROR next call, see above */
}
return Z_OK;
/* If flush != Z_NO_FLUSH && avail_out == 0, the next call
* of deflate should use the same flush parameter to make sure
* that the flush is complete. So we don't have to output an
* empty block here, this will be done at next call. This also
* ensures that for a very small output buffer, we emit at most
* one empty block.
*/
}
if (bstate === BS_BLOCK_DONE) {
if (flush === Z_PARTIAL_FLUSH) {
trees._tr_align(s);
}
else if (flush !== Z_BLOCK) { /* FULL_FLUSH or SYNC_FLUSH */
trees._tr_stored_block(s, 0, 0, false);
/* For a full flush, this empty block will be recognized
* as a special marker by inflate_sync().
*/
if (flush === Z_FULL_FLUSH) {
/*** CLEAR_HASH(s); ***/ /* forget history */
zero(s.head); // Fill with NIL (= 0);
if (s.lookahead === 0) {
s.strstart = 0;
s.block_start = 0;
s.insert = 0;
}
}
}
flush_pending(strm);
if (strm.avail_out === 0) {
s.last_flush = -1; /* avoid BUF_ERROR at next call, see above */
return Z_OK;
}
}
}
//Assert(strm->avail_out > 0, "bug2");
//if (strm.avail_out <= 0) { throw new Error("bug2");}
if (flush !== Z_FINISH) { return Z_OK; }
if (s.wrap <= 0) { return Z_STREAM_END; }
/* Write the trailer */
if (s.wrap === 2) {
put_byte(s, strm.adler & 0xff);
put_byte(s, (strm.adler >> 8) & 0xff);
put_byte(s, (strm.adler >> 16) & 0xff);
put_byte(s, (strm.adler >> 24) & 0xff);
put_byte(s, strm.total_in & 0xff);
put_byte(s, (strm.total_in >> 8) & 0xff);
put_byte(s, (strm.total_in >> 16) & 0xff);
put_byte(s, (strm.total_in >> 24) & 0xff);
}
else
{
putShortMSB(s, strm.adler >>> 16);
putShortMSB(s, strm.adler & 0xffff);
}
flush_pending(strm);
/* If avail_out is zero, the application will call deflate again
* to flush the rest.
*/
if (s.wrap > 0) { s.wrap = -s.wrap; }
/* write the trailer only once! */
return s.pending !== 0 ? Z_OK : Z_STREAM_END;
}
function deflateEnd(strm) {
var status;
if (!strm/*== Z_NULL*/ || !strm.state/*== Z_NULL*/) {
return Z_STREAM_ERROR;
}
status = strm.state.status;
if (status !== INIT_STATE &&
status !== EXTRA_STATE &&
status !== NAME_STATE &&
status !== COMMENT_STATE &&
status !== HCRC_STATE &&
status !== BUSY_STATE &&
status !== FINISH_STATE
) {
return err(strm, Z_STREAM_ERROR);
}
strm.state = null;
return status === BUSY_STATE ? err(strm, Z_DATA_ERROR) : Z_OK;
}
/* =========================================================================
* Copy the source state to the destination state
*/
//function deflateCopy(dest, source) {
//
//}
exports.deflateInit = deflateInit;
exports.deflateInit2 = deflateInit2;
exports.deflateReset = deflateReset;
exports.deflateResetKeep = deflateResetKeep;
exports.deflateSetHeader = deflateSetHeader;
exports.deflate = deflate;
exports.deflateEnd = deflateEnd;
exports.deflateInfo = 'pako deflate (from Nodeca project)';
/* Not implemented
exports.deflateBound = deflateBound;
exports.deflateCopy = deflateCopy;
exports.deflateSetDictionary = deflateSetDictionary;
exports.deflateParams = deflateParams;
exports.deflatePending = deflatePending;
exports.deflatePrime = deflatePrime;
exports.deflateTune = deflateTune;
*/
},{"../utils/common":86,"./adler32":88,"./crc32":90,"./messages":96,"./trees":97}],92:[function(_dereq_,module,exports){
'use strict';
function GZheader() {
/* true if compressed data believed to be text */
this.text = 0;
/* modification time */
this.time = 0;
/* extra flags (not used when writing a gzip file) */
this.xflags = 0;
/* operating system */
this.os = 0;
/* pointer to extra field or Z_NULL if none */
this.extra = null;
/* extra field length (valid if extra != Z_NULL) */
this.extra_len = 0; // Actually, we don't need it in JS,
// but leave for few code modifications
//
// Setup limits is not necessary because in js we should not preallocate memory
// for inflate use constant limit in 65536 bytes
//
/* space at extra (only when reading header) */
// this.extra_max = 0;
/* pointer to zero-terminated file name or Z_NULL */
this.name = '';
/* space at name (only when reading header) */
// this.name_max = 0;
/* pointer to zero-terminated comment or Z_NULL */
this.comment = '';
/* space at comment (only when reading header) */
// this.comm_max = 0;
/* true if there was or will be a header crc */
this.hcrc = 0;
/* true when done reading gzip header (not used when writing a gzip file) */
this.done = false;
}
module.exports = GZheader;
},{}],93:[function(_dereq_,module,exports){
'use strict';
// See state defs from inflate.js
var BAD = 30; /* got a data error -- remain here until reset */
var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
/*
Decode literal, length, and distance codes and write out the resulting
literal and match bytes until either not enough input or output is
available, an end-of-block is encountered, or a data error is encountered.
When large enough input and output buffers are supplied to inflate(), for
example, a 16K input buffer and a 64K output buffer, more than 95% of the
inflate execution time is spent in this routine.
Entry assumptions:
state.mode === LEN
strm.avail_in >= 6
strm.avail_out >= 258
start >= strm.avail_out
state.bits < 8
On return, state.mode is one of:
LEN -- ran out of enough output space or enough available input
TYPE -- reached end of block code, inflate() to interpret next block
BAD -- error in block data
Notes:
- The maximum input bits used by a length/distance pair is 15 bits for the
length code, 5 bits for the length extra, 15 bits for the distance code,
and 13 bits for the distance extra. This totals 48 bits, or six bytes.
Therefore if strm.avail_in >= 6, then there is enough input to avoid
checking for available input while decoding.
- The maximum bytes that a single length/distance pair can output is 258
bytes, which is the maximum length that can be coded. inflate_fast()
requires strm.avail_out >= 258 for each loop to avoid checking for
output space.
*/
module.exports = function inflate_fast(strm, start) {
var state;
var _in; /* local strm.input */
var last; /* have enough input while in < last */
var _out; /* local strm.output */
var beg; /* inflate()'s initial strm.output */
var end; /* while out < end, enough space available */
//#ifdef INFLATE_STRICT
var dmax; /* maximum distance from zlib header */
//#endif
var wsize; /* window size or zero if not using window */
var whave; /* valid bytes in the window */
var wnext; /* window write index */
// Use `s_window` instead `window`, avoid conflict with instrumentation tools
var s_window; /* allocated sliding window, if wsize != 0 */
var hold; /* local strm.hold */
var bits; /* local strm.bits */
var lcode; /* local strm.lencode */
var dcode; /* local strm.distcode */
var lmask; /* mask for first level of length codes */
var dmask; /* mask for first level of distance codes */
var here; /* retrieved table entry */
var op; /* code bits, operation, extra bits, or */
/* window position, window bytes to copy */
var len; /* match length, unused bytes */
var dist; /* match distance */
var from; /* where to copy match from */
var from_source;
var input, output; // JS specific, because we have no pointers
/* copy state to local variables */
state = strm.state;
//here = state.here;
_in = strm.next_in;
input = strm.input;
last = _in + (strm.avail_in - 5);
_out = strm.next_out;
output = strm.output;
beg = _out - (start - strm.avail_out);
end = _out + (strm.avail_out - 257);
//#ifdef INFLATE_STRICT
dmax = state.dmax;
//#endif
wsize = state.wsize;
whave = state.whave;
wnext = state.wnext;
s_window = state.window;
hold = state.hold;
bits = state.bits;
lcode = state.lencode;
dcode = state.distcode;
lmask = (1 << state.lenbits) - 1;
dmask = (1 << state.distbits) - 1;
/* decode literals and length/distances until end-of-block or not enough
input data or output space */
top:
do {
if (bits < 15) {
hold += input[_in++] << bits;
bits += 8;
hold += input[_in++] << bits;
bits += 8;
}
here = lcode[hold & lmask];
dolen:
for (;;) { // Goto emulation
op = here >>> 24/*here.bits*/;
hold >>>= op;
bits -= op;
op = (here >>> 16) & 0xff/*here.op*/;
if (op === 0) { /* literal */
//Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
// "inflate: literal '%c'\n" :
// "inflate: literal 0x%02x\n", here.val));
output[_out++] = here & 0xffff/*here.val*/;
}
else if (op & 16) { /* length base */
len = here & 0xffff/*here.val*/;
op &= 15; /* number of extra bits */
if (op) {
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
}
len += hold & ((1 << op) - 1);
hold >>>= op;
bits -= op;
}
//Tracevv((stderr, "inflate: length %u\n", len));
if (bits < 15) {
hold += input[_in++] << bits;
bits += 8;
hold += input[_in++] << bits;
bits += 8;
}
here = dcode[hold & dmask];
dodist:
for (;;) { // goto emulation
op = here >>> 24/*here.bits*/;
hold >>>= op;
bits -= op;
op = (here >>> 16) & 0xff/*here.op*/;
if (op & 16) { /* distance base */
dist = here & 0xffff/*here.val*/;
op &= 15; /* number of extra bits */
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
if (bits < op) {
hold += input[_in++] << bits;
bits += 8;
}
}
dist += hold & ((1 << op) - 1);
//#ifdef INFLATE_STRICT
if (dist > dmax) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break top;
}
//#endif
hold >>>= op;
bits -= op;
//Tracevv((stderr, "inflate: distance %u\n", dist));
op = _out - beg; /* max distance in output */
if (dist > op) { /* see if copy from window */
op = dist - op; /* distance back in window */
if (op > whave) {
if (state.sane) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break top;
}
// (!) This block is disabled in zlib defailts,
// don't enable it for binary compatibility
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
// if (len <= op - whave) {
// do {
// output[_out++] = 0;
// } while (--len);
// continue top;
// }
// len -= op - whave;
// do {
// output[_out++] = 0;
// } while (--op > whave);
// if (op === 0) {
// from = _out - dist;
// do {
// output[_out++] = output[from++];
// } while (--len);
// continue top;
// }
//#endif
}
from = 0; // window index
from_source = s_window;
if (wnext === 0) { /* very common case */
from += wsize - op;
if (op < len) { /* some from window */
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
else if (wnext < op) { /* wrap around window */
from += wsize + wnext - op;
op -= wnext;
if (op < len) { /* some from end of window */
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = 0;
if (wnext < len) { /* some from start of window */
op = wnext;
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
}
else { /* contiguous in window */
from += wnext - op;
if (op < len) { /* some from window */
len -= op;
do {
output[_out++] = s_window[from++];
} while (--op);
from = _out - dist; /* rest from output */
from_source = output;
}
}
while (len > 2) {
output[_out++] = from_source[from++];
output[_out++] = from_source[from++];
output[_out++] = from_source[from++];
len -= 3;
}
if (len) {
output[_out++] = from_source[from++];
if (len > 1) {
output[_out++] = from_source[from++];
}
}
}
else {
from = _out - dist; /* copy direct from output */
do { /* minimum length is three */
output[_out++] = output[from++];
output[_out++] = output[from++];
output[_out++] = output[from++];
len -= 3;
} while (len > 2);
if (len) {
output[_out++] = output[from++];
if (len > 1) {
output[_out++] = output[from++];
}
}
}
}
else if ((op & 64) === 0) { /* 2nd level distance code */
here = dcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
continue dodist;
}
else {
strm.msg = 'invalid distance code';
state.mode = BAD;
break top;
}
break; // need to emulate goto via "continue"
}
}
else if ((op & 64) === 0) { /* 2nd level length code */
here = lcode[(here & 0xffff)/*here.val*/ + (hold & ((1 << op) - 1))];
continue dolen;
}
else if (op & 32) { /* end-of-block */
//Tracevv((stderr, "inflate: end of block\n"));
state.mode = TYPE;
break top;
}
else {
strm.msg = 'invalid literal/length code';
state.mode = BAD;
break top;
}
break; // need to emulate goto via "continue"
}
} while (_in < last && _out < end);
/* return unused bytes (on entry, bits < 8, so in won't go too far back) */
len = bits >> 3;
_in -= len;
bits -= len << 3;
hold &= (1 << bits) - 1;
/* update state and return */
strm.next_in = _in;
strm.next_out = _out;
strm.avail_in = (_in < last ? 5 + (last - _in) : 5 - (_in - last));
strm.avail_out = (_out < end ? 257 + (end - _out) : 257 - (_out - end));
state.hold = hold;
state.bits = bits;
return;
};
},{}],94:[function(_dereq_,module,exports){
'use strict';
var utils = _dereq_('../utils/common');
var adler32 = _dereq_('./adler32');
var crc32 = _dereq_('./crc32');
var inflate_fast = _dereq_('./inffast');
var inflate_table = _dereq_('./inftrees');
var CODES = 0;
var LENS = 1;
var DISTS = 2;
/* Public constants ==========================================================*/
/* ===========================================================================*/
/* Allowed flush values; see deflate() and inflate() below for details */
//var Z_NO_FLUSH = 0;
//var Z_PARTIAL_FLUSH = 1;
//var Z_SYNC_FLUSH = 2;
//var Z_FULL_FLUSH = 3;
var Z_FINISH = 4;
var Z_BLOCK = 5;
var Z_TREES = 6;
/* Return codes for the compression/decompression functions. Negative values
* are errors, positive values are used for special but normal events.
*/
var Z_OK = 0;
var Z_STREAM_END = 1;
var Z_NEED_DICT = 2;
//var Z_ERRNO = -1;
var Z_STREAM_ERROR = -2;
var Z_DATA_ERROR = -3;
var Z_MEM_ERROR = -4;
var Z_BUF_ERROR = -5;
//var Z_VERSION_ERROR = -6;
/* The deflate compression method */
var Z_DEFLATED = 8;
/* STATES ====================================================================*/
/* ===========================================================================*/
var HEAD = 1; /* i: waiting for magic header */
var FLAGS = 2; /* i: waiting for method and flags (gzip) */
var TIME = 3; /* i: waiting for modification time (gzip) */
var OS = 4; /* i: waiting for extra flags and operating system (gzip) */
var EXLEN = 5; /* i: waiting for extra length (gzip) */
var EXTRA = 6; /* i: waiting for extra bytes (gzip) */
var NAME = 7; /* i: waiting for end of file name (gzip) */
var COMMENT = 8; /* i: waiting for end of comment (gzip) */
var HCRC = 9; /* i: waiting for header crc (gzip) */
var DICTID = 10; /* i: waiting for dictionary check value */
var DICT = 11; /* waiting for inflateSetDictionary() call */
var TYPE = 12; /* i: waiting for type bits, including last-flag bit */
var TYPEDO = 13; /* i: same, but skip check to exit inflate on new block */
var STORED = 14; /* i: waiting for stored size (length and complement) */
var COPY_ = 15; /* i/o: same as COPY below, but only first time in */
var COPY = 16; /* i/o: waiting for input or output to copy stored block */
var TABLE = 17; /* i: waiting for dynamic block table lengths */
var LENLENS = 18; /* i: waiting for code length code lengths */
var CODELENS = 19; /* i: waiting for length/lit and distance code lengths */
var LEN_ = 20; /* i: same as LEN below, but only first time in */
var LEN = 21; /* i: waiting for length/lit/eob code */
var LENEXT = 22; /* i: waiting for length extra bits */
var DIST = 23; /* i: waiting for distance code */
var DISTEXT = 24; /* i: waiting for distance extra bits */
var MATCH = 25; /* o: waiting for output space to copy string */
var LIT = 26; /* o: waiting for output space to write literal */
var CHECK = 27; /* i: waiting for 32-bit check value */
var LENGTH = 28; /* i: waiting for 32-bit length (gzip) */
var DONE = 29; /* finished check, done -- remain here until reset */
var BAD = 30; /* got a data error -- remain here until reset */
var MEM = 31; /* got an inflate() memory error -- remain here until reset */
var SYNC = 32; /* looking for synchronization bytes to restart inflate() */
/* ===========================================================================*/
var ENOUGH_LENS = 852;
var ENOUGH_DISTS = 592;
//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
var MAX_WBITS = 15;
/* 32K LZ77 window */
var DEF_WBITS = MAX_WBITS;
function ZSWAP32(q) {
return (((q >>> 24) & 0xff) +
((q >>> 8) & 0xff00) +
((q & 0xff00) << 8) +
((q & 0xff) << 24));
}
function InflateState() {
this.mode = 0; /* current inflate mode */
this.last = false; /* true if processing last block */
this.wrap = 0; /* bit 0 true for zlib, bit 1 true for gzip */
this.havedict = false; /* true if dictionary provided */
this.flags = 0; /* gzip header method and flags (0 if zlib) */
this.dmax = 0; /* zlib header max distance (INFLATE_STRICT) */
this.check = 0; /* protected copy of check value */
this.total = 0; /* protected copy of output count */
// TODO: may be {}
this.head = null; /* where to save gzip header information */
/* sliding window */
this.wbits = 0; /* log base 2 of requested window size */
this.wsize = 0; /* window size or zero if not using window */
this.whave = 0; /* valid bytes in the window */
this.wnext = 0; /* window write index */
this.window = null; /* allocated sliding window, if needed */
/* bit accumulator */
this.hold = 0; /* input bit accumulator */
this.bits = 0; /* number of bits in "in" */
/* for string and stored block copying */
this.length = 0; /* literal or length of data to copy */
this.offset = 0; /* distance back to copy string from */
/* for table and code decoding */
this.extra = 0; /* extra bits needed */
/* fixed and dynamic code tables */
this.lencode = null; /* starting table for length/literal codes */
this.distcode = null; /* starting table for distance codes */
this.lenbits = 0; /* index bits for lencode */
this.distbits = 0; /* index bits for distcode */
/* dynamic table building */
this.ncode = 0; /* number of code length code lengths */
this.nlen = 0; /* number of length code lengths */
this.ndist = 0; /* number of distance code lengths */
this.have = 0; /* number of code lengths in lens[] */
this.next = null; /* next available space in codes[] */
this.lens = new utils.Buf16(320); /* temporary storage for code lengths */
this.work = new utils.Buf16(288); /* work area for code table building */
/*
because we don't have pointers in js, we use lencode and distcode directly
as buffers so we don't need codes
*/
//this.codes = new utils.Buf32(ENOUGH); /* space for code tables */
this.lendyn = null; /* dynamic table for length/literal codes (JS specific) */
this.distdyn = null; /* dynamic table for distance codes (JS specific) */
this.sane = 0; /* if false, allow invalid distance too far */
this.back = 0; /* bits back of last unprocessed length/lit */
this.was = 0; /* initial length of match */
}
function inflateResetKeep(strm) {
var state;
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
strm.total_in = strm.total_out = state.total = 0;
strm.msg = ''; /*Z_NULL*/
if (state.wrap) { /* to support ill-conceived Java test suite */
strm.adler = state.wrap & 1;
}
state.mode = HEAD;
state.last = 0;
state.havedict = 0;
state.dmax = 32768;
state.head = null/*Z_NULL*/;
state.hold = 0;
state.bits = 0;
//state.lencode = state.distcode = state.next = state.codes;
state.lencode = state.lendyn = new utils.Buf32(ENOUGH_LENS);
state.distcode = state.distdyn = new utils.Buf32(ENOUGH_DISTS);
state.sane = 1;
state.back = -1;
//Tracev((stderr, "inflate: reset\n"));
return Z_OK;
}
function inflateReset(strm) {
var state;
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
state.wsize = 0;
state.whave = 0;
state.wnext = 0;
return inflateResetKeep(strm);
}
function inflateReset2(strm, windowBits) {
var wrap;
var state;
/* get the state */
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
/* extract wrap request from windowBits parameter */
if (windowBits < 0) {
wrap = 0;
windowBits = -windowBits;
}
else {
wrap = (windowBits >> 4) + 1;
if (windowBits < 48) {
windowBits &= 15;
}
}
/* set number of window bits, free window if different */
if (windowBits && (windowBits < 8 || windowBits > 15)) {
return Z_STREAM_ERROR;
}
if (state.window !== null && state.wbits !== windowBits) {
state.window = null;
}
/* update state and reset the rest of it */
state.wrap = wrap;
state.wbits = windowBits;
return inflateReset(strm);
}
function inflateInit2(strm, windowBits) {
var ret;
var state;
if (!strm) { return Z_STREAM_ERROR; }
//strm.msg = Z_NULL; /* in case we return an error */
state = new InflateState();
//if (state === Z_NULL) return Z_MEM_ERROR;
//Tracev((stderr, "inflate: allocated\n"));
strm.state = state;
state.window = null/*Z_NULL*/;
ret = inflateReset2(strm, windowBits);
if (ret !== Z_OK) {
strm.state = null/*Z_NULL*/;
}
return ret;
}
function inflateInit(strm) {
return inflateInit2(strm, DEF_WBITS);
}
/*
Return state with length and distance decoding tables and index sizes set to
fixed code decoding. Normally this returns fixed tables from inffixed.h.
If BUILDFIXED is defined, then instead this routine builds the tables the
first time it's called, and returns those tables the first time and
thereafter. This reduces the size of the code by about 2K bytes, in
exchange for a little execution time. However, BUILDFIXED should not be
used for threaded applications, since the rewriting of the tables and virgin
may not be thread-safe.
*/
var virgin = true;
var lenfix, distfix; // We have no pointers in JS, so keep tables separate
function fixedtables(state) {
/* build fixed huffman tables if first call (may not be thread safe) */
if (virgin) {
var sym;
lenfix = new utils.Buf32(512);
distfix = new utils.Buf32(32);
/* literal/length table */
sym = 0;
while (sym < 144) { state.lens[sym++] = 8; }
while (sym < 256) { state.lens[sym++] = 9; }
while (sym < 280) { state.lens[sym++] = 7; }
while (sym < 288) { state.lens[sym++] = 8; }
inflate_table(LENS, state.lens, 0, 288, lenfix, 0, state.work, {bits: 9});
/* distance table */
sym = 0;
while (sym < 32) { state.lens[sym++] = 5; }
inflate_table(DISTS, state.lens, 0, 32, distfix, 0, state.work, {bits: 5});
/* do this just once */
virgin = false;
}
state.lencode = lenfix;
state.lenbits = 9;
state.distcode = distfix;
state.distbits = 5;
}
/*
Update the window with the last wsize (normally 32K) bytes written before
returning. If window does not exist yet, create it. This is only called
when a window is already in use, or when output has been written during this
inflate call, but the end of the deflate stream has not been reached yet.
It is also called to create a window for dictionary data when a dictionary
is loaded.
Providing output buffers larger than 32K to inflate() should provide a speed
advantage, since only the last 32K of output is copied to the sliding window
upon return from inflate(), and since all distances after the first 32K of
output will fall in the output data, making match copies simpler and faster.
The advantage may be dependent on the size of the processor's data caches.
*/
function updatewindow(strm, src, end, copy) {
var dist;
var state = strm.state;
/* if it hasn't been done already, allocate space for the window */
if (state.window === null) {
state.wsize = 1 << state.wbits;
state.wnext = 0;
state.whave = 0;
state.window = new utils.Buf8(state.wsize);
}
/* copy state->wsize or less output bytes into the circular window */
if (copy >= state.wsize) {
utils.arraySet(state.window,src, end - state.wsize, state.wsize, 0);
state.wnext = 0;
state.whave = state.wsize;
}
else {
dist = state.wsize - state.wnext;
if (dist > copy) {
dist = copy;
}
//zmemcpy(state->window + state->wnext, end - copy, dist);
utils.arraySet(state.window,src, end - copy, dist, state.wnext);
copy -= dist;
if (copy) {
//zmemcpy(state->window, end - copy, copy);
utils.arraySet(state.window,src, end - copy, copy, 0);
state.wnext = copy;
state.whave = state.wsize;
}
else {
state.wnext += dist;
if (state.wnext === state.wsize) { state.wnext = 0; }
if (state.whave < state.wsize) { state.whave += dist; }
}
}
return 0;
}
function inflate(strm, flush) {
var state;
var input, output; // input/output buffers
var next; /* next input INDEX */
var put; /* next output INDEX */
var have, left; /* available input and output */
var hold; /* bit buffer */
var bits; /* bits in bit buffer */
var _in, _out; /* save starting available input and output */
var copy; /* number of stored or match bytes to copy */
var from; /* where to copy match bytes from */
var from_source;
var here = 0; /* current decoding table entry */
var here_bits, here_op, here_val; // paked "here" denormalized (JS specific)
//var last; /* parent table entry */
var last_bits, last_op, last_val; // paked "last" denormalized (JS specific)
var len; /* length to copy for repeats, bits to drop */
var ret; /* return code */
var hbuf = new utils.Buf8(4); /* buffer for gzip header crc calculation */
var opts;
var n; // temporary var for NEED_BITS
var order = /* permutation of code lengths */
[16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15];
if (!strm || !strm.state || !strm.output ||
(!strm.input && strm.avail_in !== 0)) {
return Z_STREAM_ERROR;
}
state = strm.state;
if (state.mode === TYPE) { state.mode = TYPEDO; } /* skip check */
//--- LOAD() ---
put = strm.next_out;
output = strm.output;
left = strm.avail_out;
next = strm.next_in;
input = strm.input;
have = strm.avail_in;
hold = state.hold;
bits = state.bits;
//---
_in = have;
_out = left;
ret = Z_OK;
inf_leave: // goto emulation
for (;;) {
switch (state.mode) {
case HEAD:
if (state.wrap === 0) {
state.mode = TYPEDO;
break;
}
//=== NEEDBITS(16);
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if ((state.wrap & 2) && hold === 0x8b1f) { /* gzip header */
state.check = 0/*crc32(0L, Z_NULL, 0)*/;
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = FLAGS;
break;
}
state.flags = 0; /* expect zlib header */
if (state.head) {
state.head.done = false;
}
if (!(state.wrap & 1) || /* check if zlib header allowed */
(((hold & 0xff)/*BITS(8)*/ << 8) + (hold >> 8)) % 31) {
strm.msg = 'incorrect header check';
state.mode = BAD;
break;
}
if ((hold & 0x0f)/*BITS(4)*/ !== Z_DEFLATED) {
strm.msg = 'unknown compression method';
state.mode = BAD;
break;
}
//--- DROPBITS(4) ---//
hold >>>= 4;
bits -= 4;
//---//
len = (hold & 0x0f)/*BITS(4)*/ + 8;
if (state.wbits === 0) {
state.wbits = len;
}
else if (len > state.wbits) {
strm.msg = 'invalid window size';
state.mode = BAD;
break;
}
state.dmax = 1 << len;
//Tracev((stderr, "inflate: zlib header ok\n"));
strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
state.mode = hold & 0x200 ? DICTID : TYPE;
//=== INITBITS();
hold = 0;
bits = 0;
//===//
break;
case FLAGS:
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.flags = hold;
if ((state.flags & 0xff) !== Z_DEFLATED) {
strm.msg = 'unknown compression method';
state.mode = BAD;
break;
}
if (state.flags & 0xe000) {
strm.msg = 'unknown header flags set';
state.mode = BAD;
break;
}
if (state.head) {
state.head.text = ((hold >> 8) & 1);
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = TIME;
/* falls through */
case TIME:
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (state.head) {
state.head.time = hold;
}
if (state.flags & 0x0200) {
//=== CRC4(state.check, hold)
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
hbuf[2] = (hold >>> 16) & 0xff;
hbuf[3] = (hold >>> 24) & 0xff;
state.check = crc32(state.check, hbuf, 4, 0);
//===
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = OS;
/* falls through */
case OS:
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (state.head) {
state.head.xflags = (hold & 0xff);
state.head.os = (hold >> 8);
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = EXLEN;
/* falls through */
case EXLEN:
if (state.flags & 0x0400) {
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.length = hold;
if (state.head) {
state.head.extra_len = hold;
}
if (state.flags & 0x0200) {
//=== CRC2(state.check, hold);
hbuf[0] = hold & 0xff;
hbuf[1] = (hold >>> 8) & 0xff;
state.check = crc32(state.check, hbuf, 2, 0);
//===//
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
}
else if (state.head) {
state.head.extra = null/*Z_NULL*/;
}
state.mode = EXTRA;
/* falls through */
case EXTRA:
if (state.flags & 0x0400) {
copy = state.length;
if (copy > have) { copy = have; }
if (copy) {
if (state.head) {
len = state.head.extra_len - state.length;
if (!state.head.extra) {
// Use untyped array for more conveniend processing later
state.head.extra = new Array(state.head.extra_len);
}
utils.arraySet(
state.head.extra,
input,
next,
// extra field is limited to 65536 bytes
// - no need for additional size check
copy,
/*len + copy > state.head.extra_max - len ? state.head.extra_max : copy,*/
len
);
//zmemcpy(state.head.extra + len, next,
// len + copy > state.head.extra_max ?
// state.head.extra_max - len : copy);
}
if (state.flags & 0x0200) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
state.length -= copy;
}
if (state.length) { break inf_leave; }
}
state.length = 0;
state.mode = NAME;
/* falls through */
case NAME:
if (state.flags & 0x0800) {
if (have === 0) { break inf_leave; }
copy = 0;
do {
// TODO: 2 or 1 bytes?
len = input[next + copy++];
/* use constant limit because in js we should not preallocate memory */
if (state.head && len &&
(state.length < 65536 /*state.head.name_max*/)) {
state.head.name += String.fromCharCode(len);
}
} while (len && copy < have);
if (state.flags & 0x0200) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
if (len) { break inf_leave; }
}
else if (state.head) {
state.head.name = null;
}
state.length = 0;
state.mode = COMMENT;
/* falls through */
case COMMENT:
if (state.flags & 0x1000) {
if (have === 0) { break inf_leave; }
copy = 0;
do {
len = input[next + copy++];
/* use constant limit because in js we should not preallocate memory */
if (state.head && len &&
(state.length < 65536 /*state.head.comm_max*/)) {
state.head.comment += String.fromCharCode(len);
}
} while (len && copy < have);
if (state.flags & 0x0200) {
state.check = crc32(state.check, input, copy, next);
}
have -= copy;
next += copy;
if (len) { break inf_leave; }
}
else if (state.head) {
state.head.comment = null;
}
state.mode = HCRC;
/* falls through */
case HCRC:
if (state.flags & 0x0200) {
//=== NEEDBITS(16); */
while (bits < 16) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (hold !== (state.check & 0xffff)) {
strm.msg = 'header crc mismatch';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
}
if (state.head) {
state.head.hcrc = ((state.flags >> 9) & 1);
state.head.done = true;
}
strm.adler = state.check = 0 /*crc32(0L, Z_NULL, 0)*/;
state.mode = TYPE;
break;
case DICTID:
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
strm.adler = state.check = ZSWAP32(hold);
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = DICT;
/* falls through */
case DICT:
if (state.havedict === 0) {
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
return Z_NEED_DICT;
}
strm.adler = state.check = 1/*adler32(0L, Z_NULL, 0)*/;
state.mode = TYPE;
/* falls through */
case TYPE:
if (flush === Z_BLOCK || flush === Z_TREES) { break inf_leave; }
/* falls through */
case TYPEDO:
if (state.last) {
//--- BYTEBITS() ---//
hold >>>= bits & 7;
bits -= bits & 7;
//---//
state.mode = CHECK;
break;
}
//=== NEEDBITS(3); */
while (bits < 3) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.last = (hold & 0x01)/*BITS(1)*/;
//--- DROPBITS(1) ---//
hold >>>= 1;
bits -= 1;
//---//
switch ((hold & 0x03)/*BITS(2)*/) {
case 0: /* stored block */
//Tracev((stderr, "inflate: stored block%s\n",
// state.last ? " (last)" : ""));
state.mode = STORED;
break;
case 1: /* fixed block */
fixedtables(state);
//Tracev((stderr, "inflate: fixed codes block%s\n",
// state.last ? " (last)" : ""));
state.mode = LEN_; /* decode codes */
if (flush === Z_TREES) {
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
break inf_leave;
}
break;
case 2: /* dynamic block */
//Tracev((stderr, "inflate: dynamic codes block%s\n",
// state.last ? " (last)" : ""));
state.mode = TABLE;
break;
case 3:
strm.msg = 'invalid block type';
state.mode = BAD;
}
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
break;
case STORED:
//--- BYTEBITS() ---// /* go to byte boundary */
hold >>>= bits & 7;
bits -= bits & 7;
//---//
//=== NEEDBITS(32); */
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if ((hold & 0xffff) !== ((hold >>> 16) ^ 0xffff)) {
strm.msg = 'invalid stored block lengths';
state.mode = BAD;
break;
}
state.length = hold & 0xffff;
//Tracev((stderr, "inflate: stored length %u\n",
// state.length));
//=== INITBITS();
hold = 0;
bits = 0;
//===//
state.mode = COPY_;
if (flush === Z_TREES) { break inf_leave; }
/* falls through */
case COPY_:
state.mode = COPY;
/* falls through */
case COPY:
copy = state.length;
if (copy) {
if (copy > have) { copy = have; }
if (copy > left) { copy = left; }
if (copy === 0) { break inf_leave; }
//--- zmemcpy(put, next, copy); ---
utils.arraySet(output, input, next, copy, put);
//---//
have -= copy;
next += copy;
left -= copy;
put += copy;
state.length -= copy;
break;
}
//Tracev((stderr, "inflate: stored end\n"));
state.mode = TYPE;
break;
case TABLE:
//=== NEEDBITS(14); */
while (bits < 14) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.nlen = (hold & 0x1f)/*BITS(5)*/ + 257;
//--- DROPBITS(5) ---//
hold >>>= 5;
bits -= 5;
//---//
state.ndist = (hold & 0x1f)/*BITS(5)*/ + 1;
//--- DROPBITS(5) ---//
hold >>>= 5;
bits -= 5;
//---//
state.ncode = (hold & 0x0f)/*BITS(4)*/ + 4;
//--- DROPBITS(4) ---//
hold >>>= 4;
bits -= 4;
//---//
//#ifndef PKZIP_BUG_WORKAROUND
if (state.nlen > 286 || state.ndist > 30) {
strm.msg = 'too many length or distance symbols';
state.mode = BAD;
break;
}
//#endif
//Tracev((stderr, "inflate: table sizes ok\n"));
state.have = 0;
state.mode = LENLENS;
/* falls through */
case LENLENS:
while (state.have < state.ncode) {
//=== NEEDBITS(3);
while (bits < 3) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.lens[order[state.have++]] = (hold & 0x07);//BITS(3);
//--- DROPBITS(3) ---//
hold >>>= 3;
bits -= 3;
//---//
}
while (state.have < 19) {
state.lens[order[state.have++]] = 0;
}
// We have separate tables & no pointers. 2 commented lines below not needed.
//state.next = state.codes;
//state.lencode = state.next;
// Switch to use dynamic table
state.lencode = state.lendyn;
state.lenbits = 7;
opts = {bits: state.lenbits};
ret = inflate_table(CODES, state.lens, 0, 19, state.lencode, 0, state.work, opts);
state.lenbits = opts.bits;
if (ret) {
strm.msg = 'invalid code lengths set';
state.mode = BAD;
break;
}
//Tracev((stderr, "inflate: code lengths ok\n"));
state.have = 0;
state.mode = CODELENS;
/* falls through */
case CODELENS:
while (state.have < state.nlen + state.ndist) {
for (;;) {
here = state.lencode[hold & ((1 << state.lenbits) - 1)];/*BITS(state.lenbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if (here_val < 16) {
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.lens[state.have++] = here_val;
}
else {
if (here_val === 16) {
//=== NEEDBITS(here.bits + 2);
n = here_bits + 2;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
if (state.have === 0) {
strm.msg = 'invalid bit length repeat';
state.mode = BAD;
break;
}
len = state.lens[state.have - 1];
copy = 3 + (hold & 0x03);//BITS(2);
//--- DROPBITS(2) ---//
hold >>>= 2;
bits -= 2;
//---//
}
else if (here_val === 17) {
//=== NEEDBITS(here.bits + 3);
n = here_bits + 3;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
len = 0;
copy = 3 + (hold & 0x07);//BITS(3);
//--- DROPBITS(3) ---//
hold >>>= 3;
bits -= 3;
//---//
}
else {
//=== NEEDBITS(here.bits + 7);
n = here_bits + 7;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
len = 0;
copy = 11 + (hold & 0x7f);//BITS(7);
//--- DROPBITS(7) ---//
hold >>>= 7;
bits -= 7;
//---//
}
if (state.have + copy > state.nlen + state.ndist) {
strm.msg = 'invalid bit length repeat';
state.mode = BAD;
break;
}
while (copy--) {
state.lens[state.have++] = len;
}
}
}
/* handle error breaks in while */
if (state.mode === BAD) { break; }
/* check for end-of-block code (better have one) */
if (state.lens[256] === 0) {
strm.msg = 'invalid code -- missing end-of-block';
state.mode = BAD;
break;
}
/* build code tables -- note: do not change the lenbits or distbits
values here (9 and 6) without reading the comments in inftrees.h
concerning the ENOUGH constants, which depend on those values */
state.lenbits = 9;
opts = {bits: state.lenbits};
ret = inflate_table(LENS, state.lens, 0, state.nlen, state.lencode, 0, state.work, opts);
// We have separate tables & no pointers. 2 commented lines below not needed.
// state.next_index = opts.table_index;
state.lenbits = opts.bits;
// state.lencode = state.next;
if (ret) {
strm.msg = 'invalid literal/lengths set';
state.mode = BAD;
break;
}
state.distbits = 6;
//state.distcode.copy(state.codes);
// Switch to use dynamic table
state.distcode = state.distdyn;
opts = {bits: state.distbits};
ret = inflate_table(DISTS, state.lens, state.nlen, state.ndist, state.distcode, 0, state.work, opts);
// We have separate tables & no pointers. 2 commented lines below not needed.
// state.next_index = opts.table_index;
state.distbits = opts.bits;
// state.distcode = state.next;
if (ret) {
strm.msg = 'invalid distances set';
state.mode = BAD;
break;
}
//Tracev((stderr, 'inflate: codes ok\n'));
state.mode = LEN_;
if (flush === Z_TREES) { break inf_leave; }
/* falls through */
case LEN_:
state.mode = LEN;
/* falls through */
case LEN:
if (have >= 6 && left >= 258) {
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
inflate_fast(strm, _out);
//--- LOAD() ---
put = strm.next_out;
output = strm.output;
left = strm.avail_out;
next = strm.next_in;
input = strm.input;
have = strm.avail_in;
hold = state.hold;
bits = state.bits;
//---
if (state.mode === TYPE) {
state.back = -1;
}
break;
}
state.back = 0;
for (;;) {
here = state.lencode[hold & ((1 << state.lenbits) -1)]; /*BITS(state.lenbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if (here_bits <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if (here_op && (here_op & 0xf0) === 0) {
last_bits = here_bits;
last_op = here_op;
last_val = here_val;
for (;;) {
here = state.lencode[last_val +
((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((last_bits + here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
//--- DROPBITS(last.bits) ---//
hold >>>= last_bits;
bits -= last_bits;
//---//
state.back += last_bits;
}
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.back += here_bits;
state.length = here_val;
if (here_op === 0) {
//Tracevv((stderr, here.val >= 0x20 && here.val < 0x7f ?
// "inflate: literal '%c'\n" :
// "inflate: literal 0x%02x\n", here.val));
state.mode = LIT;
break;
}
if (here_op & 32) {
//Tracevv((stderr, "inflate: end of block\n"));
state.back = -1;
state.mode = TYPE;
break;
}
if (here_op & 64) {
strm.msg = 'invalid literal/length code';
state.mode = BAD;
break;
}
state.extra = here_op & 15;
state.mode = LENEXT;
/* falls through */
case LENEXT:
if (state.extra) {
//=== NEEDBITS(state.extra);
n = state.extra;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.length += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
//--- DROPBITS(state.extra) ---//
hold >>>= state.extra;
bits -= state.extra;
//---//
state.back += state.extra;
}
//Tracevv((stderr, "inflate: length %u\n", state.length));
state.was = state.length;
state.mode = DIST;
/* falls through */
case DIST:
for (;;) {
here = state.distcode[hold & ((1 << state.distbits) -1)];/*BITS(state.distbits)*/
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
if ((here_op & 0xf0) === 0) {
last_bits = here_bits;
last_op = here_op;
last_val = here_val;
for (;;) {
here = state.distcode[last_val +
((hold & ((1 << (last_bits + last_op)) -1))/*BITS(last.bits + last.op)*/ >> last_bits)];
here_bits = here >>> 24;
here_op = (here >>> 16) & 0xff;
here_val = here & 0xffff;
if ((last_bits + here_bits) <= bits) { break; }
//--- PULLBYTE() ---//
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
//---//
}
//--- DROPBITS(last.bits) ---//
hold >>>= last_bits;
bits -= last_bits;
//---//
state.back += last_bits;
}
//--- DROPBITS(here.bits) ---//
hold >>>= here_bits;
bits -= here_bits;
//---//
state.back += here_bits;
if (here_op & 64) {
strm.msg = 'invalid distance code';
state.mode = BAD;
break;
}
state.offset = here_val;
state.extra = (here_op) & 15;
state.mode = DISTEXT;
/* falls through */
case DISTEXT:
if (state.extra) {
//=== NEEDBITS(state.extra);
n = state.extra;
while (bits < n) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
state.offset += hold & ((1 << state.extra) -1)/*BITS(state.extra)*/;
//--- DROPBITS(state.extra) ---//
hold >>>= state.extra;
bits -= state.extra;
//---//
state.back += state.extra;
}
//#ifdef INFLATE_STRICT
if (state.offset > state.dmax) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break;
}
//#endif
//Tracevv((stderr, "inflate: distance %u\n", state.offset));
state.mode = MATCH;
/* falls through */
case MATCH:
if (left === 0) { break inf_leave; }
copy = _out - left;
if (state.offset > copy) { /* copy from window */
copy = state.offset - copy;
if (copy > state.whave) {
if (state.sane) {
strm.msg = 'invalid distance too far back';
state.mode = BAD;
break;
}
// (!) This block is disabled in zlib defailts,
// don't enable it for binary compatibility
//#ifdef INFLATE_ALLOW_INVALID_DISTANCE_TOOFAR_ARRR
// Trace((stderr, "inflate.c too far\n"));
// copy -= state.whave;
// if (copy > state.length) { copy = state.length; }
// if (copy > left) { copy = left; }
// left -= copy;
// state.length -= copy;
// do {
// output[put++] = 0;
// } while (--copy);
// if (state.length === 0) { state.mode = LEN; }
// break;
//#endif
}
if (copy > state.wnext) {
copy -= state.wnext;
from = state.wsize - copy;
}
else {
from = state.wnext - copy;
}
if (copy > state.length) { copy = state.length; }
from_source = state.window;
}
else { /* copy from output */
from_source = output;
from = put - state.offset;
copy = state.length;
}
if (copy > left) { copy = left; }
left -= copy;
state.length -= copy;
do {
output[put++] = from_source[from++];
} while (--copy);
if (state.length === 0) { state.mode = LEN; }
break;
case LIT:
if (left === 0) { break inf_leave; }
output[put++] = state.length;
left--;
state.mode = LEN;
break;
case CHECK:
if (state.wrap) {
//=== NEEDBITS(32);
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
// Use '|' insdead of '+' to make sure that result is signed
hold |= input[next++] << bits;
bits += 8;
}
//===//
_out -= left;
strm.total_out += _out;
state.total += _out;
if (_out) {
strm.adler = state.check =
/*UPDATE(state.check, put - _out, _out);*/
(state.flags ? crc32(state.check, output, _out, put - _out) : adler32(state.check, output, _out, put - _out));
}
_out = left;
// NB: crc32 stored as signed 32-bit int, ZSWAP32 returns signed too
if ((state.flags ? hold : ZSWAP32(hold)) !== state.check) {
strm.msg = 'incorrect data check';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
//Tracev((stderr, "inflate: check matches trailer\n"));
}
state.mode = LENGTH;
/* falls through */
case LENGTH:
if (state.wrap && state.flags) {
//=== NEEDBITS(32);
while (bits < 32) {
if (have === 0) { break inf_leave; }
have--;
hold += input[next++] << bits;
bits += 8;
}
//===//
if (hold !== (state.total & 0xffffffff)) {
strm.msg = 'incorrect length check';
state.mode = BAD;
break;
}
//=== INITBITS();
hold = 0;
bits = 0;
//===//
//Tracev((stderr, "inflate: length matches trailer\n"));
}
state.mode = DONE;
/* falls through */
case DONE:
ret = Z_STREAM_END;
break inf_leave;
case BAD:
ret = Z_DATA_ERROR;
break inf_leave;
case MEM:
return Z_MEM_ERROR;
case SYNC:
/* falls through */
default:
return Z_STREAM_ERROR;
}
}
// inf_leave <- here is real place for "goto inf_leave", emulated via "break inf_leave"
/*
Return from inflate(), updating the total counts and the check value.
If there was no progress during the inflate() call, return a buffer
error. Call updatewindow() to create and/or update the window state.
Note: a memory error from inflate() is non-recoverable.
*/
//--- RESTORE() ---
strm.next_out = put;
strm.avail_out = left;
strm.next_in = next;
strm.avail_in = have;
state.hold = hold;
state.bits = bits;
//---
if (state.wsize || (_out !== strm.avail_out && state.mode < BAD &&
(state.mode < CHECK || flush !== Z_FINISH))) {
if (updatewindow(strm, strm.output, strm.next_out, _out - strm.avail_out)) {
state.mode = MEM;
return Z_MEM_ERROR;
}
}
_in -= strm.avail_in;
_out -= strm.avail_out;
strm.total_in += _in;
strm.total_out += _out;
state.total += _out;
if (state.wrap && _out) {
strm.adler = state.check = /*UPDATE(state.check, strm.next_out - _out, _out);*/
(state.flags ? crc32(state.check, output, _out, strm.next_out - _out) : adler32(state.check, output, _out, strm.next_out - _out));
}
strm.data_type = state.bits + (state.last ? 64 : 0) +
(state.mode === TYPE ? 128 : 0) +
(state.mode === LEN_ || state.mode === COPY_ ? 256 : 0);
if (((_in === 0 && _out === 0) || flush === Z_FINISH) && ret === Z_OK) {
ret = Z_BUF_ERROR;
}
return ret;
}
function inflateEnd(strm) {
if (!strm || !strm.state /*|| strm->zfree == (free_func)0*/) {
return Z_STREAM_ERROR;
}
var state = strm.state;
if (state.window) {
state.window = null;
}
strm.state = null;
return Z_OK;
}
function inflateGetHeader(strm, head) {
var state;
/* check state */
if (!strm || !strm.state) { return Z_STREAM_ERROR; }
state = strm.state;
if ((state.wrap & 2) === 0) { return Z_STREAM_ERROR; }
/* save header structure */
state.head = head;
head.done = false;
return Z_OK;
}
exports.inflateReset = inflateReset;
exports.inflateReset2 = inflateReset2;
exports.inflateResetKeep = inflateResetKeep;
exports.inflateInit = inflateInit;
exports.inflateInit2 = inflateInit2;
exports.inflate = inflate;
exports.inflateEnd = inflateEnd;
exports.inflateGetHeader = inflateGetHeader;
exports.inflateInfo = 'pako inflate (from Nodeca project)';
/* Not implemented
exports.inflateCopy = inflateCopy;
exports.inflateGetDictionary = inflateGetDictionary;
exports.inflateMark = inflateMark;
exports.inflatePrime = inflatePrime;
exports.inflateSetDictionary = inflateSetDictionary;
exports.inflateSync = inflateSync;
exports.inflateSyncPoint = inflateSyncPoint;
exports.inflateUndermine = inflateUndermine;
*/
},{"../utils/common":86,"./adler32":88,"./crc32":90,"./inffast":93,"./inftrees":95}],95:[function(_dereq_,module,exports){
'use strict';
var utils = _dereq_('../utils/common');
var MAXBITS = 15;
var ENOUGH_LENS = 852;
var ENOUGH_DISTS = 592;
//var ENOUGH = (ENOUGH_LENS+ENOUGH_DISTS);
var CODES = 0;
var LENS = 1;
var DISTS = 2;
var lbase = [ /* Length codes 257..285 base */
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
];
var lext = [ /* Length codes 257..285 extra */
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
];
var dbase = [ /* Distance codes 0..29 base */
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
];
var dext = [ /* Distance codes 0..29 extra */
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
];
module.exports = function inflate_table(type, lens, lens_index, codes, table, table_index, work, opts)
{
var bits = opts.bits;
//here = opts.here; /* table entry for duplication */
var len = 0; /* a code's length in bits */
var sym = 0; /* index of code symbols */
var min = 0, max = 0; /* minimum and maximum code lengths */
var root = 0; /* number of index bits for root table */
var curr = 0; /* number of index bits for current table */
var drop = 0; /* code bits to drop for sub-table */
var left = 0; /* number of prefix codes available */
var used = 0; /* code entries in table used */
var huff = 0; /* Huffman code */
var incr; /* for incrementing code, index */
var fill; /* index for replicating entries */
var low; /* low bits for current root entry */
var mask; /* mask for low root bits */
var next; /* next available space in table */
var base = null; /* base value table to use */
var base_index = 0;
// var shoextra; /* extra bits table to use */
var end; /* use base and extra for symbol > end */
var count = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* number of codes of each length */
var offs = new utils.Buf16(MAXBITS+1); //[MAXBITS+1]; /* offsets in table for each length */
var extra = null;
var extra_index = 0;
var here_bits, here_op, here_val;
/*
Process a set of code lengths to create a canonical Huffman code. The
code lengths are lens[0..codes-1]. Each length corresponds to the
symbols 0..codes-1. The Huffman code is generated by first sorting the
symbols by length from short to long, and retaining the symbol order
for codes with equal lengths. Then the code starts with all zero bits
for the first code of the shortest length, and the codes are integer
increments for the same length, and zeros are appended as the length
increases. For the deflate format, these bits are stored backwards
from their more natural integer increment ordering, and so when the
decoding tables are built in the large loop below, the integer codes
are incremented backwards.
This routine assumes, but does not check, that all of the entries in
lens[] are in the range 0..MAXBITS. The caller must assure this.
1..MAXBITS is interpreted as that code length. zero means that that
symbol does not occur in this code.
The codes are sorted by computing a count of codes for each length,
creating from that a table of starting indices for each length in the
sorted table, and then entering the symbols in order in the sorted
table. The sorted table is work[], with that space being provided by
the caller.
The length counts are used for other purposes as well, i.e. finding
the minimum and maximum length codes, determining if there are any
codes at all, checking for a valid set of lengths, and looking ahead
at length counts to determine sub-table sizes when building the
decoding tables.
*/
/* accumulate lengths for codes (assumes lens[] all in 0..MAXBITS) */
for (len = 0; len <= MAXBITS; len++) {
count[len] = 0;
}
for (sym = 0; sym < codes; sym++) {
count[lens[lens_index + sym]]++;
}
/* bound code lengths, force root to be within code lengths */
root = bits;
for (max = MAXBITS; max >= 1; max--) {
if (count[max] !== 0) { break; }
}
if (root > max) {
root = max;
}
if (max === 0) { /* no symbols to code at all */
//table.op[opts.table_index] = 64; //here.op = (var char)64; /* invalid code marker */
//table.bits[opts.table_index] = 1; //here.bits = (var char)1;
//table.val[opts.table_index++] = 0; //here.val = (var short)0;
table[table_index++] = (1 << 24) | (64 << 16) | 0;
//table.op[opts.table_index] = 64;
//table.bits[opts.table_index] = 1;
//table.val[opts.table_index++] = 0;
table[table_index++] = (1 << 24) | (64 << 16) | 0;
opts.bits = 1;
return 0; /* no symbols, but wait for decoding to report error */
}
for (min = 1; min < max; min++) {
if (count[min] !== 0) { break; }
}
if (root < min) {
root = min;
}
/* check for an over-subscribed or incomplete set of lengths */
left = 1;
for (len = 1; len <= MAXBITS; len++) {
left <<= 1;
left -= count[len];
if (left < 0) {
return -1;
} /* over-subscribed */
}
if (left > 0 && (type === CODES || max !== 1)) {
return -1; /* incomplete set */
}
/* generate offsets into symbol table for each length for sorting */
offs[1] = 0;
for (len = 1; len < MAXBITS; len++) {
offs[len + 1] = offs[len] + count[len];
}
/* sort symbols by length, by symbol order within each length */
for (sym = 0; sym < codes; sym++) {
if (lens[lens_index + sym] !== 0) {
work[offs[lens[lens_index + sym]]++] = sym;
}
}
/*
Create and fill in decoding tables. In this loop, the table being
filled is at next and has curr index bits. The code being used is huff
with length len. That code is converted to an index by dropping drop
bits off of the bottom. For codes where len is less than drop + curr,
those top drop + curr - len bits are incremented through all values to
fill the table with replicated entries.
root is the number of index bits for the root table. When len exceeds
root, sub-tables are created pointed to by the root entry with an index
of the low root bits of huff. This is saved in low to check for when a
new sub-table should be started. drop is zero when the root table is
being filled, and drop is root when sub-tables are being filled.
When a new sub-table is needed, it is necessary to look ahead in the
code lengths to determine what size sub-table is needed. The length
counts are used for this, and so count[] is decremented as codes are
entered in the tables.
used keeps track of how many table entries have been allocated from the
provided *table space. It is checked for LENS and DIST tables against
the constants ENOUGH_LENS and ENOUGH_DISTS to guard against changes in
the initial root table size constants. See the comments in inftrees.h
for more information.
sym increments through all symbols, and the loop terminates when
all codes of length max, i.e. all codes, have been processed. This
routine permits incomplete codes, so another loop after this one fills
in the rest of the decoding tables with invalid code markers.
*/
/* set up for code type */
// poor man optimization - use if-else instead of switch,
// to avoid deopts in old v8
if (type === CODES) {
base = extra = work; /* dummy value--not used */
end = 19;
} else if (type === LENS) {
base = lbase;
base_index -= 257;
extra = lext;
extra_index -= 257;
end = 256;
} else { /* DISTS */
base = dbase;
extra = dext;
end = -1;
}
/* initialize opts for loop */
huff = 0; /* starting code */
sym = 0; /* starting code symbol */
len = min; /* starting code length */
next = table_index; /* current table to fill in */
curr = root; /* current table index bits */
drop = 0; /* current bits to drop from code for index */
low = -1; /* trigger new sub-table when len > root */
used = 1 << root; /* use root table entries */
mask = used - 1; /* mask for comparing low */
/* check available table space */
if ((type === LENS && used > ENOUGH_LENS) ||
(type === DISTS && used > ENOUGH_DISTS)) {
return 1;
}
var i=0;
/* process all codes and make table entries */
for (;;) {
i++;
/* create table entry */
here_bits = len - drop;
if (work[sym] < end) {
here_op = 0;
here_val = work[sym];
}
else if (work[sym] > end) {
here_op = extra[extra_index + work[sym]];
here_val = base[base_index + work[sym]];
}
else {
here_op = 32 + 64; /* end of block */
here_val = 0;
}
/* replicate for those indices with low len bits equal to huff */
incr = 1 << (len - drop);
fill = 1 << curr;
min = fill; /* save offset to next table */
do {
fill -= incr;
table[next + (huff >> drop) + fill] = (here_bits << 24) | (here_op << 16) | here_val |0;
} while (fill !== 0);
/* backwards increment the len-bit code huff */
incr = 1 << (len - 1);
while (huff & incr) {
incr >>= 1;
}
if (incr !== 0) {
huff &= incr - 1;
huff += incr;
} else {
huff = 0;
}
/* go to next symbol, update count, len */
sym++;
if (--count[len] === 0) {
if (len === max) { break; }
len = lens[lens_index + work[sym]];
}
/* create new sub-table if needed */
if (len > root && (huff & mask) !== low) {
/* if first time, transition to sub-tables */
if (drop === 0) {
drop = root;
}
/* increment past last table */
next += min; /* here min is 1 << curr */
/* determine length of next table */
curr = len - drop;
left = 1 << curr;
while (curr + drop < max) {
left -= count[curr + drop];
if (left <= 0) { break; }
curr++;
left <<= 1;
}
/* check for enough space */
used += 1 << curr;
if ((type === LENS && used > ENOUGH_LENS) ||
(type === DISTS && used > ENOUGH_DISTS)) {
return 1;
}
/* point entry in root table to sub-table */
low = huff & mask;
/*table.op[low] = curr;
table.bits[low] = root;
table.val[low] = next - opts.table_index;*/
table[low] = (root << 24) | (curr << 16) | (next - table_index) |0;
}
}
/* fill in remaining table entry if code is incomplete (guaranteed to have
at most one remaining entry, since if the code is incomplete, the
maximum code length that was allowed to get this far is one bit) */
if (huff !== 0) {
//table.op[next + huff] = 64; /* invalid code marker */
//table.bits[next + huff] = len - drop;
//table.val[next + huff] = 0;
table[next + huff] = ((len - drop) << 24) | (64 << 16) |0;
}
/* set return parameters */
//opts.table_index += used;
opts.bits = root;
return 0;
};
},{"../utils/common":86}],96:[function(_dereq_,module,exports){
'use strict';
module.exports = {
'2': 'need dictionary', /* Z_NEED_DICT 2 */
'1': 'stream end', /* Z_STREAM_END 1 */
'0': '', /* Z_OK 0 */
'-1': 'file error', /* Z_ERRNO (-1) */
'-2': 'stream error', /* Z_STREAM_ERROR (-2) */
'-3': 'data error', /* Z_DATA_ERROR (-3) */
'-4': 'insufficient memory', /* Z_MEM_ERROR (-4) */
'-5': 'buffer error', /* Z_BUF_ERROR (-5) */
'-6': 'incompatible version' /* Z_VERSION_ERROR (-6) */
};
},{}],97:[function(_dereq_,module,exports){
'use strict';
var utils = _dereq_('../utils/common');
/* Public constants ==========================================================*/
/* ===========================================================================*/
//var Z_FILTERED = 1;
//var Z_HUFFMAN_ONLY = 2;
//var Z_RLE = 3;
var Z_FIXED = 4;
//var Z_DEFAULT_STRATEGY = 0;
/* Possible values of the data_type field (though see inflate()) */
var Z_BINARY = 0;
var Z_TEXT = 1;
//var Z_ASCII = 1; // = Z_TEXT
var Z_UNKNOWN = 2;
/*============================================================================*/
function zero(buf) { var len = buf.length; while (--len >= 0) { buf[len] = 0; } }
// From zutil.h
var STORED_BLOCK = 0;
var STATIC_TREES = 1;
var DYN_TREES = 2;
/* The three kinds of block type */
var MIN_MATCH = 3;
var MAX_MATCH = 258;
/* The minimum and maximum match lengths */
// From deflate.h
/* ===========================================================================
* Internal compression state.
*/
var LENGTH_CODES = 29;
/* number of length codes, not counting the special END_BLOCK code */
var LITERALS = 256;
/* number of literal bytes 0..255 */
var L_CODES = LITERALS + 1 + LENGTH_CODES;
/* number of Literal or Length codes, including the END_BLOCK code */
var D_CODES = 30;
/* number of distance codes */
var BL_CODES = 19;
/* number of codes used to transfer the bit lengths */
var HEAP_SIZE = 2*L_CODES + 1;
/* maximum heap size */
var MAX_BITS = 15;
/* All codes must not exceed MAX_BITS bits */
var Buf_size = 16;
/* size of bit buffer in bi_buf */
/* ===========================================================================
* Constants
*/
var MAX_BL_BITS = 7;
/* Bit length codes must not exceed MAX_BL_BITS bits */
var END_BLOCK = 256;
/* end of block literal code */
var REP_3_6 = 16;
/* repeat previous bit length 3-6 times (2 bits of repeat count) */
var REPZ_3_10 = 17;
/* repeat a zero length 3-10 times (3 bits of repeat count) */
var REPZ_11_138 = 18;
/* repeat a zero length 11-138 times (7 bits of repeat count) */
var extra_lbits = /* extra bits for each length code */
[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];
var extra_dbits = /* extra bits for each distance code */
[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];
var extra_blbits = /* extra bits for each bit length code */
[0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,2,3,7];
var bl_order =
[16,17,18,0,8,7,9,6,10,5,11,4,12,3,13,2,14,1,15];
/* The lengths of the bit length codes are sent in order of decreasing
* probability, to avoid transmitting the lengths for unused bit length codes.
*/
/* ===========================================================================
* Local data. These are initialized only once.
*/
// We pre-fill arrays with 0 to avoid uninitialized gaps
var DIST_CODE_LEN = 512; /* see definition of array dist_code below */
// !!!! Use flat array insdead of structure, Freq = i*2, Len = i*2+1
var static_ltree = new Array((L_CODES+2) * 2);
zero(static_ltree);
/* The static literal tree. Since the bit lengths are imposed, there is no
* need for the L_CODES extra codes used during heap construction. However
* The codes 286 and 287 are needed to build a canonical tree (see _tr_init
* below).
*/
var static_dtree = new Array(D_CODES * 2);
zero(static_dtree);
/* The static distance tree. (Actually a trivial tree since all codes use
* 5 bits.)
*/
var _dist_code = new Array(DIST_CODE_LEN);
zero(_dist_code);
/* Distance codes. The first 256 values correspond to the distances
* 3 .. 258, the last 256 values correspond to the top 8 bits of
* the 15 bit distances.
*/
var _length_code = new Array(MAX_MATCH-MIN_MATCH+1);
zero(_length_code);
/* length code for each normalized match length (0 == MIN_MATCH) */
var base_length = new Array(LENGTH_CODES);
zero(base_length);
/* First normalized length for each code (0 = MIN_MATCH) */
var base_dist = new Array(D_CODES);
zero(base_dist);
/* First normalized distance for each code (0 = distance of 1) */
var StaticTreeDesc = function (static_tree, extra_bits, extra_base, elems, max_length) {
this.static_tree = static_tree; /* static tree or NULL */
this.extra_bits = extra_bits; /* extra bits for each code or NULL */
this.extra_base = extra_base; /* base index for extra_bits */
this.elems = elems; /* max number of elements in the tree */
this.max_length = max_length; /* max bit length for the codes */
// show if `static_tree` has data or dummy - needed for monomorphic objects
this.has_stree = static_tree && static_tree.length;
};
var static_l_desc;
var static_d_desc;
var static_bl_desc;
var TreeDesc = function(dyn_tree, stat_desc) {
this.dyn_tree = dyn_tree; /* the dynamic tree */
this.max_code = 0; /* largest code with non zero frequency */
this.stat_desc = stat_desc; /* the corresponding static tree */
};
function d_code(dist) {
return dist < 256 ? _dist_code[dist] : _dist_code[256 + (dist >>> 7)];
}
/* ===========================================================================
* Output a short LSB first on the stream.
* IN assertion: there is enough room in pendingBuf.
*/
function put_short (s, w) {
// put_byte(s, (uch)((w) & 0xff));
// put_byte(s, (uch)((ush)(w) >> 8));
s.pending_buf[s.pending++] = (w) & 0xff;
s.pending_buf[s.pending++] = (w >>> 8) & 0xff;
}
/* ===========================================================================
* Send a value on a given number of bits.
* IN assertion: length <= 16 and value fits in length bits.
*/
function send_bits(s, value, length) {
if (s.bi_valid > (Buf_size - length)) {
s.bi_buf |= (value << s.bi_valid) & 0xffff;
put_short(s, s.bi_buf);
s.bi_buf = value >> (Buf_size - s.bi_valid);
s.bi_valid += length - Buf_size;
} else {
s.bi_buf |= (value << s.bi_valid) & 0xffff;
s.bi_valid += length;
}
}
function send_code(s, c, tree) {
send_bits(s, tree[c*2]/*.Code*/, tree[c*2 + 1]/*.Len*/);
}
/* ===========================================================================
* Reverse the first len bits of a code, using straightforward code (a faster
* method would use a table)
* IN assertion: 1 <= len <= 15
*/
function bi_reverse(code, len) {
var res = 0;
do {
res |= code & 1;
code >>>= 1;
res <<= 1;
} while (--len > 0);
return res >>> 1;
}
/* ===========================================================================
* Flush the bit buffer, keeping at most 7 bits in it.
*/
function bi_flush(s) {
if (s.bi_valid === 16) {
put_short(s, s.bi_buf);
s.bi_buf = 0;
s.bi_valid = 0;
} else if (s.bi_valid >= 8) {
s.pending_buf[s.pending++] = s.bi_buf & 0xff;
s.bi_buf >>= 8;
s.bi_valid -= 8;
}
}
/* ===========================================================================
* Compute the optimal bit lengths for a tree and update the total bit length
* for the current block.
* IN assertion: the fields freq and dad are set, heap[heap_max] and
* above are the tree nodes sorted by increasing frequency.
* OUT assertions: the field len is set to the optimal bit length, the
* array bl_count contains the frequencies for each bit length.
* The length opt_len is updated; static_len is also updated if stree is
* not null.
*/
function gen_bitlen(s, desc)
// deflate_state *s;
// tree_desc *desc; /* the tree descriptor */
{
var tree = desc.dyn_tree;
var max_code = desc.max_code;
var stree = desc.stat_desc.static_tree;
var has_stree = desc.stat_desc.has_stree;
var extra = desc.stat_desc.extra_bits;
var base = desc.stat_desc.extra_base;
var max_length = desc.stat_desc.max_length;
var h; /* heap index */
var n, m; /* iterate over the tree elements */
var bits; /* bit length */
var xbits; /* extra bits */
var f; /* frequency */
var overflow = 0; /* number of elements with bit length too large */
for (bits = 0; bits <= MAX_BITS; bits++) {
s.bl_count[bits] = 0;
}
/* In a first pass, compute the optimal bit lengths (which may
* overflow in the case of the bit length tree).
*/
tree[s.heap[s.heap_max]*2 + 1]/*.Len*/ = 0; /* root of the heap */
for (h = s.heap_max+1; h < HEAP_SIZE; h++) {
n = s.heap[h];
bits = tree[tree[n*2 +1]/*.Dad*/ * 2 + 1]/*.Len*/ + 1;
if (bits > max_length) {
bits = max_length;
overflow++;
}
tree[n*2 + 1]/*.Len*/ = bits;
/* We overwrite tree[n].Dad which is no longer needed */
if (n > max_code) { continue; } /* not a leaf node */
s.bl_count[bits]++;
xbits = 0;
if (n >= base) {
xbits = extra[n-base];
}
f = tree[n * 2]/*.Freq*/;
s.opt_len += f * (bits + xbits);
if (has_stree) {
s.static_len += f * (stree[n*2 + 1]/*.Len*/ + xbits);
}
}
if (overflow === 0) { return; }
// Trace((stderr,"\nbit length overflow\n"));
/* This happens for example on obj2 and pic of the Calgary corpus */
/* Find the first bit length which could increase: */
do {
bits = max_length-1;
while (s.bl_count[bits] === 0) { bits--; }
s.bl_count[bits]--; /* move one leaf down the tree */
s.bl_count[bits+1] += 2; /* move one overflow item as its brother */
s.bl_count[max_length]--;
/* The brother of the overflow item also moves one step up,
* but this does not affect bl_count[max_length]
*/
overflow -= 2;
} while (overflow > 0);
/* Now recompute all bit lengths, scanning in increasing frequency.
* h is still equal to HEAP_SIZE. (It is simpler to reconstruct all
* lengths instead of fixing only the wrong ones. This idea is taken
* from 'ar' written by Haruhiko Okumura.)
*/
for (bits = max_length; bits !== 0; bits--) {
n = s.bl_count[bits];
while (n !== 0) {
m = s.heap[--h];
if (m > max_code) { continue; }
if (tree[m*2 + 1]/*.Len*/ !== bits) {
// Trace((stderr,"code %d bits %d->%d\n", m, tree[m].Len, bits));
s.opt_len += (bits - tree[m*2 + 1]/*.Len*/)*tree[m*2]/*.Freq*/;
tree[m*2 + 1]/*.Len*/ = bits;
}
n--;
}
}
}
/* ===========================================================================
* Generate the codes for a given tree and bit counts (which need not be
* optimal).
* IN assertion: the array bl_count contains the bit length statistics for
* the given tree and the field len is set for all tree elements.
* OUT assertion: the field code is set for all tree elements of non
* zero code length.
*/
function gen_codes(tree, max_code, bl_count)
// ct_data *tree; /* the tree to decorate */
// int max_code; /* largest code with non zero frequency */
// ushf *bl_count; /* number of codes at each bit length */
{
var next_code = new Array(MAX_BITS+1); /* next code value for each bit length */
var code = 0; /* running code value */
var bits; /* bit index */
var n; /* code index */
/* The distribution counts are first used to generate the code values
* without bit reversal.
*/
for (bits = 1; bits <= MAX_BITS; bits++) {
next_code[bits] = code = (code + bl_count[bits-1]) << 1;
}
/* Check that the bit counts in bl_count are consistent. The last code
* must be all ones.
*/
//Assert (code + bl_count[MAX_BITS]-1 == (1<<MAX_BITS)-1,
// "inconsistent bit counts");
//Tracev((stderr,"\ngen_codes: max_code %d ", max_code));
for (n = 0; n <= max_code; n++) {
var len = tree[n*2 + 1]/*.Len*/;
if (len === 0) { continue; }
/* Now reverse the bits */
tree[n*2]/*.Code*/ = bi_reverse(next_code[len]++, len);
//Tracecv(tree != static_ltree, (stderr,"\nn %3d %c l %2d c %4x (%x) ",
// n, (isgraph(n) ? n : ' '), len, tree[n].Code, next_code[len]-1));
}
}
/* ===========================================================================
* Initialize the various 'constant' tables.
*/
function tr_static_init() {
var n; /* iterates over tree elements */
var bits; /* bit counter */
var length; /* length value */
var code; /* code value */
var dist; /* distance index */
var bl_count = new Array(MAX_BITS+1);
/* number of codes at each bit length for an optimal tree */
// do check in _tr_init()
//if (static_init_done) return;
/* For some embedded targets, global variables are not initialized: */
/*#ifdef NO_INIT_GLOBAL_POINTERS
static_l_desc.static_tree = static_ltree;
static_l_desc.extra_bits = extra_lbits;
static_d_desc.static_tree = static_dtree;
static_d_desc.extra_bits = extra_dbits;
static_bl_desc.extra_bits = extra_blbits;
#endif*/
/* Initialize the mapping length (0..255) -> length code (0..28) */
length = 0;
for (code = 0; code < LENGTH_CODES-1; code++) {
base_length[code] = length;
for (n = 0; n < (1<<extra_lbits[code]); n++) {
_length_code[length++] = code;
}
}
//Assert (length == 256, "tr_static_init: length != 256");
/* Note that the length 255 (match length 258) can be represented
* in two different ways: code 284 + 5 bits or code 285, so we
* overwrite length_code[255] to use the best encoding:
*/
_length_code[length-1] = code;
/* Initialize the mapping dist (0..32K) -> dist code (0..29) */
dist = 0;
for (code = 0 ; code < 16; code++) {
base_dist[code] = dist;
for (n = 0; n < (1<<extra_dbits[code]); n++) {
_dist_code[dist++] = code;
}
}
//Assert (dist == 256, "tr_static_init: dist != 256");
dist >>= 7; /* from now on, all distances are divided by 128 */
for (; code < D_CODES; code++) {
base_dist[code] = dist << 7;
for (n = 0; n < (1<<(extra_dbits[code]-7)); n++) {
_dist_code[256 + dist++] = code;
}
}
//Assert (dist == 256, "tr_static_init: 256+dist != 512");
/* Construct the codes of the static literal tree */
for (bits = 0; bits <= MAX_BITS; bits++) {
bl_count[bits] = 0;
}
n = 0;
while (n <= 143) {
static_ltree[n*2 + 1]/*.Len*/ = 8;
n++;
bl_count[8]++;
}
while (n <= 255) {
static_ltree[n*2 + 1]/*.Len*/ = 9;
n++;
bl_count[9]++;
}
while (n <= 279) {
static_ltree[n*2 + 1]/*.Len*/ = 7;
n++;
bl_count[7]++;
}
while (n <= 287) {
static_ltree[n*2 + 1]/*.Len*/ = 8;
n++;
bl_count[8]++;
}
/* Codes 286 and 287 do not exist, but we must include them in the
* tree construction to get a canonical Huffman tree (longest code
* all ones)
*/
gen_codes(static_ltree, L_CODES+1, bl_count);
/* The static distance tree is trivial: */
for (n = 0; n < D_CODES; n++) {
static_dtree[n*2 + 1]/*.Len*/ = 5;
static_dtree[n*2]/*.Code*/ = bi_reverse(n, 5);
}
// Now data ready and we can init static trees
static_l_desc = new StaticTreeDesc(static_ltree, extra_lbits, LITERALS+1, L_CODES, MAX_BITS);
static_d_desc = new StaticTreeDesc(static_dtree, extra_dbits, 0, D_CODES, MAX_BITS);
static_bl_desc =new StaticTreeDesc(new Array(0), extra_blbits, 0, BL_CODES, MAX_BL_BITS);
//static_init_done = true;
}
/* ===========================================================================
* Initialize a new block.
*/
function init_block(s) {
var n; /* iterates over tree elements */
/* Initialize the trees. */
for (n = 0; n < L_CODES; n++) { s.dyn_ltree[n*2]/*.Freq*/ = 0; }
for (n = 0; n < D_CODES; n++) { s.dyn_dtree[n*2]/*.Freq*/ = 0; }
for (n = 0; n < BL_CODES; n++) { s.bl_tree[n*2]/*.Freq*/ = 0; }
s.dyn_ltree[END_BLOCK*2]/*.Freq*/ = 1;
s.opt_len = s.static_len = 0;
s.last_lit = s.matches = 0;
}
/* ===========================================================================
* Flush the bit buffer and align the output on a byte boundary
*/
function bi_windup(s)
{
if (s.bi_valid > 8) {
put_short(s, s.bi_buf);
} else if (s.bi_valid > 0) {
//put_byte(s, (Byte)s->bi_buf);
s.pending_buf[s.pending++] = s.bi_buf;
}
s.bi_buf = 0;
s.bi_valid = 0;
}
/* ===========================================================================
* Copy a stored block, storing first the length and its
* one's complement if requested.
*/
function copy_block(s, buf, len, header)
//DeflateState *s;
//charf *buf; /* the input data */
//unsigned len; /* its length */
//int header; /* true if block header must be written */
{
bi_windup(s); /* align on byte boundary */
if (header) {
put_short(s, len);
put_short(s, ~len);
}
// while (len--) {
// put_byte(s, *buf++);
// }
utils.arraySet(s.pending_buf, s.window, buf, len, s.pending);
s.pending += len;
}
/* ===========================================================================
* Compares to subtrees, using the tree depth as tie breaker when
* the subtrees have equal frequency. This minimizes the worst case length.
*/
function smaller(tree, n, m, depth) {
var _n2 = n*2;
var _m2 = m*2;
return (tree[_n2]/*.Freq*/ < tree[_m2]/*.Freq*/ ||
(tree[_n2]/*.Freq*/ === tree[_m2]/*.Freq*/ && depth[n] <= depth[m]));
}
/* ===========================================================================
* Restore the heap property by moving down the tree starting at node k,
* exchanging a node with the smallest of its two sons if necessary, stopping
* when the heap property is re-established (each father smaller than its
* two sons).
*/
function pqdownheap(s, tree, k)
// deflate_state *s;
// ct_data *tree; /* the tree to restore */
// int k; /* node to move down */
{
var v = s.heap[k];
var j = k << 1; /* left son of k */
while (j <= s.heap_len) {
/* Set j to the smallest of the two sons: */
if (j < s.heap_len &&
smaller(tree, s.heap[j+1], s.heap[j], s.depth)) {
j++;
}
/* Exit if v is smaller than both sons */
if (smaller(tree, v, s.heap[j], s.depth)) { break; }
/* Exchange v with the smallest son */
s.heap[k] = s.heap[j];
k = j;
/* And continue down the tree, setting j to the left son of k */
j <<= 1;
}
s.heap[k] = v;
}
// inlined manually
// var SMALLEST = 1;
/* ===========================================================================
* Send the block data compressed using the given Huffman trees
*/
function compress_block(s, ltree, dtree)
// deflate_state *s;
// const ct_data *ltree; /* literal tree */
// const ct_data *dtree; /* distance tree */
{
var dist; /* distance of matched string */
var lc; /* match length or unmatched char (if dist == 0) */
var lx = 0; /* running index in l_buf */
var code; /* the code to send */
var extra; /* number of extra bits to send */
if (s.last_lit !== 0) {
do {
dist = (s.pending_buf[s.d_buf + lx*2] << 8) | (s.pending_buf[s.d_buf + lx*2 + 1]);
lc = s.pending_buf[s.l_buf + lx];
lx++;
if (dist === 0) {
send_code(s, lc, ltree); /* send a literal byte */
//Tracecv(isgraph(lc), (stderr," '%c' ", lc));
} else {
/* Here, lc is the match length - MIN_MATCH */
code = _length_code[lc];
send_code(s, code+LITERALS+1, ltree); /* send the length code */
extra = extra_lbits[code];
if (extra !== 0) {
lc -= base_length[code];
send_bits(s, lc, extra); /* send the extra length bits */
}
dist--; /* dist is now the match distance - 1 */
code = d_code(dist);
//Assert (code < D_CODES, "bad d_code");
send_code(s, code, dtree); /* send the distance code */
extra = extra_dbits[code];
if (extra !== 0) {
dist -= base_dist[code];
send_bits(s, dist, extra); /* send the extra distance bits */
}
} /* literal or match pair ? */
/* Check that the overlay between pending_buf and d_buf+l_buf is ok: */
//Assert((uInt)(s->pending) < s->lit_bufsize + 2*lx,
// "pendingBuf overflow");
} while (lx < s.last_lit);
}
send_code(s, END_BLOCK, ltree);
}
/* ===========================================================================
* Construct one Huffman tree and assigns the code bit strings and lengths.
* Update the total bit length for the current block.
* IN assertion: the field freq is set for all tree elements.
* OUT assertions: the fields len and code are set to the optimal bit length
* and corresponding code. The length opt_len is updated; static_len is
* also updated if stree is not null. The field max_code is set.
*/
function build_tree(s, desc)
// deflate_state *s;
// tree_desc *desc; /* the tree descriptor */
{
var tree = desc.dyn_tree;
var stree = desc.stat_desc.static_tree;
var has_stree = desc.stat_desc.has_stree;
var elems = desc.stat_desc.elems;
var n, m; /* iterate over heap elements */
var max_code = -1; /* largest code with non zero frequency */
var node; /* new node being created */
/* Construct the initial heap, with least frequent element in
* heap[SMALLEST]. The sons of heap[n] are heap[2*n] and heap[2*n+1].
* heap[0] is not used.
*/
s.heap_len = 0;
s.heap_max = HEAP_SIZE;
for (n = 0; n < elems; n++) {
if (tree[n * 2]/*.Freq*/ !== 0) {
s.heap[++s.heap_len] = max_code = n;
s.depth[n] = 0;
} else {
tree[n*2 + 1]/*.Len*/ = 0;
}
}
/* The pkzip format requires that at least one distance code exists,
* and that at least one bit should be sent even if there is only one
* possible code. So to avoid special checks later on we force at least
* two codes of non zero frequency.
*/
while (s.heap_len < 2) {
node = s.heap[++s.heap_len] = (max_code < 2 ? ++max_code : 0);
tree[node * 2]/*.Freq*/ = 1;
s.depth[node] = 0;
s.opt_len--;
if (has_stree) {
s.static_len -= stree[node*2 + 1]/*.Len*/;
}
/* node is 0 or 1 so it does not have extra bits */
}
desc.max_code = max_code;
/* The elements heap[heap_len/2+1 .. heap_len] are leaves of the tree,
* establish sub-heaps of increasing lengths:
*/
for (n = (s.heap_len >> 1/*int /2*/); n >= 1; n--) { pqdownheap(s, tree, n); }
/* Construct the Huffman tree by repeatedly combining the least two
* frequent nodes.
*/
node = elems; /* next internal node of the tree */
do {
//pqremove(s, tree, n); /* n = node of least frequency */
/*** pqremove ***/
n = s.heap[1/*SMALLEST*/];
s.heap[1/*SMALLEST*/] = s.heap[s.heap_len--];
pqdownheap(s, tree, 1/*SMALLEST*/);
/***/
m = s.heap[1/*SMALLEST*/]; /* m = node of next least frequency */
s.heap[--s.heap_max] = n; /* keep the nodes sorted by frequency */
s.heap[--s.heap_max] = m;
/* Create a new node father of n and m */
tree[node * 2]/*.Freq*/ = tree[n * 2]/*.Freq*/ + tree[m * 2]/*.Freq*/;
s.depth[node] = (s.depth[n] >= s.depth[m] ? s.depth[n] : s.depth[m]) + 1;
tree[n*2 + 1]/*.Dad*/ = tree[m*2 + 1]/*.Dad*/ = node;
/* and insert the new node in the heap */
s.heap[1/*SMALLEST*/] = node++;
pqdownheap(s, tree, 1/*SMALLEST*/);
} while (s.heap_len >= 2);
s.heap[--s.heap_max] = s.heap[1/*SMALLEST*/];
/* At this point, the fields freq and dad are set. We can now
* generate the bit lengths.
*/
gen_bitlen(s, desc);
/* The field len is now set, we can generate the bit codes */
gen_codes(tree, max_code, s.bl_count);
}
/* ===========================================================================
* Scan a literal or distance tree to determine the frequencies of the codes
* in the bit length tree.
*/
function scan_tree(s, tree, max_code)
// deflate_state *s;
// ct_data *tree; /* the tree to be scanned */
// int max_code; /* and its largest code of non zero frequency */
{
var n; /* iterates over all tree elements */
var prevlen = -1; /* last emitted length */
var curlen; /* length of current code */
var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
var count = 0; /* repeat count of the current code */
var max_count = 7; /* max repeat count */
var min_count = 4; /* min repeat count */
if (nextlen === 0) {
max_count = 138;
min_count = 3;
}
tree[(max_code+1)*2 + 1]/*.Len*/ = 0xffff; /* guard */
for (n = 0; n <= max_code; n++) {
curlen = nextlen;
nextlen = tree[(n+1)*2 + 1]/*.Len*/;
if (++count < max_count && curlen === nextlen) {
continue;
} else if (count < min_count) {
s.bl_tree[curlen * 2]/*.Freq*/ += count;
} else if (curlen !== 0) {
if (curlen !== prevlen) { s.bl_tree[curlen * 2]/*.Freq*/++; }
s.bl_tree[REP_3_6*2]/*.Freq*/++;
} else if (count <= 10) {
s.bl_tree[REPZ_3_10*2]/*.Freq*/++;
} else {
s.bl_tree[REPZ_11_138*2]/*.Freq*/++;
}
count = 0;
prevlen = curlen;
if (nextlen === 0) {
max_count = 138;
min_count = 3;
} else if (curlen === nextlen) {
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
}
}
}
/* ===========================================================================
* Send a literal or distance tree in compressed form, using the codes in
* bl_tree.
*/
function send_tree(s, tree, max_code)
// deflate_state *s;
// ct_data *tree; /* the tree to be scanned */
// int max_code; /* and its largest code of non zero frequency */
{
var n; /* iterates over all tree elements */
var prevlen = -1; /* last emitted length */
var curlen; /* length of current code */
var nextlen = tree[0*2 + 1]/*.Len*/; /* length of next code */
var count = 0; /* repeat count of the current code */
var max_count = 7; /* max repeat count */
var min_count = 4; /* min repeat count */
/* tree[max_code+1].Len = -1; */ /* guard already set */
if (nextlen === 0) {
max_count = 138;
min_count = 3;
}
for (n = 0; n <= max_code; n++) {
curlen = nextlen;
nextlen = tree[(n+1)*2 + 1]/*.Len*/;
if (++count < max_count && curlen === nextlen) {
continue;
} else if (count < min_count) {
do { send_code(s, curlen, s.bl_tree); } while (--count !== 0);
} else if (curlen !== 0) {
if (curlen !== prevlen) {
send_code(s, curlen, s.bl_tree);
count--;
}
//Assert(count >= 3 && count <= 6, " 3_6?");
send_code(s, REP_3_6, s.bl_tree);
send_bits(s, count-3, 2);
} else if (count <= 10) {
send_code(s, REPZ_3_10, s.bl_tree);
send_bits(s, count-3, 3);
} else {
send_code(s, REPZ_11_138, s.bl_tree);
send_bits(s, count-11, 7);
}
count = 0;
prevlen = curlen;
if (nextlen === 0) {
max_count = 138;
min_count = 3;
} else if (curlen === nextlen) {
max_count = 6;
min_count = 3;
} else {
max_count = 7;
min_count = 4;
}
}
}
/* ===========================================================================
* Construct the Huffman tree for the bit lengths and return the index in
* bl_order of the last bit length code to send.
*/
function build_bl_tree(s) {
var max_blindex; /* index of last bit length code of non zero freq */
/* Determine the bit length frequencies for literal and distance trees */
scan_tree(s, s.dyn_ltree, s.l_desc.max_code);
scan_tree(s, s.dyn_dtree, s.d_desc.max_code);
/* Build the bit length tree: */
build_tree(s, s.bl_desc);
/* opt_len now includes the length of the tree representations, except
* the lengths of the bit lengths codes and the 5+5+4 bits for the counts.
*/
/* Determine the number of bit length codes to send. The pkzip format
* requires that at least 4 bit length codes be sent. (appnote.txt says
* 3 but the actual value used is 4.)
*/
for (max_blindex = BL_CODES-1; max_blindex >= 3; max_blindex--) {
if (s.bl_tree[bl_order[max_blindex]*2 + 1]/*.Len*/ !== 0) {
break;
}
}
/* Update opt_len to include the bit length tree and counts */
s.opt_len += 3*(max_blindex+1) + 5+5+4;
//Tracev((stderr, "\ndyn trees: dyn %ld, stat %ld",
// s->opt_len, s->static_len));
return max_blindex;
}
/* ===========================================================================
* Send the header for a block using dynamic Huffman trees: the counts, the
* lengths of the bit length codes, the literal tree and the distance tree.
* IN assertion: lcodes >= 257, dcodes >= 1, blcodes >= 4.
*/
function send_all_trees(s, lcodes, dcodes, blcodes)
// deflate_state *s;
// int lcodes, dcodes, blcodes; /* number of codes for each tree */
{
var rank; /* index in bl_order */
//Assert (lcodes >= 257 && dcodes >= 1 && blcodes >= 4, "not enough codes");
//Assert (lcodes <= L_CODES && dcodes <= D_CODES && blcodes <= BL_CODES,
// "too many codes");
//Tracev((stderr, "\nbl counts: "));
send_bits(s, lcodes-257, 5); /* not +255 as stated in appnote.txt */
send_bits(s, dcodes-1, 5);
send_bits(s, blcodes-4, 4); /* not -3 as stated in appnote.txt */
for (rank = 0; rank < blcodes; rank++) {
//Tracev((stderr, "\nbl code %2d ", bl_order[rank]));
send_bits(s, s.bl_tree[bl_order[rank]*2 + 1]/*.Len*/, 3);
}
//Tracev((stderr, "\nbl tree: sent %ld", s->bits_sent));
send_tree(s, s.dyn_ltree, lcodes-1); /* literal tree */
//Tracev((stderr, "\nlit tree: sent %ld", s->bits_sent));
send_tree(s, s.dyn_dtree, dcodes-1); /* distance tree */
//Tracev((stderr, "\ndist tree: sent %ld", s->bits_sent));
}
/* ===========================================================================
* Check if the data type is TEXT or BINARY, using the following algorithm:
* - TEXT if the two conditions below are satisfied:
* a) There are no non-portable control characters belonging to the
* "black list" (0..6, 14..25, 28..31).
* b) There is at least one printable character belonging to the
* "white list" (9 {TAB}, 10 {LF}, 13 {CR}, 32..255).
* - BINARY otherwise.
* - The following partially-portable control characters form a
* "gray list" that is ignored in this detection algorithm:
* (7 {BEL}, 8 {BS}, 11 {VT}, 12 {FF}, 26 {SUB}, 27 {ESC}).
* IN assertion: the fields Freq of dyn_ltree are set.
*/
function detect_data_type(s) {
/* black_mask is the bit mask of black-listed bytes
* set bits 0..6, 14..25, and 28..31
* 0xf3ffc07f = binary 11110011111111111100000001111111
*/
var black_mask = 0xf3ffc07f;
var n;
/* Check for non-textual ("black-listed") bytes. */
for (n = 0; n <= 31; n++, black_mask >>>= 1) {
if ((black_mask & 1) && (s.dyn_ltree[n*2]/*.Freq*/ !== 0)) {
return Z_BINARY;
}
}
/* Check for textual ("white-listed") bytes. */
if (s.dyn_ltree[9 * 2]/*.Freq*/ !== 0 || s.dyn_ltree[10 * 2]/*.Freq*/ !== 0 ||
s.dyn_ltree[13 * 2]/*.Freq*/ !== 0) {
return Z_TEXT;
}
for (n = 32; n < LITERALS; n++) {
if (s.dyn_ltree[n * 2]/*.Freq*/ !== 0) {
return Z_TEXT;
}
}
/* There are no "black-listed" or "white-listed" bytes:
* this stream either is empty or has tolerated ("gray-listed") bytes only.
*/
return Z_BINARY;
}
var static_init_done = false;
/* ===========================================================================
* Initialize the tree data structures for a new zlib stream.
*/
function _tr_init(s)
{
if (!static_init_done) {
tr_static_init();
static_init_done = true;
}
s.l_desc = new TreeDesc(s.dyn_ltree, static_l_desc);
s.d_desc = new TreeDesc(s.dyn_dtree, static_d_desc);
s.bl_desc = new TreeDesc(s.bl_tree, static_bl_desc);
s.bi_buf = 0;
s.bi_valid = 0;
/* Initialize the first block of the first file: */
init_block(s);
}
/* ===========================================================================
* Send a stored block
*/
function _tr_stored_block(s, buf, stored_len, last)
//DeflateState *s;
//charf *buf; /* input block */
//ulg stored_len; /* length of input block */
//int last; /* one if this is the last block for a file */
{
send_bits(s, (STORED_BLOCK<<1)+(last ? 1 : 0), 3); /* send block type */
copy_block(s, buf, stored_len, true); /* with header */
}
/* ===========================================================================
* Send one empty static block to give enough lookahead for inflate.
* This takes 10 bits, of which 7 may remain in the bit buffer.
*/
function _tr_align(s) {
send_bits(s, STATIC_TREES<<1, 3);
send_code(s, END_BLOCK, static_ltree);
bi_flush(s);
}
/* ===========================================================================
* Determine the best encoding for the current block: dynamic trees, static
* trees or store, and output the encoded block to the zip file.
*/
function _tr_flush_block(s, buf, stored_len, last)
//DeflateState *s;
//charf *buf; /* input block, or NULL if too old */
//ulg stored_len; /* length of input block */
//int last; /* one if this is the last block for a file */
{
var opt_lenb, static_lenb; /* opt_len and static_len in bytes */
var max_blindex = 0; /* index of last bit length code of non zero freq */
/* Build the Huffman trees unless a stored block is forced */
if (s.level > 0) {
/* Check if the file is binary or text */
if (s.strm.data_type === Z_UNKNOWN) {
s.strm.data_type = detect_data_type(s);
}
/* Construct the literal and distance trees */
build_tree(s, s.l_desc);
// Tracev((stderr, "\nlit data: dyn %ld, stat %ld", s->opt_len,
// s->static_len));
build_tree(s, s.d_desc);
// Tracev((stderr, "\ndist data: dyn %ld, stat %ld", s->opt_len,
// s->static_len));
/* At this point, opt_len and static_len are the total bit lengths of
* the compressed block data, excluding the tree representations.
*/
/* Build the bit length tree for the above two trees, and get the index
* in bl_order of the last bit length code to send.
*/
max_blindex = build_bl_tree(s);
/* Determine the best encoding. Compute the block lengths in bytes. */
opt_lenb = (s.opt_len+3+7) >>> 3;
static_lenb = (s.static_len+3+7) >>> 3;
// Tracev((stderr, "\nopt %lu(%lu) stat %lu(%lu) stored %lu lit %u ",
// opt_lenb, s->opt_len, static_lenb, s->static_len, stored_len,
// s->last_lit));
if (static_lenb <= opt_lenb) { opt_lenb = static_lenb; }
} else {
// Assert(buf != (char*)0, "lost buf");
opt_lenb = static_lenb = stored_len + 5; /* force a stored block */
}
if ((stored_len+4 <= opt_lenb) && (buf !== -1)) {
/* 4: two words for the lengths */
/* The test buf != NULL is only necessary if LIT_BUFSIZE > WSIZE.
* Otherwise we can't have processed more than WSIZE input bytes since
* the last block flush, because compression would have been
* successful. If LIT_BUFSIZE <= WSIZE, it is never too late to
* transform a block into a stored block.
*/
_tr_stored_block(s, buf, stored_len, last);
} else if (s.strategy === Z_FIXED || static_lenb === opt_lenb) {
send_bits(s, (STATIC_TREES<<1) + (last ? 1 : 0), 3);
compress_block(s, static_ltree, static_dtree);
} else {
send_bits(s, (DYN_TREES<<1) + (last ? 1 : 0), 3);
send_all_trees(s, s.l_desc.max_code+1, s.d_desc.max_code+1, max_blindex+1);
compress_block(s, s.dyn_ltree, s.dyn_dtree);
}
// Assert (s->compressed_len == s->bits_sent, "bad compressed size");
/* The above check is made mod 2^32, for files larger than 512 MB
* and uLong implemented on 32 bits.
*/
init_block(s);
if (last) {
bi_windup(s);
}
// Tracev((stderr,"\ncomprlen %lu(%lu) ", s->compressed_len>>3,
// s->compressed_len-7*last));
}
/* ===========================================================================
* Save the match info and tally the frequency counts. Return true if
* the current block must be flushed.
*/
function _tr_tally(s, dist, lc)
// deflate_state *s;
// unsigned dist; /* distance of matched string */
// unsigned lc; /* match length-MIN_MATCH or unmatched char (if dist==0) */
{
//var out_length, in_length, dcode;
s.pending_buf[s.d_buf + s.last_lit * 2] = (dist >>> 8) & 0xff;
s.pending_buf[s.d_buf + s.last_lit * 2 + 1] = dist & 0xff;
s.pending_buf[s.l_buf + s.last_lit] = lc & 0xff;
s.last_lit++;
if (dist === 0) {
/* lc is the unmatched char */
s.dyn_ltree[lc*2]/*.Freq*/++;
} else {
s.matches++;
/* Here, lc is the match length - MIN_MATCH */
dist--; /* dist = match distance - 1 */
//Assert((ush)dist < (ush)MAX_DIST(s) &&
// (ush)lc <= (ush)(MAX_MATCH-MIN_MATCH) &&
// (ush)d_code(dist) < (ush)D_CODES, "_tr_tally: bad match");
s.dyn_ltree[(_length_code[lc]+LITERALS+1) * 2]/*.Freq*/++;
s.dyn_dtree[d_code(dist) * 2]/*.Freq*/++;
}
// (!) This block is disabled in zlib defailts,
// don't enable it for binary compatibility
//#ifdef TRUNCATE_BLOCK
// /* Try to guess if it is profitable to stop the current block here */
// if ((s.last_lit & 0x1fff) === 0 && s.level > 2) {
// /* Compute an upper bound for the compressed length */
// out_length = s.last_lit*8;
// in_length = s.strstart - s.block_start;
//
// for (dcode = 0; dcode < D_CODES; dcode++) {
// out_length += s.dyn_dtree[dcode*2]/*.Freq*/ * (5 + extra_dbits[dcode]);
// }
// out_length >>>= 3;
// //Tracev((stderr,"\nlast_lit %u, in %ld, out ~%ld(%ld%%) ",
// // s->last_lit, in_length, out_length,
// // 100L - out_length*100L/in_length));
// if (s.matches < (s.last_lit>>1)/*int /2*/ && out_length < (in_length>>1)/*int /2*/) {
// return true;
// }
// }
//#endif
return (s.last_lit === s.lit_bufsize-1);
/* We avoid equality with lit_bufsize because of wraparound at 64K
* on 16 bit machines and because stored blocks are restricted to
* 64K-1 bytes.
*/
}
exports._tr_init = _tr_init;
exports._tr_stored_block = _tr_stored_block;
exports._tr_flush_block = _tr_flush_block;
exports._tr_tally = _tr_tally;
exports._tr_align = _tr_align;
},{"../utils/common":86}],98:[function(_dereq_,module,exports){
'use strict';
function ZStream() {
/* next input byte */
this.input = null; // JS specific, because we have no pointers
this.next_in = 0;
/* number of bytes available at input */
this.avail_in = 0;
/* total number of input bytes read so far */
this.total_in = 0;
/* next output byte should be put there */
this.output = null; // JS specific, because we have no pointers
this.next_out = 0;
/* remaining free space at output */
this.avail_out = 0;
/* total number of bytes output so far */
this.total_out = 0;
/* last error message, NULL if no error */
this.msg = ''/*Z_NULL*/;
/* not visible by applications */
this.state = null;
/* best guess about the data type: binary or text */
this.data_type = 2/*Z_UNKNOWN*/;
/* adler32 value of the uncompressed data */
this.adler = 0;
}
module.exports = ZStream;
},{}]},{},[1]);
|
client/src/index.js | ahorrocks2/what_sounds_good_to_you | import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import 'semantic-ui-css/semantic.min.css';
import App from './App';
import registerServiceWorker from './registerServiceWorker';
registerServiceWorker();
const rootEl = document.getElementById('root')
ReactDOM.render(
<App />,
rootEl
)
if (module.hot) {
module.hot.accept('./App', () => {
const NextApp = require('./App').default
ReactDOM.render(
<NextApp />,
rootEl
)
})
} |
node_modules/react-bootstrap/es/NavbarCollapse.js | yeshdev1/Everydays-project | import _extends from 'babel-runtime/helpers/extends';
import _objectWithoutProperties from 'babel-runtime/helpers/objectWithoutProperties';
import _classCallCheck from 'babel-runtime/helpers/classCallCheck';
import _possibleConstructorReturn from 'babel-runtime/helpers/possibleConstructorReturn';
import _inherits from 'babel-runtime/helpers/inherits';
import React from 'react';
import PropTypes from 'prop-types';
import Collapse from './Collapse';
import { prefix } from './utils/bootstrapUtils';
var contextTypes = {
$bs_navbar: PropTypes.shape({
bsClass: PropTypes.string,
expanded: PropTypes.bool
})
};
var NavbarCollapse = function (_React$Component) {
_inherits(NavbarCollapse, _React$Component);
function NavbarCollapse() {
_classCallCheck(this, NavbarCollapse);
return _possibleConstructorReturn(this, _React$Component.apply(this, arguments));
}
NavbarCollapse.prototype.render = function render() {
var _props = this.props,
children = _props.children,
props = _objectWithoutProperties(_props, ['children']);
var navbarProps = this.context.$bs_navbar || { bsClass: 'navbar' };
var bsClassName = prefix(navbarProps, 'collapse');
return React.createElement(
Collapse,
_extends({ 'in': navbarProps.expanded }, props),
React.createElement(
'div',
{ className: bsClassName },
children
)
);
};
return NavbarCollapse;
}(React.Component);
NavbarCollapse.contextTypes = contextTypes;
export default NavbarCollapse; |
src/svg-icons/image/brightness-4.js | igorbt/material-ui | import React from 'react';
import pure from 'recompose/pure';
import SvgIcon from '../../SvgIcon';
let ImageBrightness4 = (props) => (
<SvgIcon {...props}>
<path d="M20 8.69V4h-4.69L12 .69 8.69 4H4v4.69L.69 12 4 15.31V20h4.69L12 23.31 15.31 20H20v-4.69L23.31 12 20 8.69zM12 18c-.89 0-1.74-.2-2.5-.55C11.56 16.5 13 14.42 13 12s-1.44-4.5-3.5-5.45C10.26 6.2 11.11 6 12 6c3.31 0 6 2.69 6 6s-2.69 6-6 6z"/>
</SvgIcon>
);
ImageBrightness4 = pure(ImageBrightness4);
ImageBrightness4.displayName = 'ImageBrightness4';
ImageBrightness4.muiName = 'SvgIcon';
export default ImageBrightness4;
|
Web Development/JS_frameworks/02. Mustache/02. Students/StudentsDatabase/Scripts/jquery-1.8.2.min.js | niki-funky/Telerik_Academy | /*! jQuery v1.8.2 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 bY(a,b){if(b in a)return b;var c=b.charAt(0).toUpperCase()+b.slice(1),d=b,e=bW.length;while(e--){b=bW[e]+c;if(b in a)return b}return d}function bZ(a,b){return a=b||a,p.css(a,"display")==="none"||!p.contains(a.ownerDocument,a)}function b$(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===""&&bZ(c)&&(e[f]=p._data(c,"olddisplay",cc(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=bP.exec(b);return d?Math.max(0,d[1]-(c||0))+(d[2]||"px"):b}function ca(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+bV[e],!0)),d?(c==="content"&&(f-=parseFloat(bH(a,"padding"+bV[e]))||0),c!=="margin"&&(f-=parseFloat(bH(a,"border"+bV[e]+"Width"))||0)):(f+=parseFloat(bH(a,"padding"+bV[e]))||0,c!=="padding"&&(f+=parseFloat(bH(a,"border"+bV[e]+"Width"))||0));return f}function cb(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==null){d=bH(a,b);if(d<0||d==null)d=a.style[b];if(bQ.test(d))return d;e=f&&(p.support.boxSizingReliable||d===a.style[b]),d=parseFloat(d)||0}return d+ca(a,b,c||(f?"border":"content"),e)+"px"}function cc(a){if(bS[a])return bS[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 bS[a]=c,c}function ci(a,b,c,d){var e;if(p.isArray(b))p.each(b,function(b,e){c||ce.test(a)?d(a,e):ci(a+"["+(typeof e=="object"?b:"")+"]",e,c,d)});else if(!c&&p.type(b)==="object")for(e in b)ci(a+"["+e+"]",b[e],c,d);else d(a,b)}function cz(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 cA(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===cv;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=cA(a,c,d,e,h,g)));return(l||!h)&&!g["*"]&&(h=cA(a,c,d,e,"*",g)),h}function cB(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 cC(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 cD(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 cL(){try{return new a.XMLHttpRequest}catch(b){}}function cM(){try{return new a.ActiveXObject("Microsoft.XMLHTTP")}catch(b){}}function cU(){return setTimeout(function(){cN=b},0),cN=p.now()}function cV(a,b){p.each(b,function(b,c){var d=(cT[b]||[]).concat(cT["*"]),e=0,f=d.length;for(;e<f;e++)if(d[e].call(a,b,c))return})}function cW(a,b,c){var d,e=0,f=0,g=cS.length,h=p.Deferred().always(function(){delete i.elem}),i=function(){var b=cN||cU(),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:cN||cU(),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;cX(k,j.opts.specialEasing);for(;e<g;e++){d=cS[e].call(j,a,k,j.opts);if(d)return d}return cV(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 cX(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 cY(a,b,c){var d,e,f,g,h,i,j,k,l=this,m=a.style,n={},o=[],q=a.nodeType&&bZ(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||cc(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(cP.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 cZ(a,b,c,d,e){return new cZ.prototype.init(a,b,c,d,e)}function c$(a,b){var c,d={height:a},e=0;b=b?1:0;for(;e<4;e+=2-b)c=bV[e],d["margin"+c]=d["padding"+c]=a;return b&&(d.opacity=d.width=a),d}function da(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=/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/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.2",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.toLowerCase()===b.toLowerCase()},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&&!o.call(" ")?function(a){return a==null?"":o.call(a)}:function(a){return a==null?"":(a+"").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||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")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){var e=p.type(c);e==="function"&&(!a.unique||!l.has(c))?i.push(c):c&&c.length&&e!=="string"&&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 a!=null?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)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=/(?:\{[\s\S]*\}|\[[\s\S]*\])$/,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.guid++: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-")||(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.length,e=c.shift(),f=p._queueHooks(a,b),g=function(){p.dequeue(a,b)};e==="inprogress"&&(e=c.shift(),d--),e&&(b==="fx"&&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 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&&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]+" ")<0&&(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]+" ")>=0)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)>=0)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,needsContext:f&&p.expr.match.needsContext.test(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&&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,l,m,n,o=(p._data(this,"events")||{})[c.type]||[],q=o.delegateCount,r=k.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"))for(f=c.target;f!=this;f=f.parentNode||this)if(f.disabled!==!0||c.type!=="click"){h={},j=[];for(d=0;d<q;d++)l=o[d],m=l.selector,h[m]===b&&(h[m]=l.needsContext?p(m,this).index(f)>=0:p.find(m,this,null,[f]).length),h[m]&&j.push(l);j.length&&u.push({elem:f,matches:j})}o.length>q&&u.push({elem:this,matches:o.slice(q)});for(d=0;d<u.length&&!c.isPropagationStopped();d++){i=u[d],c.currentTarget=i.elem;for(e=0;e<i.matches.length&&!c.isImmediatePropagationStopped();e++){l=i.matches[e];if(s||!c.namespace&&!l.namespace||c.namespace_re&&c.namespace_re.test(l.namespace))c.data=l.data,c.handleObj=l,g=((p.event.special[l.origType]||{}).handle||l.handler).apply(i.elem,r),g!==b&&(c.result=g,g===!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:{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 bc(a,b,c,d){c=c||[],b=b||r;var e,f,i,j,k=b.nodeType;if(!a||typeof a!="string")return c;if(k!==1&&k!==9)return[];i=g(b);if(!i&&!d)if(e=P.exec(a))if(j=e[1]){if(k===9){f=b.getElementById(j);if(!f||!f.parentNode)return c;if(f.id===j)return c.push(f),c}else if(b.ownerDocument&&(f=b.ownerDocument.getElementById(j))&&h(b,f)&&f.id===j)return c.push(f),c}else{if(e[2])return w.apply(c,x.call(b.getElementsByTagName(a),0)),c;if((j=e[3])&&_&&b.getElementsByClassName)return w.apply(c,x.call(b.getElementsByClassName(j),0)),c}return bp(a.replace(L,"$1"),b,c,d,i)}function bd(a){return function(b){var c=b.nodeName.toLowerCase();return c==="input"&&b.type===a}}function be(a){return function(b){var c=b.nodeName.toLowerCase();return(c==="input"||c==="button")&&b.type===a}}function bf(a){return z(function(b){return b=+b,z(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 bg(a,b,c){if(a===b)return c;var d=a.nextSibling;while(d){if(d===b)return-1;d=d.nextSibling}return 1}function bh(a,b){var c,d,f,g,h,i,j,k=C[o][a];if(k)return b?0:k.slice(0);h=a,i=[],j=e.preFilter;while(h){if(!c||(d=M.exec(h)))d&&(h=h.slice(d[0].length)),i.push(f=[]);c=!1;if(d=N.exec(h))f.push(c=new q(d.shift())),h=h.slice(c.length),c.type=d[0].replace(L," ");for(g in e.filter)(d=W[g].exec(h))&&(!j[g]||(d=j[g](d,r,!0)))&&(f.push(c=new q(d.shift())),h=h.slice(c.length),c.type=g,c.matches=d);if(!c)break}return b?h.length:h?bc.error(a):C(a,i).slice(0)}function bi(a,b,d){var e=b.dir,f=d&&b.dir==="parentNode",g=u++;return b.first?function(b,c,d){while(b=b[e])if(f||b.nodeType===1)return a(b,c,d)}:function(b,d,h){if(!h){var i,j=t+" "+g+" ",k=j+c;while(b=b[e])if(f||b.nodeType===1){if((i=b[o])===k)return b.sizset;if(typeof i=="string"&&i.indexOf(j)===0){if(b.sizset)return b}else{b[o]=k;if(a(b,d,h))return b.sizset=!0,b;b.sizset=!1}}}else while(b=b[e])if(f||b.nodeType===1)if(a(b,d,h))return b}}function bj(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 bk(a,b,c,d,e){var f,g=[],h=0,i=a.length,j=b!=null;for(;h<i;h++)if(f=a[h])if(!c||c(f,d,e))g.push(f),j&&b.push(h);return g}function bl(a,b,c,d,e,f){return d&&!d[o]&&(d=bl(d)),e&&!e[o]&&(e=bl(e,f)),z(function(f,g,h,i){if(f&&e)return;var j,k,l,m=[],n=[],o=g.length,p=f||bo(b||"*",h.nodeType?[h]:h,[],f),q=a&&(f||!b)?bk(p,m,a,h,i):p,r=c?e||(f?a:o||d)?[]:g:q;c&&c(q,r,h,i);if(d){l=bk(r,n),d(l,[],h,i),j=l.length;while(j--)if(k=l[j])r[n[j]]=!(q[n[j]]=k)}if(f){j=a&&r.length;while(j--)if(k=r[j])f[m[j]]=!(g[m[j]]=k)}else r=bk(r===g?r.splice(o,r.length):r),e?e(null,g,r,i):w.apply(g,r)})}function bm(a){var b,c,d,f=a.length,g=e.relative[a[0].type],h=g||e.relative[" "],i=g?1:0,j=bi(function(a){return a===b},h,!0),k=bi(function(a){return y.call(b,a)>-1},h,!0),m=[function(a,c,d){return!g&&(d||c!==l)||((b=c).nodeType?j(a,c,d):k(a,c,d))}];for(;i<f;i++)if(c=e.relative[a[i].type])m=[bi(bj(m),c)];else{c=e.filter[a[i].type].apply(null,a[i].matches);if(c[o]){d=++i;for(;d<f;d++)if(e.relative[a[d].type])break;return bl(i>1&&bj(m),i>1&&a.slice(0,i-1).join("").replace(L,"$1"),c,i<d&&bm(a.slice(i,d)),d<f&&bm(a=a.slice(d)),d<f&&a.join(""))}m.push(c)}return bj(m)}function bn(a,b){var d=b.length>0,f=a.length>0,g=function(h,i,j,k,m){var n,o,p,q=[],s=0,u="0",x=h&&[],y=m!=null,z=l,A=h||f&&e.find.TAG("*",m&&i.parentNode||i),B=t+=z==null?1:Math.E;y&&(l=i!==r&&i,c=g.el);for(;(n=A[u])!=null;u++){if(f&&n){for(o=0;p=a[o];o++)if(p(n,i,j)){k.push(n);break}y&&(t=B,c=++g.el)}d&&((n=!p&&n)&&s--,h&&x.push(n))}s+=u;if(d&&u!==s){for(o=0;p=b[o];o++)p(x,q,i,j);if(h){if(s>0)while(u--)!x[u]&&!q[u]&&(q[u]=v.call(k));q=bk(q)}w.apply(k,q),y&&!h&&q.length>0&&s+b.length>1&&bc.uniqueSort(k)}return y&&(t=B,l=z),x};return g.el=0,d?z(g):g}function bo(a,b,c,d){var e=0,f=b.length;for(;e<f;e++)bc(a,b[e],c,d);return c}function bp(a,b,c,d,f){var g,h,j,k,l,m=bh(a),n=m.length;if(!d&&m.length===1){h=m[0]=m[0].slice(0);if(h.length>2&&(j=h[0]).type==="ID"&&b.nodeType===9&&!f&&e.relative[h[1].type]){b=e.find.ID(j.matches[0].replace(V,""),b,f)[0];if(!b)return c;a=a.slice(h.shift().length)}for(g=W.POS.test(a)?-1:h.length-1;g>=0;g--){j=h[g];if(e.relative[k=j.type])break;if(l=e.find[k])if(d=l(j.matches[0].replace(V,""),R.test(h[0].type)&&b.parentNode||b,f)){h.splice(g,1),a=d.length&&h.join("");if(!a)return w.apply(c,x.call(d,0)),c;break}}}return i(a,m)(d,b,f,c,R.test(a)),c}function bq(){}var c,d,e,f,g,h,i,j,k,l,m=!0,n="undefined",o=("sizcache"+Math.random()).replace(".",""),q=String,r=a.document,s=r.documentElement,t=0,u=0,v=[].pop,w=[].push,x=[].slice,y=[].indexOf||function(a){var b=0,c=this.length;for(;b<c;b++)if(this[b]===a)return b;return-1},z=function(a,b){return a[o]=b==null||b,a},A=function(){var a={},b=[];return z(function(c,d){return b.push(c)>e.cacheLength&&delete a[b.shift()],a[c]=d},a)},B=A(),C=A(),D=A(),E="[\\x20\\t\\r\\n\\f]",F="(?:\\\\.|[-\\w]|[^\\x00-\\xa0])+",G=F.replace("w","w#"),H="([*^$|!~]?=)",I="\\["+E+"*("+F+")"+E+"*(?:"+H+E+"*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|("+G+")|)|)"+E+"*\\]",J=":("+F+")(?:\\((?:(['\"])((?:\\\\.|[^\\\\])*?)\\2|([^()[\\]]*|(?:(?:"+I+")|[^:]|\\\\.)*|.*))\\)|)",K=":(even|odd|eq|gt|lt|nth|first|last)(?:\\("+E+"*((?:-\\d)?\\d*)"+E+"*\\)|)(?=[^-]|$)",L=new RegExp("^"+E+"+|((?:^|[^\\\\])(?:\\\\.)*)"+E+"+$","g"),M=new RegExp("^"+E+"*,"+E+"*"),N=new RegExp("^"+E+"*([\\x20\\t\\r\\n\\f>+~])"+E+"*"),O=new RegExp(J),P=/^(?:#([\w\-]+)|(\w+)|\.([\w\-]+))$/,Q=/^:not/,R=/[\x20\t\r\n\f]*[+~]/,S=/:not\($/,T=/h\d/i,U=/input|select|textarea|button/i,V=/\\(?!\\)/g,W={ID:new RegExp("^#("+F+")"),CLASS:new RegExp("^\\.("+F+")"),NAME:new RegExp("^\\[name=['\"]?("+F+")['\"]?\\]"),TAG:new RegExp("^("+F.replace("w","w*")+")"),ATTR:new RegExp("^"+I),PSEUDO:new RegExp("^"+J),POS:new RegExp(K,"i"),CHILD:new RegExp("^:(only|nth|first|last)-child(?:\\("+E+"*(even|odd|(([+-]|)(\\d*)n|)"+E+"*(?:([+-]|)"+E+"*(\\d+)|))"+E+"*\\)|)","i"),needsContext:new RegExp("^"+E+"*[>+~]|"+K,"i")},X=function(a){var b=r.createElement("div");try{return a(b)}catch(c){return!1}finally{b=null}},Y=X(function(a){return a.appendChild(r.createComment("")),!a.getElementsByTagName("*").length}),Z=X(function(a){return a.innerHTML="<a href='#'></a>",a.firstChild&&typeof a.firstChild.getAttribute!==n&&a.firstChild.getAttribute("href")==="#"}),$=X(function(a){a.innerHTML="<select></select>";var b=typeof a.lastChild.getAttribute("multiple");return b!=="boolean"&&b!=="string"}),_=X(function(a){return a.innerHTML="<div class='hidden e'></div><div class='hidden'></div>",!a.getElementsByClassName||!a.getElementsByClassName("e").length?!1:(a.lastChild.className="e",a.getElementsByClassName("e").length===2)}),ba=X(function(a){a.id=o+0,a.innerHTML="<a name='"+o+"'></a><div name='"+o+"'></div>",s.insertBefore(a,s.firstChild);var b=r.getElementsByName&&r.getElementsByName(o).length===2+r.getElementsByName(o+0).length;return d=!r.getElementById(o),s.removeChild(a),b});try{x.call(s.childNodes,0)[0].nodeType}catch(bb){x=function(a){var b,c=[];for(;b=this[a];a++)c.push(b);return c}}bc.matches=function(a,b){return bc(a,null,null,b)},bc.matchesSelector=function(a,b){return bc(b,null,null,[a]).length>0},f=bc.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+=f(a)}else if(e===3||e===4)return a.nodeValue}else for(;b=a[d];d++)c+=f(b);return c},g=bc.isXML=function(a){var b=a&&(a.ownerDocument||a).documentElement;return b?b.nodeName!=="HTML":!1},h=bc.contains=s.contains?function(a,b){var c=a.nodeType===9?a.documentElement:a,d=b&&b.parentNode;return a===d||!!(d&&d.nodeType===1&&c.contains&&c.contains(d))}:s.compareDocumentPosition?function(a,b){return b&&!!(a.compareDocumentPosition(b)&16)}:function(a,b){while(b=b.parentNode)if(b===a)return!0;return!1},bc.attr=function(a,b){var c,d=g(a);return d||(b=b.toLowerCase()),(c=e.attrHandle[b])?c(a):d||$?a.getAttribute(b):(c=a.getAttributeNode(b),c?typeof a[b]=="boolean"?a[b]?b:null:c.specified?c.value:null:null)},e=bc.selectors={cacheLength:50,createPseudo:z,match:W,attrHandle:Z?{}:{href:function(a){return a.getAttribute("href",2)},type:function(a){return a.getAttribute("type")}},find:{ID:d?function(a,b,c){if(typeof b.getElementById!==n&&!c){var d=b.getElementById(a);return d&&d.parentNode?[d]:[]}}:function(a,c,d){if(typeof c.getElementById!==n&&!d){var e=c.getElementById(a);return e?e.id===a||typeof e.getAttributeNode!==n&&e.getAttributeNode("id").value===a?[e]:b:[]}},TAG:Y?function(a,b){if(typeof b.getElementsByTagName!==n)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},NAME:ba&&function(a,b){if(typeof b.getElementsByName!==n)return b.getElementsByName(name)},CLASS:_&&function(a,b,c){if(typeof b.getElementsByClassName!==n&&!c)return b.getElementsByClassName(a)}},relative:{">":{dir:"parentNode",first:!0}," ":{dir:"parentNode"},"+":{dir:"previousSibling",first:!0},"~":{dir:"previousSibling"}},preFilter:{ATTR:function(a){return a[1]=a[1].replace(V,""),a[3]=(a[4]||a[5]||"").replace(V,""),a[2]==="~="&&(a[3]=" "+a[3]+" "),a.slice(0,4)},CHILD:function(a){return a[1]=a[1].toLowerCase(),a[1]==="nth"?(a[2]||bc.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]&&bc.error(a[0]),a},PSEUDO:function(a){var b,c;if(W.CHILD.test(a[0]))return null;if(a[3])a[2]=a[3];else if(b=a[4])O.test(b)&&(c=bh(b,!0))&&(c=b.indexOf(")",b.length-c)-b.length)&&(b=b.slice(0,c),a[0]=a[0].slice(0,c)),a[2]=b;return a.slice(0,3)}},filter:{ID:d?function(a){return a=a.replace(V,""),function(b){return b.getAttribute("id")===a}}:function(a){return a=a.replace(V,""),function(b){var c=typeof b.getAttributeNode!==n&&b.getAttributeNode("id");return c&&c.value===a}},TAG:function(a){return a==="*"?function(){return!0}:(a=a.replace(V,"").toLowerCase(),function(b){return b.nodeName&&b.nodeName.toLowerCase()===a})},CLASS:function(a){var b=B[o][a];return b||(b=B(a,new RegExp("(^|"+E+")"+a+"("+E+"|$)"))),function(a){return b.test(a.className||typeof a.getAttribute!==n&&a.getAttribute("class")||"")}},ATTR:function(a,b,c){return function(d,e){var f=bc.attr(d,a);return f==null?b==="!=":b?(f+="",b==="="?f===c:b==="!="?f!==c:b==="^="?c&&f.indexOf(c)===0:b==="*="?c&&f.indexOf(c)>-1:b==="$="?c&&f.substr(f.length-c.length)===c:b==="~="?(" "+f+" ").indexOf(c)>-1:b==="|="?f===c||f.substr(0,c.length+1)===c+"-":!1):!0}},CHILD:function(a,b,c,d){return a==="nth"?function(a){var b,e,f=a.parentNode;if(c===1&&d===0)return!0;if(f){e=0;for(b=f.firstChild;b;b=b.nextSibling)if(b.nodeType===1){e++;if(a===b)break}}return e-=d,e===c||e%c===0&&e/c>=0}: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){var c,d=e.pseudos[a]||e.setFilters[a.toLowerCase()]||bc.error("unsupported pseudo: "+a);return d[o]?d(b):d.length>1?(c=[a,a,"",b],e.setFilters.hasOwnProperty(a.toLowerCase())?z(function(a,c){var e,f=d(a,b),g=f.length;while(g--)e=y.call(a,f[g]),a[e]=!(c[e]=f[g])}):function(a){return d(a,0,c)}):d}},pseudos:{not:z(function(a){var b=[],c=[],d=i(a.replace(L,"$1"));return d[o]?z(function(a,b,c,e){var f,g=d(a,null,e,[]),h=a.length;while(h--)if(f=g[h])a[h]=!(b[h]=f)}):function(a,e,f){return b[0]=a,d(b,null,f,c),!c.pop()}}),has:z(function(a){return function(b){return bc(a,b).length>0}}),contains:z(function(a){return function(b){return(b.textContent||b.innerText||f(b)).indexOf(a)>-1}}),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!e.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},header:function(a){return T.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:bd("radio"),checkbox:bd("checkbox"),file:bd("file"),password:bd("password"),image:bd("image"),submit:be("submit"),reset:be("reset"),button:function(a){var b=a.nodeName.toLowerCase();return b==="input"&&a.type==="button"||b==="button"},input:function(a){return U.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},first:bf(function(a,b,c){return[0]}),last:bf(function(a,b,c){return[b-1]}),eq:bf(function(a,b,c){return[c<0?c+b:c]}),even:bf(function(a,b,c){for(var d=0;d<b;d+=2)a.push(d);return a}),odd:bf(function(a,b,c){for(var d=1;d<b;d+=2)a.push(d);return a}),lt:bf(function(a,b,c){for(var d=c<0?c+b:c;--d>=0;)a.push(d);return a}),gt:bf(function(a,b,c){for(var d=c<0?c+b:c;++d<b;)a.push(d);return a})}},j=s.compareDocumentPosition?function(a,b){return a===b?(k=!0,0):(!a.compareDocumentPosition||!b.compareDocumentPosition?a.compareDocumentPosition:a.compareDocumentPosition(b)&4)?-1:1}:function(a,b){if(a===b)return k=!0,0;if(a.sourceIndex&&b.sourceIndex)return a.sourceIndex-b.sourceIndex;var c,d,e=[],f=[],g=a.parentNode,h=b.parentNode,i=g;if(g===h)return bg(a,b);if(!g)return-1;if(!h)return 1;while(i)e.unshift(i),i=i.parentNode;i=h;while(i)f.unshift(i),i=i.parentNode;c=e.length,d=f.length;for(var j=0;j<c&&j<d;j++)if(e[j]!==f[j])return bg(e[j],f[j]);return j===c?bg(a,f[j],-1):bg(e[j],b,1)},[0,0].sort(j),m=!k,bc.uniqueSort=function(a){var b,c=1;k=m,a.sort(j);if(k)for(;b=a[c];c++)b===a[c-1]&&a.splice(c--,1);return a},bc.error=function(a){throw new Error("Syntax error, unrecognized expression: "+a)},i=bc.compile=function(a,b){var c,d=[],e=[],f=D[o][a];if(!f){b||(b=bh(a)),c=b.length;while(c--)f=bm(b[c]),f[o]?d.push(f):e.push(f);f=D(a,bn(e,d))}return f},r.querySelectorAll&&function(){var a,b=bp,c=/'|\\/g,d=/\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g,e=[":focus"],f=[":active",":focus"],h=s.matchesSelector||s.mozMatchesSelector||s.webkitMatchesSelector||s.oMatchesSelector||s.msMatchesSelector;X(function(a){a.innerHTML="<select><option selected=''></option></select>",a.querySelectorAll("[selected]").length||e.push("\\["+E+"*(?:checked|disabled|ismap|multiple|readonly|selected|value)"),a.querySelectorAll(":checked").length||e.push(":checked")}),X(function(a){a.innerHTML="<p test=''></p>",a.querySelectorAll("[test^='']").length&&e.push("[*^$]="+E+"*(?:\"\"|'')"),a.innerHTML="<input type='hidden'/>",a.querySelectorAll(":enabled").length||e.push(":enabled",":disabled")}),e=new RegExp(e.join("|")),bp=function(a,d,f,g,h){if(!g&&!h&&(!e||!e.test(a))){var i,j,k=!0,l=o,m=d,n=d.nodeType===9&&a;if(d.nodeType===1&&d.nodeName.toLowerCase()!=="object"){i=bh(a),(k=d.getAttribute("id"))?l=k.replace(c,"\\$&"):d.setAttribute("id",l),l="[id='"+l+"'] ",j=i.length;while(j--)i[j]=l+i[j].join("");m=R.test(a)&&d.parentNode||d,n=i.join(",")}if(n)try{return w.apply(f,x.call(m.querySelectorAll(n),0)),f}catch(p){}finally{k||d.removeAttribute("id")}}return b(a,d,f,g,h)},h&&(X(function(b){a=h.call(b,"div");try{h.call(b,"[test!='']:sizzle"),f.push("!=",J)}catch(c){}}),f=new RegExp(f.join("|")),bc.matchesSelector=function(b,c){c=c.replace(d,"='$1']");if(!g(b)&&!f.test(c)&&(!e||!e.test(c)))try{var i=h.call(b,c);if(i||a||b.document&&b.document.nodeType!==11)return i}catch(j){}return bc(c,null,null,[b]).length>0})}(),e.pseudos.nth=e.pseudos.eq,e.filters=bq.prototype=e.pseudos,e.setFilters=new bq,bc.attr=p.attr,p.find=bc,p.expr=bc.selectors,p.expr[":"]=p.expr.pseudos,p.unique=bc.uniqueSort,p.text=bc.getText,p.isXMLDoc=bc.isXML,p.contains=bc.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.nodeType&&c[0]||c,c=c.ownerDocument||c,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=b===e&&bA,t=[];if(!b||typeof b.createDocumentFragment=="undefined")b=e;for(f=0;(h=a[f])!=null;f++){typeof h=="number"&&(h+="");if(!h)continue;if(typeof h=="string")if(!br.test(h))h=b.createTextNode(h);else{s=s||bk(b),l=b.createElement("div"),s.appendChild(l),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(g=n.length-1;g>=0;--g)p.nodeName(n[g],"tbody")&&!n[g].childNodes.length&&n[g].parentNode.removeChild(n[g])}!p.support.leadingWhitespace&&bn.test(h)&&l.insertBefore(b.createTextNode(bn.exec(h)[0]),l.firstChild),h=l.childNodes,l.parentNode.removeChild(l)}h.nodeType?t.push(h):p.merge(t,h)}l&&(h=l=s=null);if(!p.support.appendChecked)for(f=0;(h=t[f])!=null;f++)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(f=0;(h=t[f])!=null;f++)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,[f+1,0].concat(r)),f+=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.chrome?b.webkit=!0: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=/^(none|table(?!-c[ea]).+)/,bO=/^margin/,bP=new RegExp("^("+q+")(.*)$","i"),bQ=new RegExp("^("+q+")(?!px)[a-z%]+$","i"),bR=new RegExp("^([-+])=("+q+")","i"),bS={},bT={position:"absolute",visibility:"hidden",display:"block"},bU={letterSpacing:0,fontWeight:400},bV=["Top","Right","Bottom","Left"],bW=["Webkit","O","Moz","ms"],bX=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 b$(this,!0)},hide:function(){return b$(this)},toggle:function(a,b){var c=typeof a=="boolean";return p.isFunction(a)&&p.isFunction(b)?bX.apply(this,arguments):this.each(function(){(c?a:bZ(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]=bY(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=bR.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]=bY(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 bU&&(f=bU[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(b,c){var d,e,f,g,h=a.getComputedStyle(b,null),i=b.style;return h&&(d=h[c],d===""&&!p.contains(b.ownerDocument,b)&&(d=p.style(b,c)),bQ.test(d)&&bO.test(c)&&(e=i.width,f=i.minWidth,g=i.maxWidth,i.minWidth=i.maxWidth=i.width=d,d=h.width,i.width=e,i.minWidth=f,i.maxWidth=g)),d}: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]),bQ.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&&bN.test(bH(a,"display"))?p.swap(a,bT,function(){return cb(a,b,d)}):cb(a,b,d)},set:function(a,c,d){return b_(a,c,d?ca(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 bQ.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+bV[d]+b]=e[d]||e[d-2]||e[0];return f}},bO.test(a)||(p.cssHooks[a+b].set=b_)});var cd=/%20/g,ce=/\[\]$/,cf=/\r?\n/g,cg=/^(?:color|date|datetime|datetime-local|email|hidden|month|number|password|range|search|tel|text|time|url|week)$/i,ch=/^(?: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||ch.test(this.nodeName)||cg.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(cf,"\r\n")}}):{name:b.name,value:c.replace(cf,"\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)ci(d,a[d],c,f);return e.join("&").replace(cd,"+")};var cj,ck,cl=/#.*$/,cm=/^(.*?):[ \t]*([^\r\n]*)\r?$/mg,cn=/^(?:about|app|app\-storage|.+\-extension|file|res|widget):$/,co=/^(?:GET|HEAD)$/,cp=/^\/\//,cq=/\?/,cr=/<script\b[^<]*(?:(?!<\/script>)<[^<]*)*<\/script>/gi,cs=/([?&])_=[^&]*/,ct=/^([\w\+\.\-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/,cu=p.fn.load,cv={},cw={},cx=["*/"]+["*"];try{ck=f.href}catch(cy){ck=e.createElement("a"),ck.href="",ck=ck.href}cj=ct.exec(ck.toLowerCase())||[],p.fn.load=function(a,c,d){if(typeof a!="string"&&cu)return cu.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):c&&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(cr,"")).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?cB(a,p.ajaxSettings):(b=a,a=p.ajaxSettings),cB(a,b),a},ajaxSettings:{url:ck,isLocal:cn.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","*":cx},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:cz(cv),ajaxTransport:cz(cw),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=cC(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=cD(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=cm.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(cl,"").replace(cp,cj[1]+"//"),l.dataTypes=p.trim(l.dataType||"*").toLowerCase().split(s),l.crossDomain==null&&(i=ct.exec(l.url.toLowerCase())||!1,l.crossDomain=i&&i.join(":")+(i[3]?"":i[1]==="http:"?80:443)!==cj.join(":")+(cj[3]?"":cj[1]==="http:"?80:443)),l.data&&l.processData&&typeof l.data!="string"&&(l.data=p.param(l.data,l.traditional)),cA(cv,l,c,x);if(v===2)return x;j=l.global,l.type=l.type.toUpperCase(),l.hasContent=!co.test(l.type),j&&p.active++===0&&p.event.trigger("ajaxStart");if(!l.hasContent){l.data&&(l.url+=(cq.test(l.url)?"&":"?")+l.data,delete l.data),d=l.url;if(l.cache===!1){var z=p.now(),A=l.url.replace(cs,"$1_="+z);l.url=A+(A===l.url?(cq.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]!=="*"?", "+cx+"; 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=cA(cw,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 cE=[],cF=/\?/,cG=/(=)\?(?=&|$)|\?\?/,cH=p.now();p.ajaxSetup({jsonp:"callback",jsonpCallback:function(){var a=cE.pop()||p.expando+"_"+cH++;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&&cG.test(j),m=k&&!l&&typeof i=="string"&&!(c.contentType||"").indexOf("application/x-www-form-urlencoded")&&cG.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(cG,"$1"+f):m?c.data=i.replace(cG,"$1"+f):k&&(c.url+=(cF.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,cE.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 cI,cJ=a.ActiveXObject?function(){for(var a in cI)cI[a](0,1)}:!1,cK=0;p.ajaxSettings.xhr=a.ActiveXObject?function(){return!this.isLocal&&cL()||cM()}:cL,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,cJ&&delete cI[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=++cK,cJ&&(cI||(cI={},p(a).unload(cJ)),cI[g]=d),i.onreadystatechange=d):d()},abort:function(){d&&d(0,1)}}}});var cN,cO,cP=/^(?:toggle|show|hide)$/,cQ=new RegExp("^(?:([-+])=|)("+q+")([a-z%]*)$","i"),cR=/queueHooks$/,cS=[cY],cT={"*":[function(a,b){var c,d,e=this.createTween(a,b),f=cQ.exec(b),g=e.cur(),h=+g||0,i=1,j=20;if(f){c=+f[2],d=f[3]||(p.cssNumber[a]?"":"px");if(d!=="px"&&h){h=p.css(e.elem,a,!0)||c||1;do i=i||".5",h=h/i,p.style(e.elem,a,h+d);while(i!==(i=e.cur()/g)&&i!==1&&--j)}e.unit=d,e.start=h,e.end=f[1]?h+(f[1]+1)*c:c}return e}]};p.Animation=p.extend(cW,{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],cT[c]=cT[c]||[],cT[c].unshift(b)},prefilter:function(a,b){b?cS.unshift(a):cS.push(a)}}),p.Tween=cZ,cZ.prototype={constructor:cZ,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=cZ.propHooks[this.prop];return a&&a.get?a.get(this):cZ.propHooks._default.get(this)},run:function(a){var b,c=cZ.propHooks[this.prop];return this.options.duration?this.pos=b=p.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):cZ.propHooks._default.set(this),this}},cZ.prototype.init.prototype=cZ.prototype,cZ.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}}},cZ.propHooks.scrollTop=cZ.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(c$(b,!0),d,e,f)}}),p.fn.extend({fadeTo:function(a,b,c,d){return this.filter(bZ).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=cW(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&&cR.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:c$("show"),slideUp:c$("hide"),slideToggle:c$("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=cZ.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)&&!cO&&(cO=setInterval(p.fx.tick,p.fx.interval))},p.fx.interval=13,p.fx.stop=function(){clearInterval(cO),cO=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={top:0,left:0},k=this[0],l=k&&k.ownerDocument;if(!l)return;return(d=l.body)===k?p.offset.bodyOffset(k):(c=l.documentElement,p.contains(c,k)?(typeof k.getBoundingClientRect!="undefined"&&(j=k.getBoundingClientRect()),e=da(l),f=c.clientTop||d.clientTop||0,g=c.clientLeft||d.clientLeft||0,h=e.pageYOffset||c.scrollTop,i=e.pageXOffset||c.scrollLeft,{top:j.top+h-f,left:j.left+i-g}):j)},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=da(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,null)}})}),a.jQuery=a.$=p,typeof define=="function"&&define.amd&&define.amd.jQuery&&define("jquery",[],function(){return p})})(window); |
src/Parts/DetailPart/index.js | sqhtiamo/zaro | import React, { Component } from 'react';
import PropTypes from 'prop-types';
import styles from './style';
import filter from '../../utils/filter';
class DetailPart extends Component {
constructor(props) {
super(props);
this.state = {};
}
getValue(detail) {
this.detail = detail;
if (detail.format && detail.format !== '') {
if (detail.format === 'html') {
return (<span style={styles.value} dangerouslySetInnerHTML={{ __html: detail.value }} />);
}
return (<span style={styles.value}> {filter(detail.format, detail.value)} </span>);
}
return (<span style={styles.value}> {detail.value} </span>);
}
render() {
const { detailList, data, display } = this.props;
let contentStyle = styles.container;
if (detailList.length >= 10 && display === 'half') {
contentStyle = styles.halfContainer;
}
const comment = detailList.map((detail, idx) => {
const key = `${idx}-${detail.text}`;
const items = detail.items || [detail];
if (detail.isShow) {
const params = detail.isShowParams.map(p => data[p]);
if (!detail.isShow(...params)) {
return null;
}
}
return (
<div
key={key}
style={contentStyle}
>
<span
style={styles.text}
>
{detail.text}:
</span>
{
items.map((item) => {
const value = this.getValue(item);
const after = item.after ? <span style={styles.value}> {item.after} </span> : '';
const k = `inner-${item.key}`;
return (
<div key={k} style={styles.inline}>
{value}
{after}
</div>
);
})
}
</div>
);
}
);
return (
<div>
{comment}
</div>
);
}
}
DetailPart.propTypes = {
detailList: PropTypes.arrayOf(PropTypes.shape({})),
data: PropTypes.shape({}),
display: PropTypes.string
};
DetailPart.defaultProps = {
detailList: [],
data: {},
display: ''
};
export default DetailPart;
|
src/client/pages/project/TaskList.js | callmeJozo/MKRN | import React from 'react';
import { Link } from 'react-router';
import { Button, Icon, Menu, Dropdown, Modal, message } from 'antd';
import ProjectStore from '../../stores/project';
class ProjectDetailApi extends React.Component {
constructor(props) {
super(props);
this.state = {
projectUrl: this.props.params.url,
list: []
}
}
componentWillMount() {
ProjectStore.getTaskList(this.state.projectUrl, (err, list) => {
if (err) {
message.error(err, 3);
return;
}
this.setState({
list: list || []
})
})
}
render() {
let _id = this.props.params.id;
let listItems = this.state.list.map((item, index) => {
return (
<li className="item" key={item._id}>
<p>
<span className="name">{item.title}</span>
<span className="time">{item.startTime.substr(0, 10)}--{item.endTime.substr(0, 10)}</span>
</p>
<p>
<Link to={`/u/${item.owner._id}`}>
<span className="owner">{item.owner.username}</span>
</Link>
</p>
</li>
)
});
return (
<div className="api-module">
<div className="api-list-wrap">
<div className="header">
<span className="api-count">共{this.state.list.length}项</span>
<Link to={{ pathname: 'addtask', query: { projectUrl: this.state.projectUrl } }}>
<span className="api-add" title="添加任务"><Icon type="plus" /></span>
</Link>
</div>
<ul className="list">
{listItems}
</ul>
</div>
</div>
)
}
}
export default ProjectDetailApi;
|
packages/material-ui-icons/src/HeightSharp.js | kybarg/material-ui | import React from 'react';
import createSvgIcon from './utils/createSvgIcon';
export default createSvgIcon(
<path d="M13 6.99h3L12 3 8 6.99h3v10.02H8L12 21l4-3.99h-3z" />
, 'HeightSharp');
|
ajax/libs/rxjs/2.3.25/rx.all.compat.js | Olical/cdnjs | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
;(function (undefined) {
var objectTypes = {
'boolean': false,
'function': true,
'object': true,
'number': false,
'string': false,
'undefined': false
};
var root = (objectTypes[typeof window] && window) || this,
freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports,
freeModule = objectTypes[typeof module] && module && !module.nodeType && module,
moduleExports = freeModule && freeModule.exports === freeExports && freeExports,
freeGlobal = objectTypes[typeof global] && global;
if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) {
root = freeGlobal;
}
var Rx = {
internals: {},
config: {
Promise: root.Promise
},
helpers: { }
};
// Defaults
var noop = Rx.helpers.noop = function () { },
notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; },
isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; },
identity = Rx.helpers.identity = function (x) { return x; },
pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; },
just = Rx.helpers.just = function (value) { return function () { return value; }; },
defaultNow = Rx.helpers.defaultNow = (function () { return !!Date.now ? Date.now : function () { return +new Date; }; }()),
defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); },
defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); },
defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); },
defaultError = Rx.helpers.defaultError = function (err) { throw err; },
isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; },
asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); },
not = Rx.helpers.not = function (a) { return !a; },
isFunction = Rx.helpers.isFunction = (function () {
var isFn = function (value) {
return typeof value == 'function' || false;
}
// fallback for older versions of Chrome and Safari
if (isFn(/x/)) {
isFn = function(value) {
return typeof value == 'function' && toString.call(value) == '[object Function]';
};
}
return isFn;
}());
// Errors
var sequenceContainsNoElements = 'Sequence contains no elements.';
var argumentOutOfRange = 'Argument out of range';
var objectDisposed = 'Object has been disposed';
function checkDisposed(self) { if (self.isDisposed) { throw new Error(objectDisposed); } }
function cloneArray(arr) { for(var a = [], i = 0, len = arr.length; i < len; i++) { a.push(arr[i]); } return a;}
Rx.config.longStackSupport = false;
var hasStacks = false;
try {
throw new Error();
} catch (e) {
hasStacks = !!e.stack;
}
// All code after this point will be filtered from stack traces reported by RxJS
var rStartingLine = captureLine(), rFileName;
var STACK_JUMP_SEPARATOR = "From previous event:";
function makeStackTraceLong(error, observable) {
// If possible, transform the error stack trace by removing Node and RxJS
// cruft, then concatenating with the stack trace of `observable`.
if (hasStacks &&
observable.stack &&
typeof error === "object" &&
error !== null &&
error.stack &&
error.stack.indexOf(STACK_JUMP_SEPARATOR) === -1
) {
var stacks = [];
for (var o = observable; !!o; o = o.source) {
if (o.stack) {
stacks.unshift(o.stack);
}
}
stacks.unshift(error.stack);
var concatedStacks = stacks.join("\n" + STACK_JUMP_SEPARATOR + "\n");
error.stack = filterStackString(concatedStacks);
}
}
function filterStackString(stackString) {
var lines = stackString.split("\n"),
desiredLines = [];
for (var i = 0, len = lines.length; i < len; i++) {
var line = lines[i];
if (!isInternalFrame(line) && !isNodeFrame(line) && line) {
desiredLines.push(line);
}
}
return desiredLines.join("\n");
}
function isInternalFrame(stackLine) {
var fileNameAndLineNumber = getFileNameAndLineNumber(stackLine);
if (!fileNameAndLineNumber) {
return false;
}
var fileName = fileNameAndLineNumber[0], lineNumber = fileNameAndLineNumber[1];
return fileName === rFileName &&
lineNumber >= rStartingLine &&
lineNumber <= rEndingLine;
}
function isNodeFrame(stackLine) {
return stackLine.indexOf("(module.js:") !== -1 ||
stackLine.indexOf("(node.js:") !== -1;
}
function captureLine() {
if (!hasStacks) { return; }
try {
throw new Error();
} catch (e) {
var lines = e.stack.split("\n");
var firstLine = lines[0].indexOf("@") > 0 ? lines[1] : lines[2];
var fileNameAndLineNumber = getFileNameAndLineNumber(firstLine);
if (!fileNameAndLineNumber) { return; }
rFileName = fileNameAndLineNumber[0];
return fileNameAndLineNumber[1];
}
}
function getFileNameAndLineNumber(stackLine) {
// Named functions: "at functionName (filename:lineNumber:columnNumber)"
var attempt1 = /at .+ \((.+):(\d+):(?:\d+)\)$/.exec(stackLine);
if (attempt1) { return [attempt1[1], Number(attempt1[2])]; }
// Anonymous functions: "at filename:lineNumber:columnNumber"
var attempt2 = /at ([^ ]+):(\d+):(?:\d+)$/.exec(stackLine);
if (attempt2) { return [attempt2[1], Number(attempt2[2])]; }
// Firefox style: "function@filename:lineNumber or @filename:lineNumber"
var attempt3 = /.*@(.+):(\d+)$/.exec(stackLine);
if (attempt3) { return [attempt3[1], Number(attempt3[2])]; }
}
// Shim in iterator support
var $iterator$ = (typeof Symbol === 'function' && Symbol.iterator) ||
'_es6shim_iterator_';
// Bug for mozilla version
if (root.Set && typeof new root.Set()['@@iterator'] === 'function') {
$iterator$ = '@@iterator';
}
var doneEnumerator = Rx.doneEnumerator = { done: true, value: undefined };
var isIterable = Rx.helpers.isIterable = function (o) {
return o[$iterator$] !== undefined;
}
var isArrayLike = Rx.helpers.isArrayLike = function (o) {
return o && o.length !== undefined;
}
Rx.helpers.iterator = $iterator$;
var bindCallback = Rx.internals.bindCallback = function (func, thisArg, argCount) {
if (typeof thisArg === 'undefined') { return func; }
switch(argCount) {
case 0:
return function() {
return func.call(thisArg)
};
case 1:
return function(arg) {
return func.call(thisArg, arg);
}
case 2:
return function(value, index) {
return func.call(thisArg, value, index);
};
case 3:
return function(value, index, collection) {
return func.call(thisArg, value, index, collection);
};
}
return function() {
return func.apply(thisArg, arguments);
};
};
/** Used to determine if values are of the language type Object */
var dontEnums = ['toString',
'toLocaleString',
'valueOf',
'hasOwnProperty',
'isPrototypeOf',
'propertyIsEnumerable',
'constructor'],
dontEnumsLength = dontEnums.length;
/** `Object#toString` result shortcuts */
var argsClass = '[object Arguments]',
arrayClass = '[object Array]',
boolClass = '[object Boolean]',
dateClass = '[object Date]',
errorClass = '[object Error]',
funcClass = '[object Function]',
numberClass = '[object Number]',
objectClass = '[object Object]',
regexpClass = '[object RegExp]',
stringClass = '[object String]';
var toString = Object.prototype.toString,
hasOwnProperty = Object.prototype.hasOwnProperty,
supportsArgsClass = toString.call(arguments) == argsClass, // For less <IE9 && FF<4
supportNodeClass,
errorProto = Error.prototype,
objectProto = Object.prototype,
stringProto = String.prototype,
propertyIsEnumerable = objectProto.propertyIsEnumerable;
try {
supportNodeClass = !(toString.call(document) == objectClass && !({ 'toString': 0 } + ''));
} catch (e) {
supportNodeClass = true;
}
var nonEnumProps = {};
nonEnumProps[arrayClass] = nonEnumProps[dateClass] = nonEnumProps[numberClass] = { 'constructor': true, 'toLocaleString': true, 'toString': true, 'valueOf': true };
nonEnumProps[boolClass] = nonEnumProps[stringClass] = { 'constructor': true, 'toString': true, 'valueOf': true };
nonEnumProps[errorClass] = nonEnumProps[funcClass] = nonEnumProps[regexpClass] = { 'constructor': true, 'toString': true };
nonEnumProps[objectClass] = { 'constructor': true };
var support = {};
(function () {
var ctor = function() { this.x = 1; },
props = [];
ctor.prototype = { 'valueOf': 1, 'y': 1 };
for (var key in new ctor) { props.push(key); }
for (key in arguments) { }
// Detect if `name` or `message` properties of `Error.prototype` are enumerable by default.
support.enumErrorProps = propertyIsEnumerable.call(errorProto, 'message') || propertyIsEnumerable.call(errorProto, 'name');
// Detect if `prototype` properties are enumerable by default.
support.enumPrototypes = propertyIsEnumerable.call(ctor, 'prototype');
// Detect if `arguments` object indexes are non-enumerable
support.nonEnumArgs = key != 0;
// Detect if properties shadowing those on `Object.prototype` are non-enumerable.
support.nonEnumShadows = !/valueOf/.test(props);
}(1));
var isObject = Rx.internals.isObject = function(value) {
var type = typeof value;
return value && (type == 'function' || type == 'object') || false;
};
function keysIn(object) {
var result = [];
if (!isObject(object)) {
return result;
}
if (support.nonEnumArgs && object.length && isArguments(object)) {
object = slice.call(object);
}
var skipProto = support.enumPrototypes && typeof object == 'function',
skipErrorProps = support.enumErrorProps && (object === errorProto || object instanceof Error);
for (var key in object) {
if (!(skipProto && key == 'prototype') &&
!(skipErrorProps && (key == 'message' || key == 'name'))) {
result.push(key);
}
}
if (support.nonEnumShadows && object !== objectProto) {
var ctor = object.constructor,
index = -1,
length = dontEnumsLength;
if (object === (ctor && ctor.prototype)) {
var className = object === stringProto ? stringClass : object === errorProto ? errorClass : toString.call(object),
nonEnum = nonEnumProps[className];
}
while (++index < length) {
key = dontEnums[index];
if (!(nonEnum && nonEnum[key]) && hasOwnProperty.call(object, key)) {
result.push(key);
}
}
}
return result;
}
function internalFor(object, callback, keysFunc) {
var index = -1,
props = keysFunc(object),
length = props.length;
while (++index < length) {
var key = props[index];
if (callback(object[key], key, object) === false) {
break;
}
}
return object;
}
function internalForIn(object, callback) {
return internalFor(object, callback, keysIn);
}
function isNode(value) {
// IE < 9 presents DOM nodes as `Object` objects except they have `toString`
// methods that are `typeof` "string" and still can coerce nodes to strings
return typeof value.toString != 'function' && typeof (value + '') == 'string';
}
var isArguments = function(value) {
return (value && typeof value == 'object') ? toString.call(value) == argsClass : false;
}
// fallback for browsers that can't detect `arguments` objects by [[Class]]
if (!supportsArgsClass) {
isArguments = function(value) {
return (value && typeof value == 'object') ? hasOwnProperty.call(value, 'callee') : false;
};
}
var isEqual = Rx.internals.isEqual = function (x, y) {
return deepEquals(x, y, [], []);
};
/** @private
* Used for deep comparison
**/
function deepEquals(a, b, stackA, stackB) {
// exit early for identical values
if (a === b) {
// treat `+0` vs. `-0` as not equal
return a !== 0 || (1 / a == 1 / b);
}
var type = typeof a,
otherType = typeof b;
// exit early for unlike primitive values
if (a === a && (a == null || b == null ||
(type != 'function' && type != 'object' && otherType != 'function' && otherType != 'object'))) {
return false;
}
// compare [[Class]] names
var className = toString.call(a),
otherClass = toString.call(b);
if (className == argsClass) {
className = objectClass;
}
if (otherClass == argsClass) {
otherClass = objectClass;
}
if (className != otherClass) {
return false;
}
switch (className) {
case boolClass:
case dateClass:
// coerce dates and booleans to numbers, dates to milliseconds and booleans
// to `1` or `0` treating invalid dates coerced to `NaN` as not equal
return +a == +b;
case numberClass:
// treat `NaN` vs. `NaN` as equal
return (a != +a) ?
b != +b :
// but treat `-0` vs. `+0` as not equal
(a == 0 ? (1 / a == 1 / b) : a == +b);
case regexpClass:
case stringClass:
// coerce regexes to strings (http://es5.github.io/#x15.10.6.4)
// treat string primitives and their corresponding object instances as equal
return a == String(b);
}
var isArr = className == arrayClass;
if (!isArr) {
// exit for functions and DOM nodes
if (className != objectClass || (!support.nodeClass && (isNode(a) || isNode(b)))) {
return false;
}
// in older versions of Opera, `arguments` objects have `Array` constructors
var ctorA = !support.argsObject && isArguments(a) ? Object : a.constructor,
ctorB = !support.argsObject && isArguments(b) ? Object : b.constructor;
// non `Object` object instances with different constructors are not equal
if (ctorA != ctorB &&
!(hasOwnProperty.call(a, 'constructor') && hasOwnProperty.call(b, 'constructor')) &&
!(isFunction(ctorA) && ctorA instanceof ctorA && isFunction(ctorB) && ctorB instanceof ctorB) &&
('constructor' in a && 'constructor' in b)
) {
return false;
}
}
// assume cyclic structures are equal
// the algorithm for detecting cyclic structures is adapted from ES 5.1
// section 15.12.3, abstract operation `JO` (http://es5.github.io/#x15.12.3)
var initedStack = !stackA;
stackA || (stackA = []);
stackB || (stackB = []);
var length = stackA.length;
while (length--) {
if (stackA[length] == a) {
return stackB[length] == b;
}
}
var size = 0;
var result = true;
// add `a` and `b` to the stack of traversed objects
stackA.push(a);
stackB.push(b);
// recursively compare objects and arrays (susceptible to call stack limits)
if (isArr) {
// compare lengths to determine if a deep comparison is necessary
length = a.length;
size = b.length;
result = size == length;
if (result) {
// deep compare the contents, ignoring non-numeric properties
while (size--) {
var index = length,
value = b[size];
if (!(result = deepEquals(a[size], value, stackA, stackB))) {
break;
}
}
}
}
else {
// deep compare objects using `forIn`, instead of `forOwn`, to avoid `Object.keys`
// which, in this case, is more costly
internalForIn(b, function(value, key, b) {
if (hasOwnProperty.call(b, key)) {
// count the number of properties.
size++;
// deep compare each property value.
return (result = hasOwnProperty.call(a, key) && deepEquals(a[key], value, stackA, stackB));
}
});
if (result) {
// ensure both objects have the same number of properties
internalForIn(a, function(value, key, a) {
if (hasOwnProperty.call(a, key)) {
// `size` will be `-1` if `a` has more properties than `b`
return (result = --size > -1);
}
});
}
}
stackA.pop();
stackB.pop();
return result;
}
var hasProp = {}.hasOwnProperty,
slice = Array.prototype.slice;
var inherits = this.inherits = Rx.internals.inherits = function (child, parent) {
function __() { this.constructor = child; }
__.prototype = parent.prototype;
child.prototype = new __();
};
var addProperties = Rx.internals.addProperties = function (obj) {
for(var sources = [], i = 1, len = arguments.length; i < len; i++) { sources.push(arguments[i]); }
for (var idx = 0, ln = sources.length; idx < ln; idx++) {
var source = sources[idx];
for (var prop in source) {
obj[prop] = source[prop];
}
}
};
// Rx Utils
var addRef = Rx.internals.addRef = function (xs, r) {
return new AnonymousObservable(function (observer) {
return new CompositeDisposable(r.getDisposable(), xs.subscribe(observer));
});
};
function arrayInitialize(count, factory) {
var a = new Array(count);
for (var i = 0; i < count; i++) {
a[i] = factory();
}
return a;
}
// Utilities
if (!Function.prototype.bind) {
Function.prototype.bind = function (that) {
var target = this,
args = slice.call(arguments, 1);
var bound = function () {
if (this instanceof bound) {
function F() { }
F.prototype = target.prototype;
var self = new F();
var result = target.apply(self, args.concat(slice.call(arguments)));
if (Object(result) === result) {
return result;
}
return self;
} else {
return target.apply(that, args.concat(slice.call(arguments)));
}
};
return bound;
};
}
if (!Array.prototype.forEach) {
Array.prototype.forEach = function (callback, thisArg) {
var T, k;
if (this == null) {
throw new TypeError(" this is null or not defined");
}
var O = Object(this);
var len = O.length >>> 0;
if (typeof callback !== "function") {
throw new TypeError(callback + " is not a function");
}
if (arguments.length > 1) {
T = thisArg;
}
k = 0;
while (k < len) {
var kValue;
if (k in O) {
kValue = O[k];
callback.call(T, kValue, k, O);
}
k++;
}
};
}
var boxedString = Object("a"),
splitString = boxedString[0] != "a" || !(0 in boxedString);
if (!Array.prototype.every) {
Array.prototype.every = function every(fun /*, thisp */) {
var object = Object(this),
self = splitString && {}.toString.call(this) == stringClass ?
this.split("") :
object,
length = self.length >>> 0,
thisp = arguments[1];
if ({}.toString.call(fun) != funcClass) {
throw new TypeError(fun + " is not a function");
}
for (var i = 0; i < length; i++) {
if (i in self && !fun.call(thisp, self[i], i, object)) {
return false;
}
}
return true;
};
}
if (!Array.prototype.map) {
Array.prototype.map = function map(fun /*, thisp*/) {
var object = Object(this),
self = splitString && {}.toString.call(this) == stringClass ?
this.split("") :
object,
length = self.length >>> 0,
result = Array(length),
thisp = arguments[1];
if ({}.toString.call(fun) != funcClass) {
throw new TypeError(fun + " is not a function");
}
for (var i = 0; i < length; i++) {
if (i in self) {
result[i] = fun.call(thisp, self[i], i, object);
}
}
return result;
};
}
if (!Array.prototype.filter) {
Array.prototype.filter = function (predicate) {
var results = [], item, t = new Object(this);
for (var i = 0, len = t.length >>> 0; i < len; i++) {
item = t[i];
if (i in t && predicate.call(arguments[1], item, i, t)) {
results.push(item);
}
}
return results;
};
}
if (!Array.isArray) {
Array.isArray = function (arg) {
return {}.toString.call(arg) == arrayClass;
};
}
if (!Array.prototype.indexOf) {
Array.prototype.indexOf = function indexOf(searchElement) {
var t = Object(this);
var len = t.length >>> 0;
if (len === 0) {
return -1;
}
var n = 0;
if (arguments.length > 1) {
n = Number(arguments[1]);
if (n !== n) {
n = 0;
} else if (n !== 0 && n != Infinity && n !== -Infinity) {
n = (n > 0 || -1) * Math.floor(Math.abs(n));
}
}
if (n >= len) {
return -1;
}
var k = n >= 0 ? n : Math.max(len - Math.abs(n), 0);
for (; k < len; k++) {
if (k in t && t[k] === searchElement) {
return k;
}
}
return -1;
};
}
// Fix for Tessel
if (!Object.prototype.propertyIsEnumerable) {
Object.prototype.propertyIsEnumerable = function (key) {
for (var k in this) { if (k === key) { return true; } }
return false;
};
}
if (!Object.keys) {
Object.keys = (function() {
'use strict';
var hasOwnProperty = Object.prototype.hasOwnProperty,
hasDontEnumBug = !({ toString: null }).propertyIsEnumerable('toString');
return function(obj) {
if (typeof obj !== 'object' && (typeof obj !== 'function' || obj === null)) {
throw new TypeError('Object.keys called on non-object');
}
var result = [], prop, i;
for (prop in obj) {
if (hasOwnProperty.call(obj, prop)) {
result.push(prop);
}
}
if (hasDontEnumBug) {
for (i = 0; i < dontEnumsLength; i++) {
if (hasOwnProperty.call(obj, dontEnums[i])) {
result.push(dontEnums[i]);
}
}
}
return result;
};
}());
}
// Collections
function IndexedItem(id, value) {
this.id = id;
this.value = value;
}
IndexedItem.prototype.compareTo = function (other) {
var c = this.value.compareTo(other.value);
c === 0 && (c = this.id - other.id);
return c;
};
// Priority Queue for Scheduling
var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) {
this.items = new Array(capacity);
this.length = 0;
};
var priorityProto = PriorityQueue.prototype;
priorityProto.isHigherPriority = function (left, right) {
return this.items[left].compareTo(this.items[right]) < 0;
};
priorityProto.percolate = function (index) {
if (index >= this.length || index < 0) { return; }
var parent = index - 1 >> 1;
if (parent < 0 || parent === index) { return; }
if (this.isHigherPriority(index, parent)) {
var temp = this.items[index];
this.items[index] = this.items[parent];
this.items[parent] = temp;
this.percolate(parent);
}
};
priorityProto.heapify = function (index) {
+index || (index = 0);
if (index >= this.length || index < 0) { return; }
var left = 2 * index + 1,
right = 2 * index + 2,
first = index;
if (left < this.length && this.isHigherPriority(left, first)) {
first = left;
}
if (right < this.length && this.isHigherPriority(right, first)) {
first = right;
}
if (first !== index) {
var temp = this.items[index];
this.items[index] = this.items[first];
this.items[first] = temp;
this.heapify(first);
}
};
priorityProto.peek = function () { return this.items[0].value; };
priorityProto.removeAt = function (index) {
this.items[index] = this.items[--this.length];
this.items[this.length] = undefined;
this.heapify();
};
priorityProto.dequeue = function () {
var result = this.peek();
this.removeAt(0);
return result;
};
priorityProto.enqueue = function (item) {
var index = this.length++;
this.items[index] = new IndexedItem(PriorityQueue.count++, item);
this.percolate(index);
};
priorityProto.remove = function (item) {
for (var i = 0; i < this.length; i++) {
if (this.items[i].value === item) {
this.removeAt(i);
return true;
}
}
return false;
};
PriorityQueue.count = 0;
/**
* Represents a group of disposable resources that are disposed together.
* @constructor
*/
var CompositeDisposable = Rx.CompositeDisposable = function () {
var args = [];
if (Array.isArray(arguments[0])) {
args = arguments[0];
} else {
for(var i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
}
this.disposables = args;
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;
for(var currentDisposables = [], i = 0, len = this.disposables.length; i < len; i++) { currentDisposables.push(this.disposables[i]); }
this.disposables = [];
this.length = 0;
for (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 () {
for(var currentDisposables = [], ix = 0, len = this.disposables.length; i < len; i++) { currentDisposables.push(this.disposables[i]); }
return currentDisposables;
};
/**
* Provides a set of static methods for creating Disposables.
*
* @constructor
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
*/
var Disposable = Rx.Disposable = function (action) {
this.isDisposed = false;
this.action = action || noop;
};
/** Performs the task of cleaning up resources. */
Disposable.prototype.dispose = function () {
if (!this.isDisposed) {
this.action();
this.isDisposed = true;
}
};
/**
* Creates a disposable object that invokes the specified action when disposed.
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
* @return {Disposable} The disposable object that runs the given action upon disposal.
*/
var disposableCreate = Disposable.create = function (action) { return new Disposable(action); };
/**
* Gets the disposable that does nothing when disposed.
*/
var disposableEmpty = Disposable.empty = { dispose: noop };
var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function () {
function BooleanDisposable () {
this.isDisposed = false;
this.current = null;
}
var booleanDisposablePrototype = BooleanDisposable.prototype;
/**
* Gets the underlying disposable.
* @return The underlying disposable.
*/
booleanDisposablePrototype.getDisposable = function () {
return this.current;
};
/**
* Sets the underlying disposable.
* @param {Disposable} value The new underlying disposable.
*/
booleanDisposablePrototype.setDisposable = function (value) {
var shouldDispose = this.isDisposed;
if (!shouldDispose) {
var old = this.current;
this.current = value;
}
old && old.dispose();
shouldDispose && value && value.dispose();
};
/**
* Disposes the underlying disposable as well as all future replacements.
*/
booleanDisposablePrototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var old = this.current;
this.current = null;
}
old && old.dispose();
};
return BooleanDisposable;
}());
var SerialDisposable = Rx.SerialDisposable = SingleAssignmentDisposable;
/**
* Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed.
*/
var RefCountDisposable = Rx.RefCountDisposable = (function () {
function InnerDisposable(disposable) {
this.disposable = disposable;
this.disposable.count++;
this.isInnerDisposed = false;
}
InnerDisposable.prototype.dispose = function () {
if (!this.disposable.isDisposed && !this.isInnerDisposed) {
this.isInnerDisposed = true;
this.disposable.count--;
if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) {
this.disposable.isDisposed = true;
this.disposable.underlyingDisposable.dispose();
}
}
};
/**
* Initializes a new instance of the RefCountDisposable with the specified disposable.
* @constructor
* @param {Disposable} disposable Underlying disposable.
*/
function RefCountDisposable(disposable) {
this.underlyingDisposable = disposable;
this.isDisposed = false;
this.isPrimaryDisposed = false;
this.count = 0;
}
/**
* Disposes the underlying disposable only when all dependent disposables have been disposed
*/
RefCountDisposable.prototype.dispose = function () {
if (!this.isDisposed && !this.isPrimaryDisposed) {
this.isPrimaryDisposed = true;
if (this.count === 0) {
this.isDisposed = true;
this.underlyingDisposable.dispose();
}
}
};
/**
* Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable.
* @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime.
*/
RefCountDisposable.prototype.getDisposable = function () {
return this.isDisposed ? disposableEmpty : new InnerDisposable(this);
};
return RefCountDisposable;
})();
function ScheduledDisposable(scheduler, disposable) {
this.scheduler = scheduler;
this.disposable = disposable;
this.isDisposed = false;
}
function scheduleItem(s, self) {
if (!self.isDisposed) {
self.isDisposed = true;
self.disposable.dispose();
}
}
ScheduledDisposable.prototype.dispose = function () {
this.scheduler.scheduleWithState(this, scheduleItem);
};
var ScheduledItem = Rx.internals.ScheduledItem = function (scheduler, state, action, dueTime, comparer) {
this.scheduler = scheduler;
this.state = state;
this.action = action;
this.dueTime = dueTime;
this.comparer = comparer || defaultSubComparer;
this.disposable = new SingleAssignmentDisposable();
}
ScheduledItem.prototype.invoke = function () {
this.disposable.setDisposable(this.invokeCore());
};
ScheduledItem.prototype.compareTo = function (other) {
return this.comparer(this.dueTime, other.dueTime);
};
ScheduledItem.prototype.isCancelled = function () {
return this.disposable.isDisposed;
};
ScheduledItem.prototype.invokeCore = function () {
return this.action(this.scheduler, this.state);
};
/** Provides a set of static properties to access commonly used schedulers. */
var Scheduler = Rx.Scheduler = (function () {
function Scheduler(now, schedule, scheduleRelative, scheduleAbsolute) {
this.now = now;
this._schedule = schedule;
this._scheduleRelative = scheduleRelative;
this._scheduleAbsolute = scheduleAbsolute;
}
function invokeAction(scheduler, action) {
action();
return disposableEmpty;
}
var schedulerProto = Scheduler.prototype;
/**
* Schedules an action to be executed.
* @param {Function} action Action to execute.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.schedule = function (action) {
return this._schedule(action, invokeAction);
};
/**
* Schedules an action to be executed.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithState = function (state, action) {
return this._schedule(state, action);
};
/**
* Schedules an action to be executed after the specified relative due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelative = function (dueTime, action) {
return this._scheduleRelative(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed after dueTime.
* @param state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number} dueTime Relative time after which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative(state, dueTime, action);
};
/**
* Schedules an action to be executed at the specified absolute due time.
* @param {Function} action Action to execute.
* @param {Number} dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsolute = function (dueTime, action) {
return this._scheduleAbsolute(action, dueTime, invokeAction);
};
/**
* Schedules an action to be executed at dueTime.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to be executed.
* @param {Number}dueTime Absolute time at which to execute the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute(state, dueTime, action);
};
/** Gets the current time according to the local machine's system clock. */
Scheduler.now = defaultNow;
/**
* Normalizes the specified TimeSpan value to a positive value.
* @param {Number} timeSpan The time span value to normalize.
* @returns {Number} The specified TimeSpan value if it is zero or positive; otherwise, 0
*/
Scheduler.normalize = function (timeSpan) {
timeSpan < 0 && (timeSpan = 0);
return timeSpan;
};
return Scheduler;
}());
var normalizeTime = Scheduler.normalize;
(function (schedulerProto) {
function invokeRecImmediate(scheduler, pair) {
var state = pair.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](state2, dueTime1, function (scheduler1, state3) {
if (isAdded) {
group.remove(d);
} else {
isDone = true;
}
recursiveAction(state3);
return disposableEmpty;
});
if (!isDone) {
group.add(d);
isAdded = true;
}
});
};
recursiveAction(state);
return group;
}
function scheduleInnerRecursive(action, self) {
action(function(dt) { self(action, dt); });
}
/**
* Schedules an action to be executed recursively.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursive = function (action) {
return this.scheduleRecursiveWithState(action, function (_action, self) {
_action(function () { self(_action); }); });
};
/**
* Schedules an action to be executed recursively.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in recursive invocation state.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithState = function (state, action) {
return this.scheduleWithState({ first: state, second: action }, invokeRecImmediate);
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified relative time.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelative = function (dueTime, action) {
return this.scheduleRecursiveWithRelativeAndState(action, dueTime, scheduleInnerRecursive);
};
/**
* Schedules an action to be executed recursively after a specified relative due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Relative time after which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithRelativeAndState = function (state, dueTime, action) {
return this._scheduleRelative({ first: state, second: action }, dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithRelativeAndState');
});
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Function} action Action to execute recursively. The parameter passed to the action is used to trigger recursive scheduling of the action at the specified absolute time.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsolute = function (dueTime, action) {
return this.scheduleRecursiveWithAbsoluteAndState(action, dueTime, scheduleInnerRecursive);
};
/**
* Schedules an action to be executed recursively at a specified absolute due time.
* @param {Mixed} state State passed to the action to be executed.
* @param {Function} action Action to execute recursively. The last parameter passed to the action is used to trigger recursive scheduling of the action, passing in the recursive due time and invocation state.
* @param {Number}dueTime Absolute time at which to execute the action for the first time.
* @returns {Disposable} The disposable object used to cancel the scheduled action (best effort).
*/
schedulerProto.scheduleRecursiveWithAbsoluteAndState = function (state, dueTime, action) {
return this._scheduleAbsolute({ first: state, second: action }, dueTime, function (s, p) {
return invokeRecDate(s, p, 'scheduleWithAbsoluteAndState');
});
};
}(Scheduler.prototype));
(function (schedulerProto) {
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
Scheduler.prototype.schedulePeriodic = function (period, action) {
return this.schedulePeriodicWithState(null, period, action);
};
/**
* Schedules a periodic piece of work by dynamically discovering the scheduler's capabilities. The periodic task will be scheduled using window.setInterval for the base implementation.
* @param {Mixed} state Initial state passed to the action upon the first iteration.
* @param {Number} period Period for running the work periodically.
* @param {Function} action Action to be executed, potentially updating the state.
* @returns {Disposable} The disposable object used to cancel the scheduled recurring action (best effort).
*/
Scheduler.prototype.schedulePeriodicWithState = function(state, period, action) {
if (typeof root.setInterval === 'undefined') { throw new Error('Periodic scheduling not supported.'); }
var s = state;
var id = root.setInterval(function () {
s = action(s);
}, period);
return disposableCreate(function () {
root.clearInterval(id);
});
};
}(Scheduler.prototype));
(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 = this.now() + normalizeTime(dueTime);
while (dt - this.now() > 0) { }
return action(this, state);
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
}());
/**
* Gets a scheduler that schedules work as soon as possible on the current thread.
*/
var currentThreadScheduler = Scheduler.currentThread = (function () {
var queue;
function runTrampoline (q) {
while (q.length > 0) {
var item = q.dequeue();
if (!item.isCancelled()) {
// Note, do not schedule blocking work!
while (item.dueTime - Scheduler.now() > 0) {
}
!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;
var localTimer = (function () {
var localSetTimeout, localClearTimeout = noop;
if ('WScript' in this) {
localSetTimeout = function (fn, time) {
WScript.Sleep(time);
fn();
};
} else if (!!root.setTimeout) {
localSetTimeout = root.setTimeout;
localClearTimeout = root.clearTimeout;
} else {
throw new Error('No concurrency detected!');
}
return {
setTimeout: localSetTimeout,
clearTimeout: localClearTimeout
};
}());
var localSetTimeout = localTimer.setTimeout,
localClearTimeout = localTimer.clearTimeout;
(function () {
var reNative = RegExp('^' +
String(toString)
.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
.replace(/toString| for [^\]]+/g, '.*?') + '$'
);
var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' &&
!reNative.test(setImmediate) && setImmediate,
clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' &&
!reNative.test(clearImmediate) && clearImmediate;
function postMessageSupported () {
// Ensure not in a worker
if (!root.postMessage || root.importScripts) { return false; }
var isAsync = false,
oldHandler = root.onmessage;
// Test for async
root.onmessage = function () { isAsync = true; };
root.postMessage('', '*');
root.onmessage = oldHandler;
return isAsync;
}
// Use in order, setImmediate, nextTick, postMessage, MessageChannel, script readystatechanged, setTimeout
if (typeof setImmediate === 'function') {
scheduleMethod = setImmediate;
clearMethod = clearImmediate;
} else if (typeof process !== 'undefined' && {}.toString.call(process) === '[object process]') {
scheduleMethod = process.nextTick;
} else if (postMessageSupported()) {
var MSG_PREFIX = 'ms.rx.schedule' + Math.random(),
tasks = {},
taskId = 0;
var onGlobalPostMessage = function (event) {
// Only if we're a match to avoid any other global events
if (typeof event.data === 'string' && event.data.substring(0, MSG_PREFIX.length) === MSG_PREFIX) {
var handleId = event.data.substring(MSG_PREFIX.length),
action = tasks[handleId];
action();
delete tasks[handleId];
}
}
if (root.addEventListener) {
root.addEventListener('message', onGlobalPostMessage, false);
} else {
root.attachEvent('onmessage', onGlobalPostMessage, false);
}
scheduleMethod = function (action) {
var currentId = taskId++;
tasks[currentId] = action;
root.postMessage(MSG_PREFIX + currentId, '*');
};
} else if (!!root.MessageChannel) {
var channel = new root.MessageChannel(),
channelTasks = {},
channelTaskId = 0;
channel.port1.onmessage = function (event) {
var id = event.data,
action = channelTasks[id];
action();
delete channelTasks[id];
};
scheduleMethod = function (action) {
var id = channelTaskId++;
channelTasks[id] = action;
channel.port2.postMessage(id);
};
} else if ('document' in root && 'onreadystatechange' in root.document.createElement('script')) {
scheduleMethod = function (action) {
var scriptElement = root.document.createElement('script');
scriptElement.onreadystatechange = function () {
action();
scriptElement.onreadystatechange = null;
scriptElement.parentNode.removeChild(scriptElement);
scriptElement = null;
};
root.document.documentElement.appendChild(scriptElement);
};
} else {
scheduleMethod = function (action) { return localSetTimeout(action, 0); };
clearMethod = localClearTimeout;
}
}());
/**
* Gets a scheduler that schedules work via a timed callback based upon platform.
*/
var timeoutScheduler = Scheduler.timeout = (function () {
function scheduleNow(state, action) {
var scheduler = this,
disposable = new SingleAssignmentDisposable();
var id = scheduleMethod(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
});
return new CompositeDisposable(disposable, disposableCreate(function () {
clearMethod(id);
}));
}
function scheduleRelative(state, dueTime, action) {
var scheduler = this,
dt = Scheduler.normalize(dueTime);
if (dt === 0) {
return scheduler.scheduleWithState(state, action);
}
var disposable = new SingleAssignmentDisposable();
var id = localSetTimeout(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
}, dt);
return new CompositeDisposable(disposable, disposableCreate(function () {
localClearTimeout(id);
}));
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
})();
var CatchScheduler = (function (__super__) {
function scheduleNow(state, action) {
return this._scheduler.scheduleWithState(state, this._wrap(action));
}
function scheduleRelative(state, dueTime, action) {
return this._scheduler.scheduleWithRelativeAndState(state, dueTime, this._wrap(action));
}
function scheduleAbsolute(state, dueTime, action) {
return this._scheduler.scheduleWithAbsoluteAndState(state, dueTime, this._wrap(action));
}
inherits(CatchScheduler, __super__);
function CatchScheduler(scheduler, handler) {
this._scheduler = scheduler;
this._handler = handler;
this._recursiveOriginal = null;
this._recursiveWrapper = null;
__super__.call(this, this._scheduler.now.bind(this._scheduler), scheduleNow, scheduleRelative, scheduleAbsolute);
}
CatchScheduler.prototype._clone = function (scheduler) {
return new CatchScheduler(scheduler, this._handler);
};
CatchScheduler.prototype._wrap = function (action) {
var parent = this;
return function (self, state) {
try {
return action(parent._getRecursiveWrapper(self), state);
} catch (e) {
if (!parent._handler(e)) { throw e; }
return disposableEmpty;
}
};
};
CatchScheduler.prototype._getRecursiveWrapper = function (scheduler) {
if (this._recursiveOriginal !== scheduler) {
this._recursiveOriginal = scheduler;
var wrapper = this._clone(scheduler);
wrapper._recursiveOriginal = scheduler;
wrapper._recursiveWrapper = wrapper;
this._recursiveWrapper = wrapper;
}
return this._recursiveWrapper;
};
CatchScheduler.prototype.schedulePeriodicWithState = function (state, period, action) {
var self = this, failed = false, d = new SingleAssignmentDisposable();
d.setDisposable(this._scheduler.schedulePeriodicWithState(state, period, function (state1) {
if (failed) { return null; }
try {
return action(state1);
} catch (e) {
failed = true;
if (!self._handler(e)) { throw e; }
d.dispose();
return null;
}
}));
return d;
};
return CatchScheduler;
}(Scheduler));
/**
* Represents a notification to an observer.
*/
var Notification = Rx.Notification = (function () {
function Notification(kind, hasValue) {
this.hasValue = hasValue == null ? false : hasValue;
this.kind = kind;
}
/**
* Invokes the delegate corresponding to the notification or the observer's method corresponding to the notification and returns the produced result.
*
* @memberOf Notification
* @param {Any} observerOrOnNext Delegate to invoke for an OnNext notification or Observer to invoke the notification on..
* @param {Function} onError Delegate to invoke for an OnError notification.
* @param {Function} onCompleted Delegate to invoke for an OnCompleted notification.
* @returns {Any} Result produced by the observation.
*/
Notification.prototype.accept = function (observerOrOnNext, onError, onCompleted) {
return observerOrOnNext && typeof observerOrOnNext === 'object' ?
this._acceptObservable(observerOrOnNext) :
this._accept(observerOrOnNext, onError, onCompleted);
};
/**
* Returns an observable sequence with a single notification.
*
* @memberOf Notifications
* @param {Scheduler} [scheduler] Scheduler to send out the notification calls on.
* @returns {Observable} The observable sequence that surfaces the behavior of the notification upon subscription.
*/
Notification.prototype.toObservable = function (scheduler) {
var notification = this;
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
notification._acceptObservable(observer);
notification.kind === 'N' && observer.onCompleted();
});
});
};
return Notification;
})();
/**
* Creates an object that represents an OnNext notification to an observer.
* @param {Any} value The value contained in the notification.
* @returns {Notification} The OnNext notification containing the value.
*/
var notificationCreateOnNext = Notification.createOnNext = (function () {
function _accept (onNext) { return onNext(this.value); }
function _acceptObservable(observer) { return observer.onNext(this.value); }
function toString () { return 'OnNext(' + this.value + ')'; }
return function (value) {
var notification = new Notification('N', true);
notification.value = value;
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
/**
* Creates an object that represents an OnError notification to an observer.
* @param {Any} error The exception contained in the notification.
* @returns {Notification} The OnError notification containing the exception.
*/
var notificationCreateOnError = Notification.createOnError = (function () {
function _accept (onNext, onError) { return onError(this.exception); }
function _acceptObservable(observer) { return observer.onError(this.exception); }
function toString () { return 'OnError(' + this.exception + ')'; }
return function (e) {
var notification = new Notification('E');
notification.exception = e;
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
/**
* Creates an object that represents an OnCompleted notification to an observer.
* @returns {Notification} The OnCompleted notification.
*/
var notificationCreateOnCompleted = Notification.createOnCompleted = (function () {
function _accept (onNext, onError, onCompleted) { return onCompleted(); }
function _acceptObservable(observer) { return observer.onCompleted(); }
function toString () { return 'OnCompleted()'; }
return function () {
var notification = new Notification('C');
notification._accept = _accept;
notification._acceptObservable = _acceptObservable;
notification.toString = toString;
return notification;
};
}());
var Enumerator = Rx.internals.Enumerator = function (next) {
this._next = next;
};
Enumerator.prototype.next = function () {
return this._next();
};
Enumerator.prototype[$iterator$] = function () { return this; }
var Enumerable = Rx.internals.Enumerable = function (iterator) {
this._iterator = iterator;
};
Enumerable.prototype[$iterator$] = function () {
return this._iterator();
};
Enumerable.prototype.concat = function () {
var sources = this;
return new AnonymousObservable(function (o) {
var e = sources[$iterator$]();
var isDisposed, subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
if (isDisposed) { return; }
try {
var currentItem = e.next();
} catch (ex) {
return o.onError(ex);
}
if (currentItem.done) {
return o.onCompleted();
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(
function(x) { o.onNext(x); },
function(err) { o.onError(err); },
self)
);
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
Enumerable.prototype.catchError = function () {
var sources = this;
return new AnonymousObservable(function (o) {
var e = sources[$iterator$]();
var isDisposed, subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursiveWithState(null, function (lastException, self) {
if (isDisposed) { return; }
try {
var currentItem = e.next();
} catch (ex) {
return observer.onError(ex);
}
if (currentItem.done) {
if (lastException !== null) {
o.onError(lastException);
} else {
o.onCompleted();
}
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(currentValue.subscribe(
function(x) { o.onNext(x); },
self,
function() { o.onCompleted(); }));
});
return new CompositeDisposable(subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
Enumerable.prototype.catchErrorWhen = function (notificationHandler) {
var sources = this;
return new AnonymousObservable(function (o) {
var exceptions = new Subject(),
notifier = new Subject(),
handled = notificationHandler(exceptions),
notificationDisposable = handled.subscribe(notifier);
var e = sources[$iterator$]();
var isDisposed,
lastException,
subscription = new SerialDisposable();
var cancelable = immediateScheduler.scheduleRecursive(function (self) {
if (isDisposed) { return; }
try {
var currentItem = e.next();
} catch (ex) {
return o.onError(ex);
}
if (currentItem.done) {
if (lastException) {
o.onError(lastException);
} else {
o.onCompleted();
}
return;
}
// Check if promise
var currentValue = currentItem.value;
isPromise(currentValue) && (currentValue = observableFromPromise(currentValue));
var outer = new SingleAssignmentDisposable();
var inner = new SingleAssignmentDisposable();
subscription.setDisposable(new CompositeDisposable(inner, outer));
outer.setDisposable(currentValue.subscribe(
function(x) { o.onNext(x); },
function (exn) {
inner.setDisposable(notifier.subscribe(self, function(ex) {
o.onError(ex);
}, function() {
o.onCompleted();
}));
exceptions.onNext(exn);
},
function() { o.onCompleted(); }));
});
return new CompositeDisposable(notificationDisposable, subscription, cancelable, disposableCreate(function () {
isDisposed = true;
}));
});
};
var enumerableRepeat = Enumerable.repeat = function (value, repeatCount) {
if (repeatCount == null) { repeatCount = -1; }
return new Enumerable(function () {
var left = repeatCount;
return new Enumerator(function () {
if (left === 0) { return doneEnumerator; }
if (left > 0) { left--; }
return { done: false, value: value };
});
});
};
var enumerableOf = Enumerable.of = function (source, selector, thisArg) {
if (selector) {
var selectorFn = bindCallback(selector, thisArg, 3);
}
return new Enumerable(function () {
var index = -1;
return new Enumerator(
function () {
return ++index < source.length ?
{ done: false, value: !selector ? source[index] : selectorFn(source[index], index, source) } :
doneEnumerator;
});
});
};
/**
* Supports push-style iteration over an observable sequence.
*/
var Observer = Rx.Observer = function () { };
/**
* Creates a notification callback from an observer.
* @returns The action that forwards its input notification to the underlying observer.
*/
Observer.prototype.toNotifier = function () {
var observer = this;
return function (n) { return n.accept(observer); };
};
/**
* Hides the identity of an observer.
* @returns An observer that hides the identity of the specified observer.
*/
Observer.prototype.asObserver = function () {
return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this));
};
/**
* Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods.
* If a violation is detected, an Error is thrown from the offending observer method call.
* @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer.
*/
Observer.prototype.checked = function () { return new CheckedObserver(this); };
/**
* Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions.
* @param {Function} [onNext] Observer's OnNext action implementation.
* @param {Function} [onError] Observer's OnError action implementation.
* @param {Function} [onCompleted] Observer's OnCompleted action implementation.
* @returns {Observer} The observer object implemented using the given actions.
*/
var observerCreate = Observer.create = function (onNext, onError, onCompleted) {
onNext || (onNext = noop);
onError || (onError = defaultError);
onCompleted || (onCompleted = noop);
return new AnonymousObserver(onNext, onError, onCompleted);
};
/**
* Creates an observer from a notification callback.
*
* @static
* @memberOf Observer
* @param {Function} handler Action that handles a notification.
* @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives.
*/
Observer.fromNotifier = function (handler, thisArg) {
return new AnonymousObserver(function (x) {
return handler.call(thisArg, notificationCreateOnNext(x));
}, function (e) {
return handler.call(thisArg, notificationCreateOnError(e));
}, function () {
return handler.call(thisArg, notificationCreateOnCompleted());
});
};
/**
* Schedules the invocation of observer methods on the given scheduler.
* @param {Scheduler} scheduler Scheduler to schedule observer messages on.
* @returns {Observer} Observer whose messages are scheduled on the given scheduler.
*/
Observer.prototype.notifyOn = function (scheduler) {
return new ObserveOnObserver(scheduler, this);
};
Observer.prototype.makeSafe = function(disposable) {
return new AnonymousSafeObserver(this._onNext, this._onError, this._onCompleted, disposable);
};
/**
* Abstract base class for implementations of the Observer class.
* This base class enforces the grammar of observers where OnError and OnCompleted are terminal messages.
*/
var AbstractObserver = Rx.internals.AbstractObserver = (function (__super__) {
inherits(AbstractObserver, __super__);
/**
* Creates a new observer in a non-stopped state.
*/
function AbstractObserver() {
this.isStopped = false;
__super__.call(this);
}
/**
* Notifies the observer of a new element in the sequence.
* @param {Any} value Next element in the sequence.
*/
AbstractObserver.prototype.onNext = function (value) {
if (!this.isStopped) { this.next(value); }
};
/**
* Notifies the observer that an exception has occurred.
* @param {Any} error The error that has occurred.
*/
AbstractObserver.prototype.onError = function (error) {
if (!this.isStopped) {
this.isStopped = true;
this.error(error);
}
};
/**
* Notifies the observer of the end of the sequence.
*/
AbstractObserver.prototype.onCompleted = function () {
if (!this.isStopped) {
this.isStopped = true;
this.completed();
}
};
/**
* Disposes the observer, causing it to transition to the stopped state.
*/
AbstractObserver.prototype.dispose = function () {
this.isStopped = true;
};
AbstractObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.error(e);
return true;
}
return false;
};
return AbstractObserver;
}(Observer));
/**
* Class to create an Observer instance from delegate-based implementations of the on* methods.
*/
var AnonymousObserver = Rx.AnonymousObserver = (function (__super__) {
inherits(AnonymousObserver, __super__);
/**
* Creates an observer from the specified OnNext, OnError, and OnCompleted actions.
* @param {Any} onNext Observer's OnNext action implementation.
* @param {Any} onError Observer's OnError action implementation.
* @param {Any} onCompleted Observer's OnCompleted action implementation.
*/
function AnonymousObserver(onNext, onError, onCompleted) {
__super__.call(this);
this._onNext = onNext;
this._onError = onError;
this._onCompleted = onCompleted;
}
/**
* Calls the onNext action.
* @param {Any} value Next element in the sequence.
*/
AnonymousObserver.prototype.next = function (value) {
this._onNext(value);
};
/**
* Calls the onError action.
* @param {Any} error The error that has occurred.
*/
AnonymousObserver.prototype.error = function (error) {
this._onError(error);
};
/**
* Calls the onCompleted action.
*/
AnonymousObserver.prototype.completed = function () {
this._onCompleted();
};
return AnonymousObserver;
}(AbstractObserver));
var CheckedObserver = (function (_super) {
inherits(CheckedObserver, _super);
function CheckedObserver(observer) {
_super.call(this);
this._observer = observer;
this._state = 0; // 0 - idle, 1 - busy, 2 - done
}
var CheckedObserverPrototype = CheckedObserver.prototype;
CheckedObserverPrototype.onNext = function (value) {
this.checkAccess();
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 (e) {
var self = this;
this.queue.push(function () { self.observer.onError(e); });
};
ScheduledObserver.prototype.completed = function () {
var self = this;
this.queue.push(function () { self.observer.onCompleted(); });
};
ScheduledObserver.prototype.ensureActive = function () {
var isOwner = false, parent = this;
if (!this.hasFaulted && this.queue.length > 0) {
isOwner = !this.isAcquired;
this.isAcquired = true;
}
if (isOwner) {
this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) {
var work;
if (parent.queue.length > 0) {
work = parent.queue.shift();
} else {
parent.isAcquired = false;
return;
}
try {
work();
} catch (ex) {
parent.queue = [];
parent.hasFaulted = true;
throw ex;
}
self();
}));
}
};
ScheduledObserver.prototype.dispose = function () {
__super__.prototype.dispose.call(this);
this.disposable.dispose();
};
return ScheduledObserver;
}(AbstractObserver));
var ObserveOnObserver = (function (__super__) {
inherits(ObserveOnObserver, __super__);
function ObserveOnObserver(scheduler, observer, cancel) {
__super__.call(this, scheduler, observer);
this._cancel = cancel;
}
ObserveOnObserver.prototype.next = function (value) {
__super__.prototype.next.call(this, value);
this.ensureActive();
};
ObserveOnObserver.prototype.error = function (e) {
__super__.prototype.error.call(this, e);
this.ensureActive();
};
ObserveOnObserver.prototype.completed = function () {
__super__.prototype.completed.call(this);
this.ensureActive();
};
ObserveOnObserver.prototype.dispose = function () {
__super__.prototype.dispose.call(this);
this._cancel && this._cancel.dispose();
this._cancel = null;
};
return ObserveOnObserver;
})(ScheduledObserver);
var observableProto;
/**
* Represents a push-style collection.
*/
var Observable = Rx.Observable = (function () {
function Observable(subscribe) {
if (Rx.config.longStackSupport && hasStacks) {
try {
throw new Error();
} catch (e) {
this.stack = e.stack.substring(e.stack.indexOf("\n") + 1);
}
var self = this;
this._subscribe = function (observer) {
var oldOnError = observer.onError.bind(observer);
observer.onError = function (err) {
makeStackTraceLong(err, self);
oldOnError(err);
};
return subscribe.call(self, observer);
};
} else {
this._subscribe = subscribe;
}
}
observableProto = Observable.prototype;
/**
* Subscribes an observer to the observable sequence.
* @param {Mixed} [observerOrOnNext] The object that is to receive notifications or an action to invoke for each element in the observable sequence.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence.
* @returns {Diposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribe = observableProto.forEach = function (observerOrOnNext, onError, onCompleted) {
return this._subscribe(typeof observerOrOnNext === 'object' ?
observerOrOnNext :
observerCreate(observerOrOnNext, onError, onCompleted));
};
/**
* Subscribes to the next value in the sequence with an optional "this" argument.
* @param {Function} onNext The function to invoke on each element in the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnNext = function (onNext, thisArg) {
return this._subscribe(observerCreate(typeof thisArg !== 'undefined' ? function(x) { onNext.call(thisArg, x); } : onNext));
};
/**
* Subscribes to an exceptional condition in the sequence with an optional "this" argument.
* @param {Function} onError The function to invoke upon exceptional termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnError = function (onError, thisArg) {
return this._subscribe(observerCreate(null, typeof thisArg !== 'undefined' ? function(e) { onError.call(thisArg, e); } : onError));
};
/**
* Subscribes to the next value in the sequence with an optional "this" argument.
* @param {Function} onCompleted The function to invoke upon graceful termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Disposable} A disposable handling the subscriptions and unsubscriptions.
*/
observableProto.subscribeOnCompleted = function (onCompleted, thisArg) {
return this._subscribe(observerCreate(null, null, typeof thisArg !== 'undefined' ? function() { onCompleted.call(thisArg); } : onCompleted));
};
return Observable;
})();
var ObservableBase = Rx.ObservableBase = (function (__super__) {
inherits(ObservableBase, __super__);
// 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 setDisposable(s, state) {
var ado = state[0], self = state[1];
try {
ado.setDisposable(fixSubscriber(self.subscribeCore(ado)));
} catch (e) {
if (!ado.fail(e)) { throw e; }
}
}
function subscribe(observer) {
var ado = new AutoDetachObserver(observer), state = [ado, this];
if (currentThreadScheduler.scheduleRequired()) {
currentThreadScheduler.scheduleWithState(state, setDisposable);
} else {
setDisposable(null, state);
}
return ado;
}
function ObservableBase() {
__super__.call(this, subscribe);
}
ObservableBase.prototype.subscribeCore = function(observer) {
throw new Error('Not implemeneted');
}
return ObservableBase;
}(Observable));
/**
* Wraps the source sequence in order to run its observer callbacks on the specified scheduler.
*
* This only invokes observer callbacks on a scheduler. In case the subscription and/or unsubscription actions have side-effects
* that require to be run on a scheduler, use subscribeOn.
*
* @param {Scheduler} scheduler Scheduler to notify observers on.
* @returns {Observable} The source sequence whose observations happen on the specified scheduler.
*/
observableProto.observeOn = function (scheduler) {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(new ObserveOnObserver(scheduler, observer));
}, source);
};
/**
* Wraps the source sequence in order to run its subscription and unsubscription logic on the specified scheduler. This operation is not commonly used;
* see the remarks section for more information on the distinction between subscribeOn and observeOn.
* This only performs the side-effects of subscription and unsubscription on the specified scheduler. In order to invoke observer
* callbacks on a scheduler, use observeOn.
* @param {Scheduler} scheduler Scheduler to perform subscription and unsubscription actions on.
* @returns {Observable} The source sequence whose subscriptions and unsubscriptions happen on the specified scheduler.
*/
observableProto.subscribeOn = function (scheduler) {
var source = this;
return new AnonymousObservable(function (observer) {
var m = new SingleAssignmentDisposable(), d = new SerialDisposable();
d.setDisposable(m);
m.setDisposable(scheduler.schedule(function () {
d.setDisposable(new ScheduledDisposable(scheduler, source.subscribe(observer)));
}));
return d;
}, source);
};
/**
* Converts a Promise to an Observable sequence
* @param {Promise} An ES6 Compliant promise.
* @returns {Observable} An Observable sequence which wraps the existing promise success and failure.
*/
var observableFromPromise = Observable.fromPromise = function (promise) {
return observableDefer(function () {
var subject = new Rx.AsyncSubject();
promise.then(
function (value) {
subject.onNext(value);
subject.onCompleted();
},
subject.onError.bind(subject));
return subject;
});
};
/*
* Converts an existing observable sequence to an ES6 Compatible Promise
* @example
* var promise = Rx.Observable.return(42).toPromise(RSVP.Promise);
*
* // With config
* Rx.config.Promise = RSVP.Promise;
* var promise = Rx.Observable.return(42).toPromise();
* @param {Function} [promiseCtor] The constructor of the promise. If not provided, it looks for it in Rx.config.Promise.
* @returns {Promise} An ES6 compatible promise with the last value from the observable sequence.
*/
observableProto.toPromise = function (promiseCtor) {
promiseCtor || (promiseCtor = Rx.config.Promise);
if (!promiseCtor) { throw new TypeError('Promise type not provided nor in Rx.config.Promise'); }
var source = this;
return new promiseCtor(function (resolve, reject) {
// No cancellation can be done
var value, hasValue = false;
source.subscribe(function (v) {
value = v;
hasValue = true;
}, reject, function () {
hasValue && resolve(value);
});
});
};
/**
* Creates an array from an observable sequence.
* @returns {Observable} An observable sequence containing a single element with a list containing all the elements of the source sequence.
*/
observableProto.toArray = function () {
var source = this;
return new AnonymousObservable(function(observer) {
var arr = [];
return source.subscribe(
function (x) { arr.push(x); },
function (e) { observer.onError(e); },
function () {
observer.onNext(arr);
observer.onCompleted();
});
}, source);
};
/**
* Creates an observable sequence from a specified subscribe method implementation.
* @example
* var res = Rx.Observable.create(function (observer) { return function () { } );
* var res = Rx.Observable.create(function (observer) { return Rx.Disposable.empty; } );
* var res = Rx.Observable.create(function (observer) { } );
* @param {Function} subscribe Implementation of the resulting observable sequence's subscribe method, returning a function that will be wrapped in a Disposable.
* @returns {Observable} The observable sequence with the specified implementation for the Subscribe method.
*/
Observable.create = Observable.createWithDisposable = function (subscribe, parent) {
return new AnonymousObservable(subscribe, parent);
};
/**
* Returns an observable sequence that invokes the specified factory function whenever a new observer subscribes.
*
* @example
* var res = Rx.Observable.defer(function () { return Rx.Observable.fromArray([1,2,3]); });
* @param {Function} observableFactory Observable factory function to invoke for each observer that subscribes to the resulting sequence or Promise.
* @returns {Observable} An observable sequence whose observers trigger an invocation of the given observable factory function.
*/
var observableDefer = Observable.defer = function (observableFactory) {
return new AnonymousObservable(function (observer) {
var result;
try {
result = observableFactory();
} catch (e) {
return observableThrow(e).subscribe(observer);
}
isPromise(result) && (result = observableFromPromise(result));
return result.subscribe(observer);
});
};
/**
* Returns an empty observable sequence, using the specified scheduler to send out the single OnCompleted message.
*
* @example
* var res = Rx.Observable.empty();
* var res = Rx.Observable.empty(Rx.Scheduler.timeout);
* @param {Scheduler} [scheduler] Scheduler to send the termination call on.
* @returns {Observable} An observable sequence with no elements.
*/
var observableEmpty = Observable.empty = function (scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onCompleted();
});
});
};
var maxSafeInteger = Math.pow(2, 53) - 1;
function StringIterable(str) {
this._s = s;
}
StringIterable.prototype[$iterator$] = function () {
return new StringIterator(this._s);
};
function StringIterator(str) {
this._s = s;
this._l = s.length;
this._i = 0;
}
StringIterator.prototype[$iterator$] = function () {
return this;
};
StringIterator.prototype.next = function () {
if (this._i < this._l) {
var val = this._s.charAt(this._i++);
return { done: false, value: val };
} else {
return doneEnumerator;
}
};
function ArrayIterable(a) {
this._a = a;
}
ArrayIterable.prototype[$iterator$] = function () {
return new ArrayIterator(this._a);
};
function ArrayIterator(a) {
this._a = a;
this._l = toLength(a);
this._i = 0;
}
ArrayIterator.prototype[$iterator$] = function () {
return this;
};
ArrayIterator.prototype.next = function () {
if (this._i < this._l) {
var val = this._a[this._i++];
return { done: false, value: val };
} else {
return doneEnumerator;
}
};
function numberIsFinite(value) {
return typeof value === 'number' && root.isFinite(value);
}
function isNan(n) {
return n !== n;
}
function getIterable(o) {
var i = o[$iterator$], it;
if (!i && typeof o === 'string') {
it = new StringIterable(o);
return it[$iterator$]();
}
if (!i && o.length !== undefined) {
it = new ArrayIterable(o);
return it[$iterator$]();
}
if (!i) { throw new TypeError('Object is not iterable'); }
return o[$iterator$]();
}
function sign(value) {
var number = +value;
if (number === 0) { return number; }
if (isNaN(number)) { return number; }
return number < 0 ? -1 : 1;
}
function toLength(o) {
var len = +o.length;
if (isNaN(len)) { return 0; }
if (len === 0 || !numberIsFinite(len)) { return len; }
len = sign(len) * Math.floor(Math.abs(len));
if (len <= 0) { return 0; }
if (len > maxSafeInteger) { return maxSafeInteger; }
return len;
}
/**
* This method creates a new Observable sequence from an array-like or iterable object.
* @param {Any} arrayLike An array-like or iterable object to convert to an Observable sequence.
* @param {Function} [mapFn] Map function to call on every element of the array.
* @param {Any} [thisArg] The context to use calling the mapFn if provided.
* @param {Scheduler} [scheduler] Optional scheduler to use for scheduling. If not provided, defaults to Scheduler.currentThread.
*/
var observableFrom = Observable.from = function (iterable, mapFn, thisArg, scheduler) {
if (iterable == null) {
throw new Error('iterable cannot be null.')
}
if (mapFn && !isFunction(mapFn)) {
throw new Error('mapFn when provided must be a function');
}
if (mapFn) {
var mapper = bindCallback(mapFn, thisArg, 2);
}
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
var list = Object(iterable), it = getIterable(list);
return new AnonymousObservable(function (observer) {
return scheduler.scheduleRecursiveWithState(0, function (i, self) {
try {
var next = it.next();
} catch (e) {
observer.onError(e);
return;
}
if (next.done) {
observer.onCompleted();
return;
}
var result = next.value;
if (mapper) {
try {
result = mapper(result, i);
} catch (e) {
observer.onError(e);
return;
}
}
observer.onNext(result);
self(i + 1);
});
});
};
var FromArrayObservable = (function(__super__) {
inherits(FromArrayObservable, __super__);
function FromArrayObservable(args, scheduler) {
this.args = args;
this.scheduler = scheduler || currentThreadScheduler;
__super__.call(this);
}
FromArrayObservable.prototype.subscribeCore = function (observer) {
var sink = new FromArraySink(observer, this);
return sink.run();
};
return FromArrayObservable;
}(ObservableBase));
var FromArraySink = (function () {
function FromArraySink(observer, parent) {
this.observer = observer;
this.parent = parent;
}
function loopRecursive(state, recurse) {
if (state.i < state.len) {
state.observer.onNext(state.args[state.i++]);
recurse(state);
} else {
state.observer.onCompleted();
}
}
FromArraySink.prototype.run = function () {
return this.parent.scheduler.scheduleRecursiveWithState(
{i: 0, args: this.parent.args, len: this.parent.args.length, observer: this.observer },
loopRecursive);
};
return FromArraySink;
}());
/**
* Converts an array to an observable sequence, using an optional scheduler to enumerate the array.
* @deprecated use Observable.from or Observable.of
* @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
* @returns {Observable} The observable sequence whose elements are pulled from the given enumerable sequence.
*/
var observableFromArray = Observable.fromArray = function (array, scheduler) {
return new FromArrayObservable(array, scheduler)
};
/**
* Generates an observable sequence by running a state-driven loop producing the sequence's elements, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; });
* var res = Rx.Observable.generate(0, function (x) { return x < 10; }, function (x) { return x + 1; }, function (x) { return x; }, Rx.Scheduler.timeout);
* @param {Mixed} initialState Initial state.
* @param {Function} condition Condition to terminate generation (upon returning false).
* @param {Function} iterate Iteration step function.
* @param {Function} resultSelector Selector function for results produced in the sequence.
* @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not provided, defaults to Scheduler.currentThread.
* @returns {Observable} The generated sequence.
*/
Observable.generate = function (initialState, condition, iterate, resultSelector, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (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();
}
});
});
};
function observableOf (scheduler, array) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
var count = 0, len = array.length;
return scheduler.scheduleRecursive(function (self) {
if (count < len) {
observer.onNext(array[count++]);
self();
} else {
observer.onCompleted();
}
});
});
}
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
Observable.of = function () {
for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
return observableOf(null, args);
};
/**
* This method creates a new Observable instance with a variable number of arguments, regardless of number or type of the arguments.
* @param {Scheduler} scheduler A scheduler to use for scheduling the arguments.
* @returns {Observable} The observable sequence whose elements are pulled from the given arguments.
*/
Observable.ofWithScheduler = function (scheduler) {
for(var args = [], i = 1, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
return observableOf(scheduler, args);
};
/**
* Returns a non-terminating observable sequence, which can be used to denote an infinite duration (e.g. when using reactive joins).
* @returns {Observable} An observable sequence whose observers will never get called.
*/
var observableNever = Observable.never = function () {
return new AnonymousObservable(function () {
return disposableEmpty;
});
};
/**
* Convert an object into an observable sequence of [key, value] pairs.
* @param {Object} obj The object to inspect.
* @param {Scheduler} [scheduler] Scheduler to run the enumeration of the input sequence on.
* @returns {Observable} An observable sequence of [key, value] pairs from the object.
*/
Observable.pairs = function (obj, scheduler) {
scheduler || (scheduler = Rx.Scheduler.currentThread);
return new AnonymousObservable(function (observer) {
var keys = Object.keys(obj), len = keys.length;
return scheduler.scheduleRecursiveWithState(0, function (idx, self) {
if (idx < len) {
var key = keys[idx];
observer.onNext([key, obj[key]]);
self(idx + 1);
} else {
observer.onCompleted();
}
});
});
};
/**
* Generates an observable sequence of integral numbers within a specified range, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.range(0, 10);
* var res = Rx.Observable.range(0, 10, Rx.Scheduler.timeout);
* @param {Number} start The value of the first integer in the sequence.
* @param {Number} count The number of sequential integers to generate.
* @param {Scheduler} [scheduler] Scheduler to run the generator loop on. If not specified, defaults to Scheduler.currentThread.
* @returns {Observable} An observable sequence that contains a range of sequential integral numbers.
*/
Observable.range = function (start, count, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.scheduleRecursiveWithState(0, function (i, self) {
if (i < count) {
observer.onNext(start + i);
self(i + 1);
} else {
observer.onCompleted();
}
});
});
};
/**
* Generates an observable sequence that repeats the given element the specified number of times, using the specified scheduler to send out observer messages.
*
* @example
* var res = Rx.Observable.repeat(42);
* var res = Rx.Observable.repeat(42, 4);
* 3 - res = Rx.Observable.repeat(42, 4, Rx.Scheduler.timeout);
* 4 - res = Rx.Observable.repeat(42, null, Rx.Scheduler.timeout);
* @param {Mixed} value Element to repeat.
* @param {Number} repeatCount [Optiona] Number of times to repeat the element. If not specified, repeats indefinitely.
* @param {Scheduler} scheduler Scheduler to run the producer loop on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence that repeats the given element the specified number of times.
*/
Observable.repeat = function (value, repeatCount, scheduler) {
isScheduler(scheduler) || (scheduler = currentThreadScheduler);
return observableReturn(value, scheduler).repeat(repeatCount == null ? -1 : repeatCount);
};
/**
* Returns an observable sequence that contains a single element, using the specified scheduler to send out observer messages.
* There is an alias called 'just', and 'returnValue' for browsers <IE9.
* @param {Mixed} value Single element in the resulting observable sequence.
* @param {Scheduler} scheduler Scheduler to send the single element on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} An observable sequence containing the single specified element.
*/
var observableReturn = Observable['return'] = Observable.just = function (value, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onNext(value);
observer.onCompleted();
});
});
};
/** @deprecated use return or just */
Observable.returnValue = function () {
//deprecate('returnValue', 'return or just');
return observableReturn.apply(null, arguments);
};
/**
* Returns an observable sequence that terminates with an exception, using the specified scheduler to send out the single onError message.
* There is an alias to this method called 'throwError' for browsers <IE9.
* @param {Mixed} error An object used for the sequence's termination.
* @param {Scheduler} scheduler Scheduler to send the exceptional termination call on. If not specified, defaults to Scheduler.immediate.
* @returns {Observable} The observable sequence that terminates exceptionally with the specified exception object.
*/
var observableThrow = Observable['throw'] = Observable.throwError = function (error, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
return new AnonymousObservable(function (observer) {
return scheduler.schedule(function () {
observer.onError(error);
});
});
};
/** @deprecated use #some instead */
Observable.throwException = function () {
//deprecate('throwException', 'throwError');
return Observable.throwError.apply(null, arguments);
};
/**
* Constructs an observable sequence that depends on a resource object, whose lifetime is tied to the resulting observable sequence's lifetime.
* @param {Function} resourceFactory Factory function to obtain a resource object.
* @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource.
* @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object.
*/
Observable.using = function (resourceFactory, observableFactory) {
return new AnonymousObservable(function (observer) {
var disposable = disposableEmpty, resource, source;
try {
resource = resourceFactory();
resource && (disposable = resource);
source = observableFactory(resource);
} catch (exception) {
return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable);
}
return new CompositeDisposable(source.subscribe(observer), disposable);
});
};
/**
* Propagates the observable sequence or Promise that reacts first.
* @param {Observable} rightSource Second observable sequence or Promise.
* @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first.
*/
observableProto.amb = function (rightSource) {
var leftSource = this;
return new AnonymousObservable(function (observer) {
var choice,
leftChoice = 'L', rightChoice = 'R',
leftSubscription = new SingleAssignmentDisposable(),
rightSubscription = new SingleAssignmentDisposable();
isPromise(rightSource) && (rightSource = observableFromPromise(rightSource));
function choiceL() {
if (!choice) {
choice = leftChoice;
rightSubscription.dispose();
}
}
function choiceR() {
if (!choice) {
choice = rightChoice;
leftSubscription.dispose();
}
}
leftSubscription.setDisposable(leftSource.subscribe(function (left) {
choiceL();
if (choice === leftChoice) {
observer.onNext(left);
}
}, function (err) {
choiceL();
if (choice === leftChoice) {
observer.onError(err);
}
}, function () {
choiceL();
if (choice === leftChoice) {
observer.onCompleted();
}
}));
rightSubscription.setDisposable(rightSource.subscribe(function (right) {
choiceR();
if (choice === rightChoice) {
observer.onNext(right);
}
}, function (err) {
choiceR();
if (choice === rightChoice) {
observer.onError(err);
}
}, function () {
choiceR();
if (choice === rightChoice) {
observer.onCompleted();
}
}));
return new CompositeDisposable(leftSubscription, rightSubscription);
});
};
/**
* Propagates the observable sequence or Promise that reacts first.
*
* @example
* var = Rx.Observable.amb(xs, ys, zs);
* @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first.
*/
Observable.amb = function () {
var acc = observableNever(), items = [];
if (Array.isArray(arguments[0])) {
items = arguments[0];
} else {
for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); }
}
function func(previous, current) {
return previous.amb(current);
}
for (var i = 0, len = items.length; i < len; i++) {
acc = func(acc, items[i]);
}
return acc;
};
function observableCatchHandler(source, handler) {
return new AnonymousObservable(function (observer) {
var d1 = new SingleAssignmentDisposable(), subscription = new SerialDisposable();
subscription.setDisposable(d1);
d1.setDisposable(source.subscribe(observer.onNext.bind(observer), function (exception) {
var d, result;
try {
result = handler(exception);
} catch (ex) {
observer.onError(ex);
return;
}
isPromise(result) && (result = observableFromPromise(result));
d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(result.subscribe(observer));
}, observer.onCompleted.bind(observer)));
return subscription;
}, source);
}
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
* @example
* 1 - xs.catchException(ys)
* 2 - xs.catchException(function (ex) { return ys(ex); })
* @param {Mixed} handlerOrSecond Exception handler function that returns an observable sequence given the error that occurred in the first sequence, or a second observable sequence used to produce results when an error occurred in the first sequence.
* @returns {Observable} An observable sequence containing the first sequence's elements, followed by the elements of the handler sequence in case an exception occurred.
*/
observableProto['catch'] = observableProto.catchError = function (handlerOrSecond) {
return typeof handlerOrSecond === 'function' ?
observableCatchHandler(this, handlerOrSecond) :
observableCatch([this, handlerOrSecond]);
};
/**
* @deprecated use #catch or #catchError instead.
*/
observableProto.catchException = function (handlerOrSecond) {
//deprecate('catchException', 'catch or catchError');
return this.catchError(handlerOrSecond);
};
/**
* Continues an observable sequence that is terminated by an exception with the next observable sequence.
* @param {Array | Arguments} args Arguments or an array to use as the next sequence if an error occurs.
* @returns {Observable} An observable sequence containing elements from consecutive source sequences until a source sequence terminates successfully.
*/
var observableCatch = Observable.catchError = Observable['catch'] = Observable.catchException = function () {
var items = [];
if (Array.isArray(arguments[0])) {
items = arguments[0];
} else {
for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); }
}
return enumerableOf(items).catchError();
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
* This can be in the form of an argument list of observables or an array.
*
* @example
* 1 - obs = observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.combineLatest = function () {
for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
if (Array.isArray(args[0])) {
args[0].unshift(this);
} else {
args.unshift(this);
}
return combineLatest.apply(this, args);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever any of the observable sequences or Promises produces an element.
*
* @example
* 1 - obs = Rx.Observable.combineLatest(obs1, obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = Rx.Observable.combineLatest([obs1, obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
var combineLatest = Observable.combineLatest = function () {
for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
var resultSelector = args.pop();
if (Array.isArray(args[0])) {
args = args[0];
}
return new AnonymousObservable(function (observer) {
var falseFactory = function () { return false; },
n = args.length,
hasValue = arrayInitialize(n, falseFactory),
hasValueAll = false,
isDone = arrayInitialize(n, falseFactory),
values = new Array(n);
function next(i) {
var res;
hasValue[i] = true;
if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
try {
res = resultSelector.apply(null, values);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
}
}
function done (i) {
isDone[i] = true;
if (isDone.every(identity)) {
observer.onCompleted();
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var source = args[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
values[i] = x;
next(i);
},
function(e) { observer.onError(e); },
function () { done(i); }
));
subscriptions[i] = sad;
}(idx));
}
return new CompositeDisposable(subscriptions);
}, this);
};
/**
* Concatenates all the observable sequences. This takes in either an array or variable arguments to concatenate.
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
observableProto.concat = function () {
for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
args.unshift(this);
return observableConcat.apply(null, args);
};
/**
* Concatenates all the observable sequences.
* @param {Array | Arguments} args Arguments or an array to concat to the observable sequence.
* @returns {Observable} An observable sequence that contains the elements of each given sequence, in sequential order.
*/
var observableConcat = Observable.concat = function () {
var items = [];
if (Array.isArray(arguments[0])) {
items = arguments[0];
} else {
for(var i = 0, len = arguments.length; i < len; i++) { items.push(arguments[i]); }
}
return enumerableOf(items).concat();
};
/**
* Concatenates an observable sequence of observable sequences.
* @returns {Observable} An observable sequence that contains the elements of each observed inner sequence, in sequential order.
*/
observableProto.concatAll = observableProto.concatObservable = function () {
return this.merge(1);
};
/**
* Merges an observable sequence of observable sequences into an observable sequence, limiting the number of concurrent subscriptions to inner sequences.
* Or merges two observable sequences into a single observable sequence.
*
* @example
* 1 - merged = sources.merge(1);
* 2 - merged = source.merge(otherSource);
* @param {Mixed} [maxConcurrentOrOther] Maximum number of inner observable sequences being subscribed to concurrently or the second observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.merge = function (maxConcurrentOrOther) {
if (typeof maxConcurrentOrOther !== 'number') { return observableMerge(this, maxConcurrentOrOther); }
var sources = this;
return new AnonymousObservable(function (o) {
var activeCount = 0, group = new CompositeDisposable(), isStopped = false, q = [];
function subscribe(xs) {
var subscription = new SingleAssignmentDisposable();
group.add(subscription);
// Check for promises support
isPromise(xs) && (xs = observableFromPromise(xs));
subscription.setDisposable(xs.subscribe(function (x) { o.onNext(x); }, function (e) { o.onError(e); }, function () {
group.remove(subscription);
if (q.length > 0) {
subscribe(q.shift());
} else {
activeCount--;
isStopped && activeCount === 0 && o.onCompleted();
}
}));
}
group.add(sources.subscribe(function (innerSource) {
if (activeCount < maxConcurrentOrOther) {
activeCount++;
subscribe(innerSource);
} else {
q.push(innerSource);
}
}, function (e) { o.onError(e); }, function () {
isStopped = true;
activeCount === 0 && o.onCompleted();
}));
return group;
}, sources);
};
/**
* Merges all the observable sequences into a single observable sequence.
* The scheduler is optional and if not specified, the immediate scheduler is used.
* @returns {Observable} The observable sequence that merges the elements of the observable sequences.
*/
var observableMerge = Observable.merge = function () {
var scheduler, sources = [], i, len = arguments.length;
if (!arguments[0]) {
scheduler = immediateScheduler;
for(i = 1; i < len; i++) { sources.push(arguments[i]); }
} else if (isScheduler(arguments[0])) {
scheduler = arguments[0];
for(i = 1; i < len; i++) { sources.push(arguments[i]); }
} else {
scheduler = immediateScheduler;
for(i = 0; i < len; i++) { sources.push(arguments[i]); }
}
if (Array.isArray(sources[0])) {
sources = sources[0];
}
return observableOf(scheduler, sources).mergeAll();
};
/**
* Merges an observable sequence of observable sequences into an observable sequence.
* @returns {Observable} The observable sequence that merges the elements of the inner sequences.
*/
observableProto.mergeAll = function () {
var sources = this;
return new AnonymousObservable(function (o) {
var group = new CompositeDisposable(),
isStopped = false,
m = new SingleAssignmentDisposable();
group.add(m);
m.setDisposable(sources.subscribe(function (innerSource) {
var innerSubscription = new SingleAssignmentDisposable();
group.add(innerSubscription);
// Check for promises support
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
innerSubscription.setDisposable(innerSource.subscribe(function (x) { o.onNext(x); }, function (e) { o.onError(e); }, function () {
group.remove(innerSubscription);
isStopped && group.length === 1 && o.onCompleted();
}));
}, function (e) { o.onError(e); }, function () {
isStopped = true;
group.length === 1 && o.onCompleted();
}));
return group;
}, sources);
};
/**
* @deprecated use #mergeAll instead.
*/
observableProto.mergeObservable = function () {
//deprecate('mergeObservable', 'mergeAll');
return this.mergeAll.apply(this, arguments);
};
/**
* Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
* @param {Observable} second Second observable sequence used to produce results after the first sequence terminates.
* @returns {Observable} An observable sequence that concatenates the first and second sequence, even if the first sequence terminates exceptionally.
*/
observableProto.onErrorResumeNext = function (second) {
if (!second) { throw new Error('Second observable is required'); }
return onErrorResumeNext([this, second]);
};
/**
* Continues an observable sequence that is terminated normally or by an exception with the next observable sequence.
*
* @example
* 1 - res = Rx.Observable.onErrorResumeNext(xs, ys, zs);
* 1 - res = Rx.Observable.onErrorResumeNext([xs, ys, zs]);
* @returns {Observable} An observable sequence that concatenates the source sequences, even if a sequence terminates exceptionally.
*/
var onErrorResumeNext = Observable.onErrorResumeNext = function () {
var sources = [];
if (Array.isArray(arguments[0])) {
sources = arguments[0];
} else {
for(var i = 0, len = arguments.length; i < len; i++) { sources.push(arguments[i]); }
}
return new AnonymousObservable(function (observer) {
var pos = 0, subscription = new SerialDisposable(),
cancelable = immediateScheduler.scheduleRecursive(function (self) {
var current, d;
if (pos < sources.length) {
current = sources[pos++];
isPromise(current) && (current = observableFromPromise(current));
d = new SingleAssignmentDisposable();
subscription.setDisposable(d);
d.setDisposable(current.subscribe(observer.onNext.bind(observer), self, self));
} else {
observer.onCompleted();
}
});
return new CompositeDisposable(subscription, cancelable);
});
};
/**
* Returns the values from the source observable sequence only after the other observable sequence produces a value.
* @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation.
*/
observableProto.skipUntil = function (other) {
var source = this;
return new AnonymousObservable(function (o) {
var isOpen = false;
var disposables = new CompositeDisposable(source.subscribe(function (left) {
isOpen && o.onNext(left);
}, function (e) { o.onError(e); }, function () {
isOpen && o.onCompleted();
}));
isPromise(other) && (other = observableFromPromise(other));
var rightSubscription = new SingleAssignmentDisposable();
disposables.add(rightSubscription);
rightSubscription.setDisposable(other.subscribe(function () {
isOpen = true;
rightSubscription.dispose();
}, function (e) { o.onError(e); }, function () {
rightSubscription.dispose();
}));
return disposables;
}, source);
};
/**
* Transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @returns {Observable} The observable sequence that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto['switch'] = observableProto.switchLatest = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var hasLatest = false,
innerSubscription = new SerialDisposable(),
isStopped = false,
latest = 0,
subscription = sources.subscribe(
function (innerSource) {
var d = new SingleAssignmentDisposable(), id = ++latest;
hasLatest = true;
innerSubscription.setDisposable(d);
// Check if Promise or Observable
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
d.setDisposable(innerSource.subscribe(
function (x) { latest === id && observer.onNext(x); },
function (e) { latest === id && observer.onError(e); },
function () {
if (latest === id) {
hasLatest = false;
isStopped && observer.onCompleted();
}
}));
},
function (e) { observer.onError(e); },
function () {
isStopped = true;
!hasLatest && observer.onCompleted();
});
return new CompositeDisposable(subscription, innerSubscription);
}, sources);
};
/**
* Returns the values from the source observable sequence until the other observable sequence produces a value.
* @param {Observable | Promise} other Observable sequence or Promise that terminates propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence up to the point the other sequence interrupted further propagation.
*/
observableProto.takeUntil = function (other) {
var source = this;
return new AnonymousObservable(function (o) {
isPromise(other) && (other = observableFromPromise(other));
return new CompositeDisposable(
source.subscribe(o),
other.subscribe(function () { o.onCompleted(); }, function (e) { o.onError(e); }, noop)
);
}, source);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function only when the (first) source observable sequence produces an element.
*
* @example
* 1 - obs = obs1.withLatestFrom(obs2, obs3, function (o1, o2, o3) { return o1 + o2 + o3; });
* 2 - obs = obs1.withLatestFrom([obs2, obs3], function (o1, o2, o3) { return o1 + o2 + o3; });
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
observableProto.withLatestFrom = function () {
for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
var resultSelector = args.pop(), source = this;
if (typeof source === 'undefined') {
throw new Error('Source observable not found for withLatestFrom().');
}
if (typeof resultSelector !== 'function') {
throw new Error('withLatestFrom() expects a resultSelector function.');
}
if (Array.isArray(args[0])) {
args = args[0];
}
return new AnonymousObservable(function (observer) {
var falseFactory = function () { return false; },
n = args.length,
hasValue = arrayInitialize(n, falseFactory),
hasValueAll = false,
values = new Array(n);
var subscriptions = new Array(n + 1);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var other = args[i], sad = new SingleAssignmentDisposable();
isPromise(other) && (other = observableFromPromise(other));
sad.setDisposable(other.subscribe(function (x) {
values[i] = x;
hasValue[i] = true;
hasValueAll = hasValue.every(identity);
}, observer.onError.bind(observer), function () {}));
subscriptions[i] = sad;
}(idx));
}
var sad = new SingleAssignmentDisposable();
sad.setDisposable(source.subscribe(function (x) {
var res;
var allValues = [x].concat(values);
if (!hasValueAll) return;
try {
res = resultSelector.apply(null, allValues);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
}, observer.onError.bind(observer), function () {
observer.onCompleted();
}));
subscriptions[n] = sad;
return new CompositeDisposable(subscriptions);
}, this);
};
function zipArray(second, resultSelector) {
var first = this;
return new AnonymousObservable(function (observer) {
var index = 0, len = second.length;
return first.subscribe(function (left) {
if (index < len) {
var right = second[index++], result;
try {
result = resultSelector(left, right);
} catch (e) {
return observer.onError(e);
}
observer.onNext(result);
} else {
observer.onCompleted();
}
}, function (e) { observer.onError(e); }, function () { observer.onCompleted(); });
}, first);
}
function falseFactory() { return false; }
function emptyArrayFactory() { return []; }
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences or an array have produced an element at a corresponding index.
* The last element in the arguments must be a function to invoke for each series of elements at corresponding indexes in the args.
*
* @example
* 1 - res = obs1.zip(obs2, fn);
* 1 - res = x1.zip([1,2,3], fn);
* @returns {Observable} An observable sequence containing the result of combining elements of the args using the specified result selector function.
*/
observableProto.zip = function () {
for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
if (Array.isArray(args[0])) { return zipArray.apply(this, args); }
var parent = this, resultSelector = args.pop();
args.unshift(parent);
return new AnonymousObservable(function (observer) {
var n = args.length,
queues = arrayInitialize(n, emptyArrayFactory),
isDone = arrayInitialize(n, falseFactory);
function next(i) {
var res, queuedValues;
if (queues.every(function (x) { return x.length > 0; })) {
try {
queuedValues = queues.map(function (x) { return x.shift(); });
res = resultSelector.apply(parent, queuedValues);
} catch (ex) {
observer.onError(ex);
return;
}
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(function (x) { return x; })) {
observer.onCompleted();
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
var source = args[i], sad = new SingleAssignmentDisposable();
isPromise(source) && (source = observableFromPromise(source));
sad.setDisposable(source.subscribe(function (x) {
queues[i].push(x);
next(i);
}, function (e) { observer.onError(e); }, function () {
done(i);
}));
subscriptions[i] = sad;
})(idx);
}
return new CompositeDisposable(subscriptions);
}, parent);
};
/**
* Merges the specified observable sequences into one observable sequence by using the selector function whenever all of the observable sequences have produced an element at a corresponding index.
* @param arguments Observable sources.
* @param {Function} resultSelector Function to invoke for each series of elements at corresponding indexes in the sources.
* @returns {Observable} An observable sequence containing the result of combining elements of the sources using the specified result selector function.
*/
Observable.zip = function () {
for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
var first = args.shift();
return first.zip.apply(first, args);
};
/**
* Merges the specified observable sequences into one observable sequence by emitting a list with the elements of the observable sequences at corresponding indexes.
* @param arguments Observable sources.
* @returns {Observable} An observable sequence containing lists of elements at corresponding indexes.
*/
Observable.zipArray = function () {
var sources = [];
if (Array.isArray(arguments[0])) {
sources = arguments[0];
} else {
for(var i = 0, len = arguments.length; i < len; i++) { sources.push(arguments[i]); }
}
return new AnonymousObservable(function (observer) {
var n = sources.length,
queues = arrayInitialize(n, function () { return []; }),
isDone = arrayInitialize(n, function () { return false; });
function next(i) {
if (queues.every(function (x) { return x.length > 0; })) {
var res = queues.map(function (x) { return x.shift(); });
observer.onNext(res);
} else if (isDone.filter(function (x, j) { return j !== i; }).every(identity)) {
observer.onCompleted();
return;
}
};
function done(i) {
isDone[i] = true;
if (isDone.every(identity)) {
observer.onCompleted();
return;
}
}
var subscriptions = new Array(n);
for (var idx = 0; idx < n; idx++) {
(function (i) {
subscriptions[i] = new SingleAssignmentDisposable();
subscriptions[i].setDisposable(sources[i].subscribe(function (x) {
queues[i].push(x);
next(i);
}, function (e) { observer.onError(e); }, function () {
done(i);
}));
})(idx);
}
return new CompositeDisposable(subscriptions);
});
};
/**
* Hides the identity of an observable sequence.
* @returns {Observable} An observable sequence that hides the identity of the source sequence.
*/
observableProto.asObservable = function () {
var source = this;
return new AnonymousObservable(function (o) { return source.subscribe(o); }, this);
};
/**
* Projects each element of an observable sequence into zero or more buffers which are produced based on element count information.
*
* @example
* var res = xs.bufferWithCount(10);
* var res = xs.bufferWithCount(10, 1);
* @param {Number} count Length of each buffer.
* @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count.
* @returns {Observable} An observable sequence of buffers.
*/
observableProto.bufferWithCount = function (count, skip) {
if (typeof skip !== 'number') {
skip = count;
}
return this.windowWithCount(count, skip).selectMany(function (x) {
return x.toArray();
}).where(function (x) {
return x.length > 0;
});
};
/**
* Dematerializes the explicit notification values of an observable sequence as implicit notifications.
* @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values.
*/
observableProto.dematerialize = function () {
var source = this;
return new AnonymousObservable(function (o) {
return source.subscribe(function (x) { return x.accept(o); }, function(e) { o.onError(e); }, function () { o.onCompleted(); });
}, this);
};
/**
* Returns an observable sequence that contains only distinct contiguous elements according to the keySelector and the comparer.
*
* var obs = observable.distinctUntilChanged();
* var obs = observable.distinctUntilChanged(function (x) { return x.id; });
* var obs = observable.distinctUntilChanged(function (x) { return x.id; }, function (x, y) { return x === y; });
*
* @param {Function} [keySelector] A function to compute the comparison key for each element. If not provided, it projects the value.
* @param {Function} [comparer] Equality comparer for computed key values. If not provided, defaults to an equality comparer function.
* @returns {Observable} An observable sequence only containing the distinct contiguous elements, based on a computed key value, from the source sequence.
*/
observableProto.distinctUntilChanged = function (keySelector, comparer) {
var source = this;
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (o) {
var hasCurrentKey = false, currentKey;
return source.subscribe(function (value) {
var key = value;
if (keySelector) {
try {
key = keySelector(value);
} catch (e) {
o.onError(e);
return;
}
}
if (hasCurrentKey) {
try {
var comparerEquals = comparer(currentKey, key);
} catch (e) {
o.onError(e);
return;
}
}
if (!hasCurrentKey || !comparerEquals) {
hasCurrentKey = true;
currentKey = key;
o.onNext(value);
}
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, this);
};
/**
* Invokes an action for each element in the observable sequence and invokes an action upon graceful or exceptional termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function | Observer} observerOrOnNext Action to invoke for each element in the observable sequence or an observer.
* @param {Function} [onError] Action to invoke upon exceptional termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @param {Function} [onCompleted] Action to invoke upon graceful termination of the observable sequence. Used if only the observerOrOnNext parameter is also a function.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto['do'] = observableProto.tap = observableProto.doAction = function (observerOrOnNext, onError, onCompleted) {
var source = this, tapObserver = typeof observerOrOnNext === 'function' || typeof observerOrOnNext === 'undefined'?
observerCreate(observerOrOnNext || noop, onError || noop, onCompleted || noop) :
observerOrOnNext;
return new AnonymousObservable(function (observer) {
return source.subscribe(function (x) {
try {
tapObserver.onNext(x);
} catch (e) {
observer.onError(e);
}
observer.onNext(x);
}, function (err) {
try {
tapObserver.onError(err);
} catch (e) {
observer.onError(e);
}
observer.onError(err);
}, function () {
try {
tapObserver.onCompleted();
} catch (e) {
observer.onError(e);
}
observer.onCompleted();
});
}, this);
};
/**
* Invokes an action for each element in the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function} onNext Action to invoke for each element in the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doOnNext = observableProto.tapOnNext = function (onNext, thisArg) {
return this.tap(typeof thisArg !== 'undefined' ? function (x) { onNext.call(thisArg, x); } : onNext);
};
/**
* Invokes an action upon exceptional termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function} onError Action to invoke upon exceptional termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doOnError = observableProto.tapOnError = function (onError, thisArg) {
return this.tap(noop, typeof thisArg !== 'undefined' ? function (e) { onError.call(thisArg, e); } : onError);
};
/**
* Invokes an action upon graceful termination of the observable sequence.
* This method can be used for debugging, logging, etc. of query behavior by intercepting the message stream to run arbitrary actions for messages on the pipeline.
* @param {Function} onCompleted Action to invoke upon graceful termination of the observable sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} The source sequence with the side-effecting behavior applied.
*/
observableProto.doOnCompleted = observableProto.tapOnCompleted = function (onCompleted, thisArg) {
return this.tap(noop, null, typeof thisArg !== 'undefined' ? function () { onCompleted.call(thisArg); } : onCompleted);
};
/**
* Invokes a specified action after the source observable sequence terminates gracefully or exceptionally.
* @param {Function} finallyAction Action to invoke after the source observable sequence terminates.
* @returns {Observable} Source sequence with the action-invoking termination behavior applied.
*/
observableProto['finally'] = observableProto.ensure = function (action) {
var source = this;
return new AnonymousObservable(function (observer) {
var subscription;
try {
subscription = source.subscribe(observer);
} catch (e) {
action();
throw e;
}
return disposableCreate(function () {
try {
subscription.dispose();
} catch (e) {
throw e;
} finally {
action();
}
});
}, this);
};
/**
* @deprecated use #finally or #ensure instead.
*/
observableProto.finallyAction = function (action) {
//deprecate('finallyAction', 'finally or ensure');
return this.ensure(action);
};
/**
* Ignores all elements in an observable sequence leaving only the termination messages.
* @returns {Observable} An empty observable sequence that signals termination, successful or exceptional, of the source sequence.
*/
observableProto.ignoreElements = function () {
var source = this;
return new AnonymousObservable(function (o) {
return source.subscribe(noop, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* Materializes the implicit notifications of an observable sequence as explicit notification values.
* @returns {Observable} An observable sequence containing the materialized notification values from the source sequence.
*/
observableProto.materialize = function () {
var source = this;
return new AnonymousObservable(function (observer) {
return source.subscribe(function (value) {
observer.onNext(notificationCreateOnNext(value));
}, function (e) {
observer.onNext(notificationCreateOnError(e));
observer.onCompleted();
}, function () {
observer.onNext(notificationCreateOnCompleted());
observer.onCompleted();
});
}, source);
};
/**
* Repeats the observable sequence a specified number of times. If the repeat count is not specified, the sequence repeats indefinitely.
* @param {Number} [repeatCount] Number of times to repeat the sequence. If not provided, repeats the sequence indefinitely.
* @returns {Observable} The observable sequence producing the elements of the given sequence repeatedly.
*/
observableProto.repeat = function (repeatCount) {
return enumerableRepeat(this, repeatCount).concat();
};
/**
* Repeats the source observable sequence the specified number of times or until it successfully terminates. If the retry count is not specified, it retries indefinitely.
* Note if you encounter an error and want it to retry once, then you must use .retry(2);
*
* @example
* var res = retried = retry.repeat();
* var res = retried = retry.repeat(2);
* @param {Number} [retryCount] Number of times to retry the sequence. If not provided, retry the sequence indefinitely.
* @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
*/
observableProto.retry = function (retryCount) {
return enumerableRepeat(this, retryCount).catchError();
};
/**
* Repeats the source observable sequence upon error each time the notifier emits or until it successfully terminates.
* if the notifier completes, the observable sequence completes.
*
* @example
* var timer = Observable.timer(500);
* var source = observable.retryWhen(timer);
* @param {Observable} [notifier] An observable that triggers the retries or completes the observable with onNext or onCompleted respectively.
* @returns {Observable} An observable sequence producing the elements of the given sequence repeatedly until it terminates successfully.
*/
observableProto.retryWhen = function (notifier) {
return enumerableRepeat(this).catchErrorWhen(notifier);
};
/**
* Applies an accumulator function over an observable sequence and returns each intermediate result. The optional seed value is used as the initial accumulator value.
* For aggregation behavior with no intermediate results, see Observable.aggregate.
* @example
* var res = source.scan(function (acc, x) { return acc + x; });
* var res = source.scan(0, function (acc, x) { return acc + x; });
* @param {Mixed} [seed] The initial accumulator value.
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @returns {Observable} An observable sequence containing the accumulated values.
*/
observableProto.scan = function () {
var hasSeed = false, seed, accumulator, source = this;
if (arguments.length === 2) {
hasSeed = true;
seed = arguments[0];
accumulator = arguments[1];
} else {
accumulator = arguments[0];
}
return new AnonymousObservable(function (o) {
var hasAccumulation, accumulation, hasValue;
return source.subscribe (
function (x) {
!hasValue && (hasValue = true);
try {
if (hasAccumulation) {
accumulation = accumulator(accumulation, x);
} else {
accumulation = hasSeed ? accumulator(seed, x) : x;
hasAccumulation = true;
}
} catch (e) {
o.onError(e);
return;
}
o.onNext(accumulation);
},
function (e) { o.onError(e); },
function () {
!hasValue && hasSeed && o.onNext(seed);
o.onCompleted();
}
);
}, source);
};
/**
* Bypasses a specified number of elements at the end of an observable sequence.
* @description
* This operator accumulates a queue with a length enough to store the first `count` elements. As more elements are
* received, elements are taken from the front of the queue and produced on the result sequence. This causes elements to be delayed.
* @param count Number of elements to bypass at the end of the source sequence.
* @returns {Observable} An observable sequence containing the source sequence elements except for the bypassed ones at the end.
*/
observableProto.skipLast = function (count) {
var source = this;
return new AnonymousObservable(function (o) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && o.onNext(q.shift());
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* Prepends a sequence of values to an observable sequence with an optional scheduler and an argument list of values to prepend.
* @example
* var res = source.startWith(1, 2, 3);
* var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3);
* @param {Arguments} args The specified values to prepend to the observable sequence
* @returns {Observable} The source sequence prepended with the specified values.
*/
observableProto.startWith = function () {
var values, scheduler, start = 0;
if (!!arguments.length && isScheduler(arguments[0])) {
scheduler = arguments[0];
start = 1;
} else {
scheduler = immediateScheduler;
}
for(var args = [], i = start, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
return enumerableOf([observableFromArray(args, scheduler), this]).concat();
};
/**
* Returns a specified number of contiguous elements from the end of an observable sequence.
* @description
* This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of
* the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence.
*/
observableProto.takeLast = function (count) {
var source = this;
return new AnonymousObservable(function (o) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && q.shift();
}, function (e) { o.onError(e); }, function () {
while (q.length > 0) { o.onNext(q.shift()); }
o.onCompleted();
});
}, source);
};
/**
* Returns an array with the specified number of contiguous elements from the end of an observable sequence.
*
* @description
* This operator accumulates a buffer with a length enough to store count elements. Upon completion of the
* source sequence, this buffer is produced on the result sequence.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @returns {Observable} An observable sequence containing a single array with the specified number of elements from the end of the source sequence.
*/
observableProto.takeLastBuffer = function (count) {
var source = this;
return new AnonymousObservable(function (o) {
var q = [];
return source.subscribe(function (x) {
q.push(x);
q.length > count && q.shift();
}, function (e) { o.onError(e); }, function () {
o.onNext(q);
o.onCompleted();
});
}, source);
};
/**
* Projects each element of an observable sequence into zero or more windows which are produced based on element count information.
*
* var res = xs.windowWithCount(10);
* var res = xs.windowWithCount(10, 1);
* @param {Number} count Length of each window.
* @param {Number} [skip] Number of elements to skip between creation of consecutive windows. If not specified, defaults to the count.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.windowWithCount = function (count, skip) {
var source = this;
+count || (count = 0);
Math.abs(count) === Infinity && (count = 0);
if (count <= 0) { throw new Error(argumentOutOfRange); }
skip == null && (skip = count);
+skip || (skip = 0);
Math.abs(skip) === Infinity && (skip = 0);
if (skip <= 0) { throw new Error(argumentOutOfRange); }
return new AnonymousObservable(function (observer) {
var m = new SingleAssignmentDisposable(),
refCountDisposable = new RefCountDisposable(m),
n = 0,
q = [];
function createWindow () {
var s = new Subject();
q.push(s);
observer.onNext(addRef(s, refCountDisposable));
}
createWindow();
m.setDisposable(source.subscribe(
function (x) {
for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); }
var c = n - count + 1;
c >= 0 && c % skip === 0 && q.shift().onCompleted();
++n % skip === 0 && createWindow();
},
function (e) {
while (q.length > 0) { q.shift().onError(e); }
observer.onError(e);
},
function () {
while (q.length > 0) { q.shift().onCompleted(); }
observer.onCompleted();
}
));
return refCountDisposable;
}, source);
};
function concatMap(source, selector, thisArg) {
var selectorFunc = bindCallback(selector, thisArg, 3);
return source.map(function (x, i) {
var result = selectorFunc(x, i, source);
isPromise(result) && (result = observableFromPromise(result));
(isArrayLike(result) || isIterable(result)) && (result = observableFrom(result));
return result;
}).concatAll();
}
/**
* One of the Following:
* Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
*
* @example
* var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); });
* Or:
* Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
*
* var res = source.concatMap(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
* Or:
* Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
*
* var res = source.concatMap(Rx.Observable.fromArray([1,2,3]));
* @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the
* source sequence onto which could be either an observable or Promise.
* @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
*/
observableProto.selectConcat = observableProto.concatMap = function (selector, resultSelector, thisArg) {
if (isFunction(selector) && isFunction(resultSelector)) {
return this.concatMap(function (x, i) {
var selectorResult = selector(x, i);
isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult));
(isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult));
return selectorResult.map(function (y, i2) {
return resultSelector(x, y, i, i2);
});
});
}
return isFunction(selector) ?
concatMap(this, selector, thisArg) :
concatMap(this, function () { return selector; });
};
/**
* Projects each notification of an observable sequence to an observable sequence and concats the resulting observable sequences into one observable sequence.
* @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element.
* @param {Function} onError A transform function to apply when an error occurs in the source sequence.
* @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached.
* @param {Any} [thisArg] An optional "this" to use to invoke each transform.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence.
*/
observableProto.concatMapObserver = observableProto.selectConcatObserver = function(onNext, onError, onCompleted, thisArg) {
var source = this,
onNextFunc = bindCallback(onNext, thisArg, 2),
onErrorFunc = bindCallback(onError, thisArg, 1),
onCompletedFunc = bindCallback(onCompleted, thisArg, 0);
return new AnonymousObservable(function (observer) {
var index = 0;
return source.subscribe(
function (x) {
var result;
try {
result = onNextFunc(x, index++);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
},
function (err) {
var result;
try {
result = onErrorFunc(err);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
},
function () {
var result;
try {
result = onCompletedFunc();
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
});
}, this).concatAll();
};
/**
* Returns the elements of the specified sequence or the specified value in a singleton sequence if the sequence is empty.
*
* var res = obs = xs.defaultIfEmpty();
* 2 - obs = xs.defaultIfEmpty(false);
*
* @memberOf Observable#
* @param defaultValue The value to return if the sequence is empty. If not provided, this defaults to null.
* @returns {Observable} An observable sequence that contains the specified default value if the source is empty; otherwise, the elements of the source itself.
*/
observableProto.defaultIfEmpty = function (defaultValue) {
var source = this;
defaultValue === undefined && (defaultValue = null);
return new AnonymousObservable(function (observer) {
var found = false;
return source.subscribe(function (x) {
found = true;
observer.onNext(x);
},
function (e) { observer.onError(e); },
function () {
!found && observer.onNext(defaultValue);
observer.onCompleted();
});
}, source);
};
// Swap out for Array.findIndex
function arrayIndexOfComparer(array, item, comparer) {
for (var i = 0, len = array.length; i < len; i++) {
if (comparer(array[i], item)) { return i; }
}
return -1;
}
function HashSet(comparer) {
this.comparer = comparer;
this.set = [];
}
HashSet.prototype.push = function(value) {
var retValue = arrayIndexOfComparer(this.set, value, this.comparer) === -1;
retValue && this.set.push(value);
return retValue;
};
/**
* Returns an observable sequence that contains only distinct elements according to the keySelector and the comparer.
* Usage of this operator should be considered carefully due to the maintenance of an internal lookup structure which can grow large.
*
* @example
* var res = obs = xs.distinct();
* 2 - obs = xs.distinct(function (x) { return x.id; });
* 2 - obs = xs.distinct(function (x) { return x.id; }, function (a,b) { return a === b; });
* @param {Function} [keySelector] A function to compute the comparison key for each element.
* @param {Function} [comparer] Used to compare items in the collection.
* @returns {Observable} An observable sequence only containing the distinct elements, based on a computed key value, from the source sequence.
*/
observableProto.distinct = function (keySelector, comparer) {
var source = this;
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (o) {
var hashSet = new HashSet(comparer);
return source.subscribe(function (x) {
var key = x;
if (keySelector) {
try {
key = keySelector(x);
} catch (e) {
o.onError(e);
return;
}
}
hashSet.push(key) && o.onNext(x);
},
function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, this);
};
/**
* Groups the elements of an observable sequence according to a specified key selector function and comparer and selects the resulting elements by using a specified function.
*
* @example
* var res = observable.groupBy(function (x) { return x.id; });
* 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; });
* 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function (x) { return x.toString(); });
* @param {Function} keySelector A function to extract the key for each element.
* @param {Function} [elementSelector] A function to map each source element to an element in an observable group.
* @param {Function} [comparer] Used to determine whether the objects are equal.
* @returns {Observable} A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value.
*/
observableProto.groupBy = function (keySelector, elementSelector, comparer) {
return this.groupByUntil(keySelector, elementSelector, observableNever, comparer);
};
/**
* Groups the elements of an observable sequence according to a specified key selector function.
* A duration selector function is used to control the lifetime of groups. When a group expires, it receives an OnCompleted notification. When a new element with the same
* key value as a reclaimed group occurs, the group will be reborn with a new lifetime request.
*
* @example
* var res = observable.groupByUntil(function (x) { return x.id; }, null, function () { return Rx.Observable.never(); });
* 2 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); });
* 3 - observable.groupBy(function (x) { return x.id; }), function (x) { return x.name; }, function () { return Rx.Observable.never(); }, function (x) { return x.toString(); });
* @param {Function} keySelector A function to extract the key for each element.
* @param {Function} durationSelector A function to signal the expiration of a group.
* @param {Function} [comparer] Used to compare objects. When not specified, the default comparer is used.
* @returns {Observable}
* A sequence of observable groups, each of which corresponds to a unique key value, containing all elements that share that same key value.
* If a group's lifetime expires, a new group with the same key value can be created once an element with such a key value is encoutered.
*
*/
observableProto.groupByUntil = function (keySelector, elementSelector, durationSelector, comparer) {
var source = this;
elementSelector || (elementSelector = identity);
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (observer) {
function handleError(e) { return function (item) { item.onError(e); }; }
var map = new Dictionary(0, comparer),
groupDisposable = new CompositeDisposable(),
refCountDisposable = new RefCountDisposable(groupDisposable);
groupDisposable.add(source.subscribe(function (x) {
var key;
try {
key = keySelector(x);
} catch (e) {
map.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
var fireNewMapEntry = false,
writer = map.tryGetValue(key);
if (!writer) {
writer = new Subject();
map.set(key, writer);
fireNewMapEntry = true;
}
if (fireNewMapEntry) {
var group = new GroupedObservable(key, writer, refCountDisposable),
durationGroup = new GroupedObservable(key, writer);
try {
duration = durationSelector(durationGroup);
} catch (e) {
map.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
observer.onNext(group);
var md = new SingleAssignmentDisposable();
groupDisposable.add(md);
var expire = function () {
map.remove(key) && writer.onCompleted();
groupDisposable.remove(md);
};
md.setDisposable(duration.take(1).subscribe(
noop,
function (exn) {
map.getValues().forEach(handleError(exn));
observer.onError(exn);
},
expire)
);
}
var element;
try {
element = elementSelector(x);
} catch (e) {
map.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
writer.onNext(element);
}, function (ex) {
map.getValues().forEach(handleError(ex));
observer.onError(ex);
}, function () {
map.getValues().forEach(function (item) { item.onCompleted(); });
observer.onCompleted();
}));
return refCountDisposable;
}, source);
};
var MapObservable = (function (__super__) {
inherits(MapObservable, __super__);
function MapObservable(source, selector, thisArg) {
this.source = source;
this.selector = bindCallback(selector, thisArg, 3);
__super__.call(this);
}
MapObservable.prototype.internalMap = function (selector, thisArg) {
var self = this;
return new MapObservable(this.source, function (x, i, o) { return selector(self.selector(x, i, o), i, o); }, thisArg)
};
MapObservable.prototype.subscribeCore = function (observer) {
return this.source.subscribe(new MapObserver(observer, this.selector, this));
};
return MapObservable;
}(ObservableBase));
function MapObserver(observer, selector, source) {
this.observer = observer;
this.selector = selector;
this.source = source;
this.index = 0;
this.isStopped = false;
}
MapObserver.prototype.onNext = function(x) {
if (this.isStopped) { return; }
try {
var result = this.selector(x, this.index++, this.source);
} catch(e) {
return this.observer.onError(e);
}
this.observer.onNext(result);
};
MapObserver.prototype.onError = function (e) {
if(!this.isStopped) { this.isStopped = true; this.observer.onError(e); }
};
MapObserver.prototype.onCompleted = function () {
if(!this.isStopped) { this.isStopped = true; this.observer.onCompleted(); }
};
MapObserver.prototype.dispose = function() { this.isStopped = true; };
MapObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.observer.onError(e);
return true;
}
return false;
};
/**
* Projects each element of an observable sequence into a new form by incorporating the element's index.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source.
*/
observableProto.map = observableProto.select = function (selector, thisArg) {
var selectorFn = typeof selector === 'function' ? selector : function () { return selector; };
return this instanceof MapObservable ?
this.internalMap(selector, thisArg) :
new MapObservable(this, selectorFn, thisArg);
};
/**
* Retrieves the value of a specified nested property from all elements in
* the Observable sequence.
* @param {Arguments} arguments The nested properties to pluck.
* @returns {Observable} Returns a new Observable sequence of property values.
*/
observableProto.pluck = function () {
var args = arguments, len = arguments.length;
if (len === 0) { throw new Error('List of properties cannot be empty.'); }
return this.map(function (x) {
var currentProp = x;
for (var i = 0; i < len; i++) {
var p = currentProp[args[i]];
if (typeof p !== 'undefined') {
currentProp = p;
} else {
return undefined;
}
}
return currentProp;
});
};
function flatMap(source, selector, thisArg) {
var selectorFunc = bindCallback(selector, thisArg, 3);
return source.map(function (x, i) {
var result = selectorFunc(x, i, source);
isPromise(result) && (result = observableFromPromise(result));
(isArrayLike(result) || isIterable(result)) && (result = observableFrom(result));
return result;
}).mergeAll();
}
/**
* One of the Following:
* Projects each element of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
*
* @example
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); });
* Or:
* Projects each element of an observable sequence to an observable sequence, invokes the result selector for the source element and each of the corresponding inner sequence's elements, and merges the results into one observable sequence.
*
* var res = source.selectMany(function (x) { return Rx.Observable.range(0, x); }, function (x, y) { return x + y; });
* Or:
* Projects each element of the source observable sequence to the other observable sequence and merges the resulting observable sequences into one observable sequence.
*
* var res = source.selectMany(Rx.Observable.fromArray([1,2,3]));
* @param {Function} selector A transform function to apply to each element or an observable sequence to project each element from the source sequence onto which could be either an observable or Promise.
* @param {Function} [resultSelector] A transform function to apply to each element of the intermediate sequence.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function collectionSelector on each element of the input sequence and then mapping each of those sequence elements and their corresponding source element to a result element.
*/
observableProto.selectMany = observableProto.flatMap = function (selector, resultSelector, thisArg) {
if (isFunction(selector) && isFunction(resultSelector)) {
return this.flatMap(function (x, i) {
var selectorResult = selector(x, i);
isPromise(selectorResult) && (selectorResult = observableFromPromise(selectorResult));
(isArrayLike(selectorResult) || isIterable(selectorResult)) && (selectorResult = observableFrom(selectorResult));
return selectorResult.map(function (y, i2) {
return resultSelector(x, y, i, i2);
});
}, thisArg);
}
return isFunction(selector) ?
flatMap(this, selector, thisArg) :
flatMap(this, function () { return selector; });
};
/**
* Projects each notification of an observable sequence to an observable sequence and merges the resulting observable sequences into one observable sequence.
* @param {Function} onNext A transform function to apply to each element; the second parameter of the function represents the index of the source element.
* @param {Function} onError A transform function to apply when an error occurs in the source sequence.
* @param {Function} onCompleted A transform function to apply when the end of the source sequence is reached.
* @param {Any} [thisArg] An optional "this" to use to invoke each transform.
* @returns {Observable} An observable sequence whose elements are the result of invoking the one-to-many transform function corresponding to each notification in the input sequence.
*/
observableProto.flatMapObserver = observableProto.selectManyObserver = function (onNext, onError, onCompleted, thisArg) {
var source = this;
return new AnonymousObservable(function (observer) {
var index = 0;
return source.subscribe(
function (x) {
var result;
try {
result = onNext.call(thisArg, x, index++);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
},
function (err) {
var result;
try {
result = onError.call(thisArg, err);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
},
function () {
var result;
try {
result = onCompleted.call(thisArg);
} catch (e) {
observer.onError(e);
return;
}
isPromise(result) && (result = observableFromPromise(result));
observer.onNext(result);
observer.onCompleted();
});
}, source).mergeAll();
};
/**
* Projects each element of an observable sequence into a new sequence of observable sequences by incorporating the element's index and then
* transforms an observable sequence of observable sequences into an observable sequence producing values only from the most recent observable sequence.
* @param {Function} selector A transform function to apply to each source element; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence whose elements are the result of invoking the transform function on each element of source producing an Observable of Observable sequences
* and that at any point in time produces the elements of the most recent inner observable sequence that has been received.
*/
observableProto.selectSwitch = observableProto.flatMapLatest = observableProto.switchMap = function (selector, thisArg) {
return this.select(selector, thisArg).switchLatest();
};
/**
* Bypasses a specified number of elements in an observable sequence and then returns the remaining elements.
* @param {Number} count The number of elements to skip before returning the remaining elements.
* @returns {Observable} An observable sequence that contains the elements that occur after the specified index in the input sequence.
*/
observableProto.skip = function (count) {
if (count < 0) { throw new Error(argumentOutOfRange); }
var source = this;
return new AnonymousObservable(function (o) {
var remaining = count;
return source.subscribe(function (x) {
if (remaining <= 0) {
o.onNext(x);
} else {
remaining--;
}
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* Bypasses elements in an observable sequence as long as a specified condition is true and then returns the remaining elements.
* The element's index is used in the logic of the predicate function.
*
* var res = source.skipWhile(function (value) { return value < 10; });
* var res = source.skipWhile(function (value, index) { return value < 10 || index < 10; });
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence starting at the first element in the linear series that does not pass the test specified by predicate.
*/
observableProto.skipWhile = function (predicate, thisArg) {
var source = this,
callback = bindCallback(predicate, thisArg, 3);
return new AnonymousObservable(function (o) {
var i = 0, running = false;
return source.subscribe(function (x) {
if (!running) {
try {
running = !callback(x, i++, source);
} catch (e) {
o.onError(e);
return;
}
}
running && o.onNext(x);
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* Returns a specified number of contiguous elements from the start of an observable sequence, using the specified scheduler for the edge case of take(0).
*
* var res = source.take(5);
* var res = source.take(0, Rx.Scheduler.timeout);
* @param {Number} count The number of elements to return.
* @param {Scheduler} [scheduler] Scheduler used to produce an OnCompleted message in case <paramref name="count count</paramref> is set to 0.
* @returns {Observable} An observable sequence that contains the specified number of elements from the start of the input sequence.
*/
observableProto.take = function (count, scheduler) {
if (count < 0) { throw new RangeError(argumentOutOfRange); }
if (count === 0) { return observableEmpty(scheduler); }
var source = this;
return new AnonymousObservable(function (o) {
var remaining = count;
return source.subscribe(function (x) {
if (remaining-- > 0) {
o.onNext(x);
remaining === 0 && o.onCompleted();
}
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
/**
* Returns elements from an observable sequence as long as a specified condition is true.
* The element's index is used in the logic of the predicate function.
* @param {Function} predicate A function to test each element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains the elements from the input sequence that occur before the element at which the test no longer passes.
*/
observableProto.takeWhile = function (predicate, thisArg) {
var source = this,
callback = bindCallback(predicate, thisArg, 3);
return new AnonymousObservable(function (o) {
var i = 0, running = true;
return source.subscribe(function (x) {
if (running) {
try {
running = callback(x, i++, source);
} catch (e) {
o.onError(e);
return;
}
if (running) {
o.onNext(x);
} else {
o.onCompleted();
}
}
}, function (e) { o.onError(e); }, function () { o.onCompleted(); });
}, source);
};
var FilterObservable = (function (__super__) {
inherits(FilterObservable, __super__);
function FilterObservable(source, predicate, thisArg) {
this.source = source;
this.predicate = bindCallback(predicate, thisArg, 3);
__super__.call(this);
}
FilterObservable.prototype.subscribeCore = function (observer) {
return this.source.subscribe(new FilterObserver(observer, this.predicate, this));
};
FilterObservable.prototype.internalFilter = function(predicate, thisArg) {
var self = this;
return new FilterObservable(this.source, function(x, i, o) { return self.predicate(x, i, o) && predicate(x, i, o); }, thisArg);
};
return FilterObservable;
}(ObservableBase));
function FilterObserver(observer, predicate, source) {
this.observer = observer;
this.predicate = predicate;
this.source = source;
this.index = 0;
this.isStopped = false;
}
FilterObserver.prototype.onNext = function(x) {
try {
var shouldYield = this.predicate(x, this.index++, this.source);
} catch(e) {
return this.observer.onError(e);
}
shouldYield && this.observer.onNext(x);
};
FilterObserver.prototype.onError = function (e) {
if(!this.isStopped) { this.isStopped = true; this.observer.onError(e); }
};
FilterObserver.prototype.onCompleted = function () {
if(!this.isStopped) { this.isStopped = true; this.observer.onCompleted(); }
};
FilterObserver.prototype.dispose = function() { this.isStopped = true; };
FilterObserver.prototype.fail = function (e) {
if (!this.isStopped) {
this.isStopped = true;
this.observer.onError(e);
return true;
}
return false;
};
/**
* Filters the elements of an observable sequence based on a predicate by incorporating the element's index.
* @param {Function} predicate A function to test each source element for a condition; the second parameter of the function represents the index of the source element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence that contains elements from the input sequence that satisfy the condition.
*/
observableProto.filter = observableProto.where = function (predicate, thisArg) {
return this instanceof FilterObservable ? this.internalFilter(predicate, thisArg) :
new FilterObservable(this, predicate, thisArg);
};
function extremaBy(source, keySelector, comparer) {
return new AnonymousObservable(function (o) {
var hasValue = false, lastKey = null, list = [];
return source.subscribe(function (x) {
var comparison, key;
try {
key = keySelector(x);
} catch (ex) {
o.onError(ex);
return;
}
comparison = 0;
if (!hasValue) {
hasValue = true;
lastKey = key;
} else {
try {
comparison = comparer(key, lastKey);
} catch (ex1) {
o.onError(ex1);
return;
}
}
if (comparison > 0) {
lastKey = key;
list = [];
}
if (comparison >= 0) { list.push(x); }
}, function (e) { o.onError(e); }, function () {
o.onNext(list);
o.onCompleted();
});
}, source);
}
function firstOnly(x) {
if (x.length === 0) { throw new 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.
* @deprecated Use #reduce instead
* @param {Mixed} [seed] The initial accumulator value.
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @returns {Observable} An observable sequence containing a single element with the final accumulator value.
*/
observableProto.aggregate = function () {
//deprecate('aggregate', 'reduce');
var hasSeed = false, accumulator, seed, source = this;
if (arguments.length === 2) {
hasSeed = true;
seed = arguments[0];
accumulator = arguments[1];
} else {
accumulator = arguments[0];
}
return new AnonymousObservable(function (o) {
var hasAccumulation, accumulation, hasValue;
return source.subscribe (
function (x) {
!hasValue && (hasValue = true);
try {
if (hasAccumulation) {
accumulation = accumulator(accumulation, x);
} else {
accumulation = hasSeed ? accumulator(seed, x) : x;
hasAccumulation = true;
}
} catch (e) {
o.onError(e);
return;
}
},
function (e) { o.onError(e); },
function () {
hasValue && o.onNext(accumulation);
!hasValue && hasSeed && o.onNext(seed);
!hasValue && !hasSeed && o.onError(new Error(sequenceContainsNoElements));
o.onCompleted();
}
);
}, source);
};
/**
* Applies an accumulator function over an observable sequence, returning the result of the aggregation as a single element in the result sequence. The specified seed value is used as the initial accumulator value.
* For aggregation behavior with incremental intermediate results, see Observable.scan.
* @param {Function} accumulator An accumulator function to be invoked on each element.
* @param {Any} [seed] The initial accumulator value.
* @returns {Observable} An observable sequence containing a single element with the final accumulator value.
*/
observableProto.reduce = function (accumulator) {
var hasSeed = false, seed, source = this;
if (arguments.length === 2) {
hasSeed = true;
seed = arguments[1];
}
return new AnonymousObservable(function (o) {
var hasAccumulation, accumulation, hasValue;
return source.subscribe (
function (x) {
!hasValue && (hasValue = true);
try {
if (hasAccumulation) {
accumulation = accumulator(accumulation, x);
} else {
accumulation = hasSeed ? accumulator(seed, x) : x;
hasAccumulation = true;
}
} catch (e) {
o.onError(e);
return;
}
},
function (e) { o.onError(e); },
function () {
hasValue && o.onNext(accumulation);
!hasValue && hasSeed && o.onNext(seed);
!hasValue && !hasSeed && o.onError(new Error(sequenceContainsNoElements));
o.onCompleted();
}
);
}, source);
};
/**
* Determines whether any element of an observable sequence satisfies a condition if present, else if any items are in the sequence.
* @param {Function} [predicate] A function to test each element for a condition.
* @returns {Observable} An observable sequence containing a single element determining whether any elements in the source sequence pass the test in the specified predicate if given, else if any items are in the sequence.
*/
observableProto.some = function (predicate, thisArg) {
var source = this;
return predicate ?
source.filter(predicate, thisArg).some() :
new AnonymousObservable(function (observer) {
return source.subscribe(function () {
observer.onNext(true);
observer.onCompleted();
}, function (e) { observer.onError(e); }, function () {
observer.onNext(false);
observer.onCompleted();
});
}, source);
};
/** @deprecated use #some instead */
observableProto.any = function () {
//deprecate('any', 'some');
return this.some.apply(this, arguments);
};
/**
* Determines whether an observable sequence is empty.
* @returns {Observable} An observable sequence containing a single element determining whether the source sequence is empty.
*/
observableProto.isEmpty = function () {
return this.any().map(not);
};
/**
* Determines whether all elements of an observable sequence satisfy a condition.
* @param {Function} [predicate] A function to test each element for a condition.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element determining whether all elements in the source sequence pass the test in the specified predicate.
*/
observableProto.every = function (predicate, thisArg) {
return this.filter(function (v) { return !predicate(v); }, thisArg).some().map(not);
};
/** @deprecated use #every instead */
observableProto.all = function () {
//deprecate('all', 'every');
return this.every.apply(this, arguments);
};
/**
* Determines whether an observable sequence includes a specified element with an optional equality comparer.
* @param searchElement The value to locate in the source sequence.
* @param {Number} [fromIndex] An equality comparer to compare elements.
* @returns {Observable} An observable sequence containing a single element determining whether the source sequence includes an element that has the specified value from the given index.
*/
observableProto.includes = function (searchElement, fromIndex) {
var source = this;
function comparer(a, b) {
return (a === 0 && b === 0) || (a === b || (isNaN(a) && isNaN(b)));
}
return new AnonymousObservable(function (o) {
var i = 0, n = +fromIndex || 0;
Math.abs(n) === Infinity && (n = 0);
if (n < 0) {
o.onNext(false);
o.onCompleted();
return disposableEmpty;
}
return source.subscribe(
function (x) {
if (i++ >= n && comparer(x, searchElement)) {
o.onNext(true);
o.onCompleted();
}
},
function (e) { o.onError(e); },
function () {
o.onNext(false);
o.onCompleted();
});
}, this);
};
/**
* @deprecated use #includes instead.
*/
observableProto.contains = function (searchElement, fromIndex) {
//deprecate('contains', 'includes');
observableProto.includes(searchElement, fromIndex);
};
/**
* Returns an observable sequence containing a value that represents how many elements in the specified observable sequence satisfy a condition if provided, else the count of items.
* @example
* res = source.count();
* res = source.count(function (x) { return x > 3; });
* @param {Function} [predicate]A function to test each element for a condition.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element with a number that represents how many elements in the input sequence satisfy the condition in the predicate function if provided, else the count of items in the sequence.
*/
observableProto.count = function (predicate, thisArg) {
return predicate ?
this.filter(predicate, thisArg).count() :
this.reduce(function (count) { return count + 1; }, 0);
};
/**
* Returns the first index at which a given element can be found in the observable sequence, or -1 if it is not present.
* @param {Any} searchElement Element to locate in the array.
* @param {Number} [fromIndex] The index to start the search. If not specified, defaults to 0.
* @returns {Observable} And observable sequence containing the first index at which a given element can be found in the observable sequence, or -1 if it is not present.
*/
observableProto.indexOf = function(searchElement, fromIndex) {
var source = this;
return new AnonymousObservable(function (o) {
var i = 0, n = +fromIndex || 0;
Math.abs(n) === Infinity && (n = 0);
if (n < 0) {
o.onNext(-1);
o.onCompleted();
return disposableEmpty;
}
return source.subscribe(
function (x) {
if (i >= n && x === searchElement) {
o.onNext(i);
o.onCompleted();
}
i++;
},
function (e) { o.onError(e); },
function () {
o.onNext(-1);
o.onCompleted();
});
}, source);
};
/**
* Computes the sum of a sequence of values that are obtained by invoking an optional transform function on each element of the input sequence, else if not specified computes the sum on each item in the sequence.
* @param {Function} [selector] A transform function to apply to each element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element with the sum of the values in the source sequence.
*/
observableProto.sum = function (keySelector, thisArg) {
return keySelector && isFunction(keySelector) ?
this.map(keySelector, thisArg).sum() :
this.reduce(function (prev, curr) { return prev + curr; }, 0);
};
/**
* Returns the elements in an observable sequence with the minimum key value according to the specified comparer.
* @example
* var res = source.minBy(function (x) { return x.value; });
* var res = source.minBy(function (x) { return x.value; }, function (x, y) { return x - y; });
* @param {Function} keySelector Key selector function.
* @param {Function} [comparer] Comparer used to compare key values.
* @returns {Observable} An observable sequence containing a list of zero or more elements that have a minimum key value.
*/
observableProto.minBy = function (keySelector, comparer) {
comparer || (comparer = defaultSubComparer);
return extremaBy(this, keySelector, function (x, y) { return comparer(x, y) * -1; });
};
/**
* Returns the minimum element in an observable sequence according to the optional comparer else a default greater than less than check.
* @example
* var res = source.min();
* var res = source.min(function (x, y) { return x.value - y.value; });
* @param {Function} [comparer] Comparer used to compare elements.
* @returns {Observable} An observable sequence containing a single element with the minimum element in the source sequence.
*/
observableProto.min = function (comparer) {
return this.minBy(identity, comparer).map(function (x) { return firstOnly(x); });
};
/**
* Returns the elements in an observable sequence with the maximum key value according to the specified comparer.
* @example
* var res = source.maxBy(function (x) { return x.value; });
* var res = source.maxBy(function (x) { return x.value; }, function (x, y) { return x - y;; });
* @param {Function} keySelector Key selector function.
* @param {Function} [comparer] Comparer used to compare key values.
* @returns {Observable} An observable sequence containing a list of zero or more elements that have a maximum key value.
*/
observableProto.maxBy = function (keySelector, comparer) {
comparer || (comparer = defaultSubComparer);
return extremaBy(this, keySelector, comparer);
};
/**
* Returns the maximum value in an observable sequence according to the specified comparer.
* @example
* var res = source.max();
* var res = source.max(function (x, y) { return x.value - y.value; });
* @param {Function} [comparer] Comparer used to compare elements.
* @returns {Observable} An observable sequence containing a single element with the maximum element in the source sequence.
*/
observableProto.max = function (comparer) {
return this.maxBy(identity, comparer).map(function (x) { return firstOnly(x); });
};
/**
* Computes the average of an observable sequence of values that are in the sequence or obtained by invoking a transform function on each element of the input sequence if present.
* @param {Function} [selector] A transform function to apply to each element.
* @param {Any} [thisArg] Object to use as this when executing callback.
* @returns {Observable} An observable sequence containing a single element with the average of the sequence of values.
*/
observableProto.average = function (keySelector, thisArg) {
return keySelector && isFunction(keySelector) ?
this.map(keySelector, thisArg).average() :
this.reduce(function (prev, cur) {
return {
sum: prev.sum + cur,
count: prev.count + 1
};
}, {sum: 0, count: 0 }).map(function (s) {
if (s.count === 0) { throw new Error(sequenceContainsNoElements); }
return s.sum / s.count;
});
};
/**
* Determines whether two sequences are equal by comparing the elements pairwise using a specified equality comparer.
*
* @example
* var res = res = source.sequenceEqual([1,2,3]);
* var res = res = source.sequenceEqual([{ value: 42 }], function (x, y) { return x.value === y.value; });
* 3 - res = source.sequenceEqual(Rx.Observable.returnValue(42));
* 4 - res = source.sequenceEqual(Rx.Observable.returnValue({ value: 42 }), function (x, y) { return x.value === y.value; });
* @param {Observable} second Second observable sequence or array to compare.
* @param {Function} [comparer] Comparer used to compare elements of both sequences.
* @returns {Observable} An observable sequence that contains a single element which indicates whether both sequences are of equal length and their corresponding elements are equal according to the specified equality comparer.
*/
observableProto.sequenceEqual = function (second, comparer) {
var first = this;
comparer || (comparer = defaultComparer);
return new AnonymousObservable(function (o) {
var donel = false, doner = false, ql = [], qr = [];
var subscription1 = first.subscribe(function (x) {
var equal, v;
if (qr.length > 0) {
v = qr.shift();
try {
equal = comparer(v, x);
} catch (e) {
o.onError(e);
return;
}
if (!equal) {
o.onNext(false);
o.onCompleted();
}
} else if (doner) {
o.onNext(false);
o.onCompleted();
} else {
ql.push(x);
}
}, function(e) { o.onError(e); }, function () {
donel = true;
if (ql.length === 0) {
if (qr.length > 0) {
o.onNext(false);
o.onCompleted();
} else if (doner) {
o.onNext(true);
o.onCompleted();
}
}
});
(isArrayLike(second) || isIterable(second)) && (second = observableFrom(second));
isPromise(second) && (second = observableFromPromise(second));
var subscription2 = second.subscribe(function (x) {
var equal;
if (ql.length > 0) {
var v = ql.shift();
try {
equal = comparer(v, x);
} catch (exception) {
o.onError(exception);
return;
}
if (!equal) {
o.onNext(false);
o.onCompleted();
}
} else if (donel) {
o.onNext(false);
o.onCompleted();
} else {
qr.push(x);
}
}, function(e) { o.onError(e); }, function () {
doner = true;
if (qr.length === 0) {
if (ql.length > 0) {
o.onNext(false);
o.onCompleted();
} else if (donel) {
o.onNext(true);
o.onCompleted();
}
}
});
return new CompositeDisposable(subscription1, subscription2);
}, first);
};
function elementAtOrDefault(source, index, hasDefault, defaultValue) {
if (index < 0) { throw new Error(argumentOutOfRange); }
return new AnonymousObservable(function (o) {
var i = index;
return source.subscribe(function (x) {
if (i-- === 0) {
o.onNext(x);
o.onCompleted();
}
}, function (e) { o.onError(e); }, function () {
if (!hasDefault) {
o.onError(new Error(argumentOutOfRange));
} else {
o.onNext(defaultValue);
o.onCompleted();
}
});
}, source);
}
/**
* Returns the element at a specified index in a sequence.
* @example
* var res = source.elementAt(5);
* @param {Number} index The zero-based index of the element to retrieve.
* @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence.
*/
observableProto.elementAt = function (index) {
return elementAtOrDefault(this, index, false);
};
/**
* Returns the element at a specified index in a sequence or a default value if the index is out of range.
* @example
* var res = source.elementAtOrDefault(5);
* var res = source.elementAtOrDefault(5, 0);
* @param {Number} index The zero-based index of the element to retrieve.
* @param [defaultValue] The default value if the index is outside the bounds of the source sequence.
* @returns {Observable} An observable sequence that produces the element at the specified position in the source sequence, or a default value if the index is outside the bounds of the source sequence.
*/
observableProto.elementAtOrDefault = function (index, defaultValue) {
return elementAtOrDefault(this, index, true, defaultValue);
};
function singleOrDefaultAsync(source, hasDefault, defaultValue) {
return new AnonymousObservable(function (o) {
var value = defaultValue, seenValue = false;
return source.subscribe(function (x) {
if (seenValue) {
o.onError(new Error('Sequence contains more than one element'));
} else {
value = x;
seenValue = true;
}
}, function (e) { o.onError(e); }, function () {
if (!seenValue && !hasDefault) {
o.onError(new Error(sequenceContainsNoElements));
} else {
o.onNext(value);
o.onCompleted();
}
});
}, source);
}
/**
* Returns the only element of an observable sequence that satisfies the condition in the optional predicate, and reports an exception if there is not exactly one element in the observable sequence.
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate.
*/
observableProto.single = function (predicate, thisArg) {
return predicate && isFunction(predicate) ?
this.where(predicate, thisArg).single() :
singleOrDefaultAsync(this, false);
};
/**
* Returns the only element of an observable sequence that matches the predicate, or a default value if no such element exists; this method reports an exception if there is more than one element in the observable sequence.
* @example
* var res = res = source.singleOrDefault();
* var res = res = source.singleOrDefault(function (x) { return x === 42; });
* res = source.singleOrDefault(function (x) { return x === 42; }, 0);
* res = source.singleOrDefault(null, 0);
* @memberOf Observable#
* @param {Function} predicate A predicate function to evaluate for elements in the source sequence.
* @param [defaultValue] The default value if the index is outside the bounds of the source sequence.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
*/
observableProto.singleOrDefault = function (predicate, defaultValue, thisArg) {
return predicate && isFunction(predicate) ?
this.filter(predicate, thisArg).singleOrDefault(null, defaultValue) :
singleOrDefaultAsync(this, true, defaultValue);
};
function firstOrDefaultAsync(source, hasDefault, defaultValue) {
return new AnonymousObservable(function (o) {
return source.subscribe(function (x) {
o.onNext(x);
o.onCompleted();
}, function (e) { o.onError(e); }, function () {
if (!hasDefault) {
o.onError(new Error(sequenceContainsNoElements));
} else {
o.onNext(defaultValue);
o.onCompleted();
}
});
}, source);
}
/**
* Returns the first element of an observable sequence that satisfies the condition in the predicate if present else the first item in the sequence.
* @example
* var res = res = source.first();
* var res = res = source.first(function (x) { return x > 3; });
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate if provided, else the first item in the sequence.
*/
observableProto.first = function (predicate, thisArg) {
return predicate ?
this.where(predicate, thisArg).first() :
firstOrDefaultAsync(this, false);
};
/**
* Returns the first element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param {Any} [defaultValue] The default value if no such element exists. If not specified, defaults to null.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the first element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
*/
observableProto.firstOrDefault = function (predicate, defaultValue, thisArg) {
return predicate ?
this.where(predicate).firstOrDefault(null, defaultValue) :
firstOrDefaultAsync(this, true, defaultValue);
};
function lastOrDefaultAsync(source, hasDefault, defaultValue) {
return new AnonymousObservable(function (o) {
var value = defaultValue, seenValue = false;
return source.subscribe(function (x) {
value = x;
seenValue = true;
}, function (e) { o.onError(e); }, function () {
if (!seenValue && !hasDefault) {
o.onError(new Error(sequenceContainsNoElements));
} else {
o.onNext(value);
o.onCompleted();
}
});
}, source);
}
/**
* Returns the last element of an observable sequence that satisfies the condition in the predicate if specified, else the last element.
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate.
*/
observableProto.last = function (predicate, thisArg) {
return predicate ?
this.where(predicate, thisArg).last() :
lastOrDefaultAsync(this, false);
};
/**
* Returns the last element of an observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
* @param {Function} [predicate] A predicate function to evaluate for elements in the source sequence.
* @param [defaultValue] The default value if no such element exists. If not specified, defaults to null.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the last element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
*/
observableProto.lastOrDefault = function (predicate, defaultValue, thisArg) {
return predicate ?
this.where(predicate, thisArg).lastOrDefault(null, defaultValue) :
lastOrDefaultAsync(this, true, defaultValue);
};
function findValue (source, predicate, thisArg, yieldIndex) {
var callback = bindCallback(predicate, thisArg, 3);
return new AnonymousObservable(function (o) {
var i = 0;
return source.subscribe(function (x) {
var shouldRun;
try {
shouldRun = callback(x, i, source);
} catch (e) {
o.onError(e);
return;
}
if (shouldRun) {
o.onNext(yieldIndex ? i : x);
o.onCompleted();
} else {
i++;
}
}, function (e) { o.onError(e); }, function () {
o.onNext(yieldIndex ? -1 : undefined);
o.onCompleted();
});
}, source);
}
/**
* Searches for an element that matches the conditions defined by the specified predicate, and returns the first occurrence within the entire Observable sequence.
* @param {Function} predicate The predicate that defines the conditions of the element to search for.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} An Observable sequence with the first element that matches the conditions defined by the specified predicate, if found; otherwise, undefined.
*/
observableProto.find = function (predicate, thisArg) {
return findValue(this, predicate, thisArg, false);
};
/**
* Searches for an element that matches the conditions defined by the specified predicate, and returns
* an Observable sequence with the zero-based index of the first occurrence within the entire Observable sequence.
* @param {Function} predicate The predicate that defines the conditions of the element to search for.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} An Observable sequence with the zero-based index of the first occurrence of an element that matches the conditions defined by match, if found; otherwise, –1.
*/
observableProto.findIndex = function (predicate, thisArg) {
return findValue(this, predicate, thisArg, true);
};
/**
* Converts the observable sequence to a Set if it exists.
* @returns {Observable} An observable sequence with a single value of a Set containing the values from the observable sequence.
*/
observableProto.toSet = function () {
if (typeof root.Set === 'undefined') { throw new TypeError(); }
var source = this;
return new AnonymousObservable(function (o) {
var s = new root.Set();
return source.subscribe(
function (x) { s.add(x); },
function (e) { o.onError(e); },
function () {
o.onNext(s);
o.onCompleted();
});
}, source);
};
/**
* Converts the observable sequence to a Map if it exists.
* @param {Function} keySelector A function which produces the key for the Map.
* @param {Function} [elementSelector] An optional function which produces the element for the Map. If not present, defaults to the value from the observable sequence.
* @returns {Observable} An observable sequence with a single value of a Map containing the values from the observable sequence.
*/
observableProto.toMap = function (keySelector, elementSelector) {
if (typeof root.Map === 'undefined') { throw new TypeError(); }
var source = this;
return new AnonymousObservable(function (o) {
var m = new root.Map();
return source.subscribe(
function (x) {
var key;
try {
key = keySelector(x);
} catch (e) {
o.onError(e);
return;
}
var element = x;
if (elementSelector) {
try {
element = elementSelector(x);
} catch (e) {
o.onError(e);
return;
}
}
m.set(key, element);
},
function (e) { o.onError(e); },
function () {
o.onNext(m);
o.onCompleted();
});
}, source);
};
var fnString = 'function',
throwString = 'throw',
isObject = Rx.internals.isObject;
function toThunk(obj, ctx) {
if (Array.isArray(obj)) { return objectToThunk.call(ctx, obj); }
if (isGeneratorFunction(obj)) { return observableSpawn(obj.call(ctx)); }
if (isGenerator(obj)) { return observableSpawn(obj); }
if (isObservable(obj)) { return observableToThunk(obj); }
if (isPromise(obj)) { return promiseToThunk(obj); }
if (typeof obj === fnString) { return obj; }
if (isObject(obj) || Array.isArray(obj)) { return objectToThunk.call(ctx, obj); }
return obj;
}
function objectToThunk(obj) {
var ctx = this;
return function (done) {
var keys = Object.keys(obj),
pending = keys.length,
results = new obj.constructor(),
finished;
if (!pending) {
timeoutScheduler.schedule(function () { done(null, results); });
return;
}
for (var i = 0, len = keys.length; i < len; i++) {
run(obj[keys[i]], keys[i]);
}
function run(fn, key) {
if (finished) { return; }
try {
fn = toThunk(fn, ctx);
if (typeof fn !== fnString) {
results[key] = fn;
return --pending || done(null, results);
}
fn.call(ctx, function(err, res) {
if (finished) { return; }
if (err) {
finished = true;
return done(err);
}
results[key] = res;
--pending || done(null, results);
});
} catch (e) {
finished = true;
done(e);
}
}
}
}
function observableToThunk(observable) {
return function (fn) {
var value, hasValue = false;
observable.subscribe(
function (v) {
value = v;
hasValue = true;
},
fn,
function () {
hasValue && fn(null, value);
});
}
}
function promiseToThunk(promise) {
return function(fn) {
promise.then(function(res) {
fn(null, res);
}, fn);
}
}
function isObservable(obj) {
return obj && typeof obj.subscribe === fnString;
}
function isGeneratorFunction(obj) {
return obj && obj.constructor && obj.constructor.name === 'GeneratorFunction';
}
function isGenerator(obj) {
return obj && typeof obj.next === fnString && typeof obj[throwString] === fnString;
}
/*
* Spawns a generator function which allows for Promises, Observable sequences, Arrays, Objects, Generators and functions.
* @param {Function} The spawning function.
* @returns {Function} a function which has a done continuation.
*/
var observableSpawn = Rx.spawn = function (fn) {
var isGenFun = isGeneratorFunction(fn);
return function (done) {
var ctx = this,
gen = fn;
if (isGenFun) {
for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
var len = args.length,
hasCallback = len && typeof args[len - 1] === fnString;
done = hasCallback ? args.pop() : handleError;
gen = fn.apply(this, args);
} else {
done = done || handleError;
}
next();
function exit(err, res) {
timeoutScheduler.schedule(done.bind(ctx, err, res));
}
function next(err, res) {
var ret;
// multiple args
if (arguments.length > 2) {
for(var res = [], i = 1, len = arguments.length; i < len; i++) { res.push(arguments[i]); }
}
if (err) {
try {
ret = gen[throwString](err);
} catch (e) {
return exit(e);
}
}
if (!err) {
try {
ret = gen.next(res);
} catch (e) {
return exit(e);
}
}
if (ret.done) {
return exit(null, ret.value);
}
ret.value = toThunk(ret.value, ctx);
if (typeof ret.value === fnString) {
var called = false;
try {
ret.value.call(ctx, function() {
if (called) {
return;
}
called = true;
next.apply(ctx, arguments);
});
} catch (e) {
timeoutScheduler.schedule(function () {
if (called) {
return;
}
called = true;
next.call(ctx, e);
});
}
return;
}
// Not supported
next(new TypeError('Rx.spawn only supports a function, Promise, Observable, Object or Array.'));
}
}
};
function handleError(err) {
if (!err) { return; }
timeoutScheduler.schedule(function() {
throw err;
});
}
/**
* Invokes the specified function asynchronously on the specified scheduler, surfacing the result through an observable sequence.
*
* @example
* var res = Rx.Observable.start(function () { console.log('hello'); });
* var res = Rx.Observable.start(function () { console.log('hello'); }, Rx.Scheduler.timeout);
* var res = Rx.Observable.start(function () { this.log('hello'); }, Rx.Scheduler.timeout, console);
*
* @param {Function} func Function to run asynchronously.
* @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout.
* @param [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @returns {Observable} An observable sequence exposing the function's result value, or an exception.
*
* Remarks
* * The function is called immediately, not during the subscription of the resulting sequence.
* * Multiple subscriptions to the resulting sequence can observe the function's result.
*/
Observable.start = function (func, context, scheduler) {
return observableToAsync(func, context, scheduler)();
};
/**
* Converts the function into an asynchronous function. Each invocation of the resulting asynchronous function causes an invocation of the original synchronous function on the specified scheduler.
* @param {Function} function Function to convert to an asynchronous function.
* @param {Scheduler} [scheduler] Scheduler to run the function on. If not specified, defaults to Scheduler.timeout.
* @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @returns {Function} Asynchronous function.
*/
var observableToAsync = Observable.toAsync = function (func, context, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return function () {
var args = arguments,
subject = new AsyncSubject();
scheduler.schedule(function () {
var result;
try {
result = func.apply(context, args);
} catch (e) {
subject.onError(e);
return;
}
subject.onNext(result);
subject.onCompleted();
});
return subject.asObservable();
};
};
/**
* Converts a callback function to an observable sequence.
*
* @param {Function} function Function with a callback as the last parameter to convert to an Observable sequence.
* @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @param {Function} [selector] A selector which takes the arguments from the callback to produce a single item to yield on next.
* @returns {Function} A function, when executed with the required parameters minus the callback, produces an Observable sequence with a single value of the arguments to the callback as an array.
*/
Observable.fromCallback = function (func, context, selector) {
return function () {
for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
return new AnonymousObservable(function (observer) {
function handler() {
var results = arguments;
if (selector) {
try {
results = selector(results);
} catch (err) {
return observer.onError(err);
}
observer.onNext(results);
} else {
if (results.length <= 1) {
observer.onNext.apply(observer, results);
} else {
observer.onNext(results);
}
}
observer.onCompleted();
}
args.push(handler);
func.apply(context, args);
}).publishLast().refCount();
};
};
/**
* Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format.
* @param {Function} func The function to call
* @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next.
* @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array.
*/
Observable.fromNodeCallback = function (func, context, selector) {
return function () {
for(var args = [], i = 0, len = arguments.length; i < len; i++) { args.push(arguments[i]); }
return new AnonymousObservable(function (observer) {
function handler(err) {
if (err) {
observer.onError(err);
return;
}
for(var results = [], i = 1, len = arguments.length; i < len; i++) { results.push(arguments[i]); }
if (selector) {
try {
results = selector(results);
} catch (e) {
return observer.onError(e);
}
observer.onNext(results);
} else {
if (results.length <= 1) {
observer.onNext.apply(observer, results);
} else {
observer.onNext(results);
}
}
observer.onCompleted();
}
args.push(handler);
func.apply(context, args);
}).publishLast().refCount();
};
};
function fixEvent(event) {
var stopPropagation = function () {
this.cancelBubble = true;
};
var preventDefault = function () {
this.bubbledKeyCode = this.keyCode;
if (this.ctrlKey) {
try {
this.keyCode = 0;
} catch (e) { }
}
this.defaultPrevented = true;
this.returnValue = false;
this.modified = true;
};
event || (event = root.event);
if (!event.target) {
event.target = event.target || event.srcElement;
if (event.type == 'mouseover') {
event.relatedTarget = event.fromElement;
}
if (event.type == 'mouseout') {
event.relatedTarget = event.toElement;
}
// Adding stopPropogation and preventDefault to IE
if (!event.stopPropagation) {
event.stopPropagation = stopPropagation;
event.preventDefault = preventDefault;
}
// Normalize key events
switch (event.type) {
case 'keypress':
var c = ('charCode' in event ? event.charCode : event.keyCode);
if (c == 10) {
c = 0;
event.keyCode = 13;
} else if (c == 13 || c == 27) {
c = 0;
} else if (c == 3) {
c = 99;
}
event.charCode = c;
event.keyChar = event.charCode ? String.fromCharCode(event.charCode) : '';
break;
}
}
return event;
}
function createListener (element, name, handler) {
// Standards compliant
if (element.addEventListener) {
element.addEventListener(name, handler, false);
return disposableCreate(function () {
element.removeEventListener(name, handler, false);
});
}
if (element.attachEvent) {
// IE Specific
var innerHandler = function (event) {
handler(fixEvent(event));
};
element.attachEvent('on' + name, innerHandler);
return disposableCreate(function () {
element.detachEvent('on' + name, innerHandler);
});
}
// Level 1 DOM Events
element['on' + name] = handler;
return disposableCreate(function () {
element['on' + name] = null;
});
}
function createEventListener (el, eventName, handler) {
var disposables = new CompositeDisposable();
// Asume NodeList
if (Object.prototype.toString.call(el) === '[object NodeList]') {
for (var i = 0, len = el.length; i < len; i++) {
disposables.add(createEventListener(el.item(i), eventName, handler));
}
} else if (el) {
disposables.add(createListener(el, eventName, handler));
}
return disposables;
}
/**
* Configuration option to determine whether to use native events only
*/
Rx.config.useNativeEvents = false;
/**
* Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList.
*
* @example
* var source = Rx.Observable.fromEvent(element, 'mouseup');
*
* @param {Object} element The DOMElement or NodeList to attach a listener.
* @param {String} eventName The event name to attach the observable sequence.
* @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next.
* @returns {Observable} An observable sequence of events from the specified element and the specified event.
*/
Observable.fromEvent = function (element, eventName, selector) {
// Node.js specific
if (element.addListener) {
return fromEventPattern(
function (h) { element.addListener(eventName, h); },
function (h) { element.removeListener(eventName, h); },
selector);
}
// Use only if non-native events are allowed
if (!Rx.config.useNativeEvents) {
// Handles jq, Angular.js, Zepto, Marionette
if (typeof element.on === 'function' && typeof element.off === 'function') {
return fromEventPattern(
function (h) { element.on(eventName, h); },
function (h) { element.off(eventName, h); },
selector);
}
if (!!root.Ember && typeof root.Ember.addListener === 'function') {
return fromEventPattern(
function (h) { Ember.addListener(element, eventName, h); },
function (h) { Ember.removeListener(element, eventName, h); },
selector);
}
}
return new AnonymousObservable(function (observer) {
return createEventListener(
element,
eventName,
function handler (e) {
var results = e;
if (selector) {
try {
results = selector(arguments);
} catch (err) {
observer.onError(err);
return
}
}
observer.onNext(results);
});
}).publish().refCount();
};
/**
* Creates an observable sequence from an event emitter via an addHandler/removeHandler pair.
* @param {Function} addHandler The function to add a handler to the emitter.
* @param {Function} [removeHandler] The optional function to remove a handler from an emitter.
* @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next.
* @returns {Observable} An observable sequence which wraps an event from an event emitter
*/
var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) {
return new AnonymousObservable(function (observer) {
function innerHandler (e) {
var result = e;
if (selector) {
try {
result = selector(arguments);
} catch (err) {
observer.onError(err);
return;
}
}
observer.onNext(result);
}
var returnValue = addHandler(innerHandler);
return disposableCreate(function () {
if (removeHandler) {
removeHandler(innerHandler, returnValue);
}
});
}).publish().refCount();
};
/**
* Invokes the asynchronous function, surfacing the result through an observable sequence.
* @param {Function} functionAsync Asynchronous function which returns a Promise to run.
* @returns {Observable} An observable sequence exposing the function's result value, or an exception.
*/
Observable.startAsync = function (functionAsync) {
var promise;
try {
promise = functionAsync();
} catch (e) {
return observableThrow(e);
}
return observableFromPromise(promise);
}
var PausableObservable = (function (__super__) {
inherits(PausableObservable, __super__);
function subscribe(observer) {
var conn = this.source.publish(),
subscription = conn.subscribe(observer),
connection = disposableEmpty;
var pausable = this.pauser.distinctUntilChanged().subscribe(function (b) {
if (b) {
connection = conn.connect();
} else {
connection.dispose();
connection = disposableEmpty;
}
});
return new CompositeDisposable(subscription, connection, pausable);
}
function PausableObservable(source, pauser) {
this.source = source;
this.controller = new Subject();
if (pauser && pauser.subscribe) {
this.pauser = this.controller.merge(pauser);
} else {
this.pauser = this.controller;
}
__super__.call(this, subscribe, source);
}
PausableObservable.prototype.pause = function () {
this.controller.onNext(false);
};
PausableObservable.prototype.resume = function () {
this.controller.onNext(true);
};
return PausableObservable;
}(Observable));
/**
* Pauses the underlying observable sequence based upon the observable sequence which yields true/false.
* @example
* var pauser = new Rx.Subject();
* var source = Rx.Observable.interval(100).pausable(pauser);
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.pausable = function (pauser) {
return new PausableObservable(this, pauser);
};
function combineLatestSource(source, subject, resultSelector) {
return new AnonymousObservable(function (o) {
var hasValue = [false, false],
hasValueAll = false,
isDone = false,
values = new Array(2),
err;
function next(x, i) {
values[i] = x
var res;
hasValue[i] = true;
if (hasValueAll || (hasValueAll = hasValue.every(identity))) {
if (err) {
o.onError(err);
return;
}
try {
res = resultSelector.apply(null, values);
} catch (ex) {
o.onError(ex);
return;
}
o.onNext(res);
}
if (isDone && values[1]) {
o.onCompleted();
}
}
return new CompositeDisposable(
source.subscribe(
function (x) {
next(x, 0);
},
function (e) {
if (values[1]) {
o.onError(e);
} else {
err = e;
}
},
function () {
isDone = true;
values[1] && o.onCompleted();
}),
subject.subscribe(
function (x) {
next(x, 1);
},
function (e) { o.onError(e); },
function () {
isDone = true;
next(true, 1);
})
);
}, source);
}
var PausableBufferedObservable = (function (__super__) {
inherits(PausableBufferedObservable, __super__);
function subscribe(o) {
var q = [], previousShouldFire;
var subscription =
combineLatestSource(
this.source,
this.pauser.distinctUntilChanged().startWith(false),
function (data, shouldFire) {
return { data: data, shouldFire: shouldFire };
})
.subscribe(
function (results) {
if (previousShouldFire !== undefined && results.shouldFire != previousShouldFire) {
previousShouldFire = results.shouldFire;
// change in shouldFire
if (results.shouldFire) {
while (q.length > 0) {
o.onNext(q.shift());
}
}
} else {
previousShouldFire = results.shouldFire;
// new data
if (results.shouldFire) {
o.onNext(results.data);
} else {
q.push(results.data);
}
}
},
function (err) {
// Empty buffer before sending error
while (q.length > 0) {
o.onNext(q.shift());
}
o.onError(err);
},
function () {
// Empty buffer before sending completion
while (q.length > 0) {
o.onNext(q.shift());
}
o.onCompleted();
}
);
return subscription;
}
function PausableBufferedObservable(source, pauser) {
this.source = source;
this.controller = new Subject();
if (pauser && pauser.subscribe) {
this.pauser = this.controller.merge(pauser);
} else {
this.pauser = this.controller;
}
__super__.call(this, subscribe, source);
}
PausableBufferedObservable.prototype.pause = function () {
this.controller.onNext(false);
};
PausableBufferedObservable.prototype.resume = function () {
this.controller.onNext(true);
};
return PausableBufferedObservable;
}(Observable));
/**
* Pauses the underlying observable sequence based upon the observable sequence which yields true/false,
* and yields the values that were buffered while paused.
* @example
* var pauser = new Rx.Subject();
* var source = Rx.Observable.interval(100).pausableBuffered(pauser);
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.pausableBuffered = function (subject) {
return new PausableBufferedObservable(this, subject);
};
var ControlledObservable = (function (__super__) {
inherits(ControlledObservable, __super__);
function subscribe (observer) {
return this.source.subscribe(observer);
}
function ControlledObservable (source, enableQueue) {
__super__.call(this, subscribe, source);
this.subject = new ControlledSubject(enableQueue);
this.source = source.multicast(this.subject).refCount();
}
ControlledObservable.prototype.request = function (numberOfItems) {
if (numberOfItems == null) { numberOfItems = -1; }
return this.subject.request(numberOfItems);
};
return ControlledObservable;
}(Observable));
var ControlledSubject = (function (__super__) {
function subscribe (observer) {
return this.subject.subscribe(observer);
}
inherits(ControlledSubject, __super__);
function ControlledSubject(enableQueue) {
enableQueue == null && (enableQueue = true);
__super__.call(this, subscribe);
this.subject = new Subject();
this.enableQueue = enableQueue;
this.queue = enableQueue ? [] : null;
this.requestedCount = 0;
this.requestedDisposable = disposableEmpty;
this.error = null;
this.hasFailed = false;
this.hasCompleted = false;
this.controlledDisposable = disposableEmpty;
}
addProperties(ControlledSubject.prototype, Observer, {
onCompleted: function () {
this.hasCompleted = true;
(!this.enableQueue || this.queue.length === 0) && this.subject.onCompleted();
},
onError: function (error) {
this.hasFailed = true;
this.error = error;
(!this.enableQueue || this.queue.length === 0) && this.subject.onError(error);
},
onNext: function (value) {
var hasRequested = false;
if (this.requestedCount === 0) {
this.enableQueue && this.queue.push(value);
} else {
(this.requestedCount !== -1 && this.requestedCount-- === 0) && this.disposeCurrentRequest();
hasRequested = true;
}
hasRequested && this.subject.onNext(value);
},
_processRequest: function (numberOfItems) {
if (this.enableQueue) {
while (this.queue.length >= numberOfItems && numberOfItems > 0) {
this.subject.onNext(this.queue.shift());
numberOfItems--;
}
return this.queue.length !== 0 ?
{ numberOfItems: numberOfItems, returnValue: true } :
{ numberOfItems: numberOfItems, returnValue: false };
}
if (this.hasFailed) {
this.subject.onError(this.error);
this.controlledDisposable.dispose();
this.controlledDisposable = disposableEmpty;
} else if (this.hasCompleted) {
this.subject.onCompleted();
this.controlledDisposable.dispose();
this.controlledDisposable = disposableEmpty;
}
return { numberOfItems: numberOfItems, returnValue: false };
},
request: function (number) {
this.disposeCurrentRequest();
var self = this, r = this._processRequest(number);
var number = r.numberOfItems;
if (!r.returnValue) {
this.requestedCount = number;
this.requestedDisposable = disposableCreate(function () {
self.requestedCount = 0;
});
return this.requestedDisposable
} else {
return disposableEmpty;
}
},
disposeCurrentRequest: function () {
this.requestedDisposable.dispose();
this.requestedDisposable = disposableEmpty;
}
});
return ControlledSubject;
}(Observable));
/**
* Attaches a controller to the observable sequence with the ability to queue.
* @example
* var source = Rx.Observable.interval(100).controlled();
* source.request(3); // Reads 3 values
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.controlled = function (enableQueue) {
if (enableQueue == null) { enableQueue = true; }
return new ControlledObservable(this, enableQueue);
};
var StopAndWaitObservable = (function (__super__) {
function subscribe (observer) {
this.subscription = this.source.subscribe(new StopAndWaitObserver(observer, this, this.subscription));
var self = this;
timeoutScheduler.schedule(function () { self.source.request(1); });
return this.subscription;
}
inherits(StopAndWaitObservable, __super__);
function StopAndWaitObservable (source) {
__super__.call(this, subscribe, source);
this.source = source;
}
var StopAndWaitObserver = (function (__sub__) {
inherits(StopAndWaitObserver, __sub__);
function StopAndWaitObserver (observer, observable, cancel) {
__sub__.call(this);
this.observer = observer;
this.observable = observable;
this.cancel = cancel;
}
var stopAndWaitObserverProto = StopAndWaitObserver.prototype;
stopAndWaitObserverProto.completed = function () {
this.observer.onCompleted();
this.dispose();
};
stopAndWaitObserverProto.error = function (error) {
this.observer.onError(error);
this.dispose();
}
stopAndWaitObserverProto.next = function (value) {
this.observer.onNext(value);
var self = this;
timeoutScheduler.schedule(function () {
self.observable.source.request(1);
});
};
stopAndWaitObserverProto.dispose = function () {
this.observer = null;
if (this.cancel) {
this.cancel.dispose();
this.cancel = null;
}
__sub__.prototype.dispose.call(this);
};
return StopAndWaitObserver;
}(AbstractObserver));
return StopAndWaitObservable;
}(Observable));
/**
* Attaches a stop and wait observable to the current observable.
* @returns {Observable} A stop and wait observable.
*/
ControlledObservable.prototype.stopAndWait = function () {
return new StopAndWaitObservable(this);
};
var WindowedObservable = (function (__super__) {
function subscribe (observer) {
this.subscription = this.source.subscribe(new WindowedObserver(observer, this, this.subscription));
var self = this;
timeoutScheduler.schedule(function () {
self.source.request(self.windowSize);
});
return this.subscription;
}
inherits(WindowedObservable, __super__);
function WindowedObservable(source, windowSize) {
__super__.call(this, subscribe, source);
this.source = source;
this.windowSize = windowSize;
}
var WindowedObserver = (function (__sub__) {
inherits(WindowedObserver, __sub__);
function WindowedObserver(observer, observable, cancel) {
this.observer = observer;
this.observable = observable;
this.cancel = cancel;
this.received = 0;
}
var windowedObserverPrototype = WindowedObserver.prototype;
windowedObserverPrototype.completed = function () {
this.observer.onCompleted();
this.dispose();
};
windowedObserverPrototype.error = function (error) {
this.observer.onError(error);
this.dispose();
};
windowedObserverPrototype.next = function (value) {
this.observer.onNext(value);
this.received = ++this.received % this.observable.windowSize;
if (this.received === 0) {
var self = this;
timeoutScheduler.schedule(function () {
self.observable.source.request(self.observable.windowSize);
});
}
};
windowedObserverPrototype.dispose = function () {
this.observer = null;
if (this.cancel) {
this.cancel.dispose();
this.cancel = null;
}
__sub__.prototype.dispose.call(this);
};
return WindowedObserver;
}(AbstractObserver));
return WindowedObservable;
}(Observable));
/**
* Creates a sliding windowed observable based upon the window size.
* @param {Number} windowSize The number of items in the window
* @returns {Observable} A windowed observable based upon the window size.
*/
ControlledObservable.prototype.windowed = function (windowSize) {
return new WindowedObservable(this, windowSize);
};
/**
* Multicasts the source sequence notifications through an instantiated subject into all uses of the sequence within a selector function. Each
* subscription to the resulting sequence causes a separate multicast invocation, exposing the sequence resulting from the selector function's
* invocation. For specializations with fixed subject types, see Publish, PublishLast, and Replay.
*
* @example
* 1 - res = source.multicast(observable);
* 2 - res = source.multicast(function () { return new Subject(); }, function (x) { return x; });
*
* @param {Function|Subject} subjectOrSubjectSelector
* Factory function to create an intermediate subject through which the source sequence's elements will be multicast to the selector function.
* Or:
* Subject to push source elements into.
*
* @param {Function} [selector] Optional selector function which can use the multicasted source sequence subject to the policies enforced by the created subject. Specified only if <paramref name="subjectOrSubjectSelector" is a factory function.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.multicast = function (subjectOrSubjectSelector, selector) {
var source = this;
return typeof subjectOrSubjectSelector === 'function' ?
new AnonymousObservable(function (observer) {
var connectable = source.multicast(subjectOrSubjectSelector());
return new CompositeDisposable(selector(connectable).subscribe(observer), connectable.connect());
}, source) :
new ConnectableObservable(source, subjectOrSubjectSelector);
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence.
* This operator is a specialization of Multicast using a regular Subject.
*
* @example
* var resres = source.publish();
* var res = source.publish(function (x) { return x; });
*
* @param {Function} [selector] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all notifications of the source from the time of the subscription on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publish = function (selector) {
return selector && isFunction(selector) ?
this.multicast(function () { return new Subject(); }, selector) :
this.multicast(new Subject());
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence.
* This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.share = function () {
return this.publish().refCount();
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification.
* This operator is a specialization of Multicast using a AsyncSubject.
*
* @example
* var res = source.publishLast();
* var res = source.publishLast(function (x) { return x; });
*
* @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publishLast = function (selector) {
return selector && isFunction(selector) ?
this.multicast(function () { return new AsyncSubject(); }, selector) :
this.multicast(new AsyncSubject());
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue.
* This operator is a specialization of Multicast using a BehaviorSubject.
*
* @example
* var res = source.publishValue(42);
* var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42);
*
* @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on.
* @param {Mixed} initialValue Initial value received by observers upon subscription.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publishValue = function (initialValueOrSelector, initialValue) {
return arguments.length === 2 ?
this.multicast(function () {
return new BehaviorSubject(initialValue);
}, initialValueOrSelector) :
this.multicast(new BehaviorSubject(initialValueOrSelector));
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue.
* This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
* @param {Mixed} initialValue Initial value received by observers upon subscription.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.shareValue = function (initialValue) {
return this.publishValue(initialValue).refCount();
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer.
* This operator is a specialization of Multicast using a ReplaySubject.
*
* @example
* var res = source.replay(null, 3);
* var res = source.replay(null, 3, 500);
* var res = source.replay(null, 3, 500, scheduler);
* var res = source.replay(function (x) { return x.take(6).repeat(); }, 3, 500, scheduler);
*
* @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive all the notifications of the source subject to the specified replay buffer trimming policy.
* @param bufferSize [Optional] Maximum element count of the replay buffer.
* @param window [Optional] Maximum time length of the replay buffer.
* @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.replay = function (selector, bufferSize, window, scheduler) {
return selector && isFunction(selector) ?
this.multicast(function () { return new ReplaySubject(bufferSize, window, scheduler); }, selector) :
this.multicast(new ReplaySubject(bufferSize, window, scheduler));
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer.
* This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
*
* @example
* var res = source.shareReplay(3);
* var res = source.shareReplay(3, 500);
* var res = source.shareReplay(3, 500, scheduler);
*
* @param bufferSize [Optional] Maximum element count of the replay buffer.
* @param window [Optional] Maximum time length of the replay buffer.
* @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.shareReplay = function (bufferSize, window, scheduler) {
return this.replay(null, bufferSize, window, scheduler).refCount();
};
var InnerSubscription = function (subject, observer) {
this.subject = subject;
this.observer = observer;
};
InnerSubscription.prototype.dispose = function () {
if (!this.subject.isDisposed && this.observer !== null) {
var idx = this.subject.observers.indexOf(this.observer);
this.subject.observers.splice(idx, 1);
this.observer = null;
}
};
/**
* Represents a value that changes over time.
* Observers can subscribe to the subject to receive the last (or initial) value and all subsequent notifications.
*/
var BehaviorSubject = Rx.BehaviorSubject = (function (__super__) {
function subscribe(observer) {
checkDisposed(this);
if (!this.isStopped) {
this.observers.push(observer);
observer.onNext(this.value);
return new InnerSubscription(this, observer);
}
if (this.hasError) {
observer.onError(this.error);
} else {
observer.onCompleted();
}
return disposableEmpty;
}
inherits(BehaviorSubject, __super__);
/**
* Initializes a new instance of the BehaviorSubject class which creates a subject that caches its last value and starts with the specified value.
* @param {Mixed} value Initial value sent to observers when no other value has been received by the subject yet.
*/
function BehaviorSubject(value) {
__super__.call(this, subscribe);
this.value = value,
this.observers = [],
this.isDisposed = false,
this.isStopped = false,
this.hasError = false;
}
addProperties(BehaviorSubject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () { return this.observers.length > 0; },
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed(this);
if (this.isStopped) { return; }
this.isStopped = true;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers.length = 0;
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (error) {
checkDisposed(this);
if (this.isStopped) { return; }
this.isStopped = true;
this.hasError = true;
this.error = error;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers.length = 0;
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed(this);
if (this.isStopped) { return; }
this.value = value;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onNext(value);
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
this.value = null;
this.exception = null;
}
});
return BehaviorSubject;
}(Observable));
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies.
*/
var ReplaySubject = Rx.ReplaySubject = (function (__super__) {
function createRemovableDisposable(subject, observer) {
return disposableCreate(function () {
observer.dispose();
!subject.isDisposed && subject.observers.splice(subject.observers.indexOf(observer), 1);
});
}
function subscribe(observer) {
var so = new ScheduledObserver(this.scheduler, observer),
subscription = createRemovableDisposable(this, so);
checkDisposed(this);
this._trim(this.scheduler.now());
this.observers.push(so);
for (var i = 0, len = this.q.length; i < len; i++) {
so.onNext(this.q[i].value);
}
if (this.hasError) {
so.onError(this.error);
} else if (this.isStopped) {
so.onCompleted();
}
so.ensureActive();
return subscription;
}
inherits(ReplaySubject, __super__);
/**
* Initializes a new instance of the ReplaySubject class with the specified buffer size, window size and scheduler.
* @param {Number} [bufferSize] Maximum element count of the replay buffer.
* @param {Number} [windowSize] Maximum time length of the replay buffer.
* @param {Scheduler} [scheduler] Scheduler the observers are invoked on.
*/
function ReplaySubject(bufferSize, windowSize, scheduler) {
this.bufferSize = bufferSize == null ? Number.MAX_VALUE : bufferSize;
this.windowSize = windowSize == null ? Number.MAX_VALUE : windowSize;
this.scheduler = scheduler || currentThreadScheduler;
this.q = [];
this.observers = [];
this.isStopped = false;
this.isDisposed = false;
this.hasError = false;
this.error = null;
__super__.call(this, subscribe);
}
addProperties(ReplaySubject.prototype, Observer.prototype, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
return this.observers.length > 0;
},
_trim: function (now) {
while (this.q.length > this.bufferSize) {
this.q.shift();
}
while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) {
this.q.shift();
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed(this);
if (this.isStopped) { return; }
var now = this.scheduler.now();
this.q.push({ interval: now, value: value });
this._trim(now);
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
var observer = os[i];
observer.onNext(value);
observer.ensureActive();
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (error) {
checkDisposed(this);
if (this.isStopped) { return; }
this.isStopped = true;
this.error = error;
this.hasError = true;
var now = this.scheduler.now();
this._trim(now);
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
var observer = os[i];
observer.onError(error);
observer.ensureActive();
}
this.observers.length = 0;
},
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed(this);
if (this.isStopped) { return; }
this.isStopped = true;
var now = this.scheduler.now();
this._trim(now);
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
var observer = os[i];
observer.onCompleted();
observer.ensureActive();
}
this.observers.length = 0;
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
}
});
return ReplaySubject;
}(Observable));
var ConnectableObservable = Rx.ConnectableObservable = (function (__super__) {
inherits(ConnectableObservable, __super__);
function ConnectableObservable(source, subject) {
var hasSubscription = false,
subscription,
sourceObservable = source.asObservable();
this.connect = function () {
if (!hasSubscription) {
hasSubscription = true;
subscription = new CompositeDisposable(sourceObservable.subscribe(subject), disposableCreate(function () {
hasSubscription = false;
}));
}
return subscription;
};
__super__.call(this, function (o) { return subject.subscribe(o); });
}
ConnectableObservable.prototype.refCount = function () {
var connectableSubscription, count = 0, source = this;
return new AnonymousObservable(function (observer) {
var shouldConnect = ++count === 1,
subscription = source.subscribe(observer);
shouldConnect && (connectableSubscription = source.connect());
return function () {
subscription.dispose();
--count === 0 && connectableSubscription.dispose();
};
});
};
return ConnectableObservable;
}(Observable));
var Dictionary = (function () {
var primes = [1, 3, 7, 13, 31, 61, 127, 251, 509, 1021, 2039, 4093, 8191, 16381, 32749, 65521, 131071, 262139, 524287, 1048573, 2097143, 4194301, 8388593, 16777213, 33554393, 67108859, 134217689, 268435399, 536870909, 1073741789, 2147483647],
noSuchkey = "no such key",
duplicatekey = "duplicate key";
function isPrime(candidate) {
if ((candidate & 1) === 0) { return candidate === 2; }
var num1 = Math.sqrt(candidate),
num2 = 3;
while (num2 <= num1) {
if (candidate % num2 === 0) { return false; }
num2 += 2;
}
return true;
}
function getPrime(min) {
var index, num, candidate;
for (index = 0; index < primes.length; ++index) {
num = primes[index];
if (num >= min) { return num; }
}
candidate = min | 1;
while (candidate < primes[primes.length - 1]) {
if (isPrime(candidate)) { return candidate; }
candidate += 2;
}
return min;
}
function stringHashFn(str) {
var hash = 757602046;
if (!str.length) { return hash; }
for (var i = 0, len = str.length; i < len; i++) {
var character = str.charCodeAt(i);
hash = ((hash << 5) - hash) + character;
hash = hash & hash;
}
return hash;
}
function numberHashFn(key) {
var c2 = 0x27d4eb2d;
key = (key ^ 61) ^ (key >>> 16);
key = key + (key << 3);
key = key ^ (key >>> 4);
key = key * c2;
key = key ^ (key >>> 15);
return key;
}
var getHashCode = (function () {
var uniqueIdCounter = 0;
return function (obj) {
if (obj == null) { throw new Error(noSuchkey); }
// Check for built-ins before tacking on our own for any object
if (typeof obj === 'string') { return stringHashFn(obj); }
if (typeof obj === 'number') { return numberHashFn(obj); }
if (typeof obj === 'boolean') { return obj === true ? 1 : 0; }
if (obj instanceof Date) { return numberHashFn(obj.valueOf()); }
if (obj instanceof RegExp) { return stringHashFn(obj.toString()); }
if (typeof obj.valueOf === 'function') {
// Hack check for valueOf
var valueOf = obj.valueOf();
if (typeof valueOf === 'number') { return numberHashFn(valueOf); }
if (typeof valueOf === 'string') { return stringHashFn(valueOf); }
}
if (obj.hashCode) { return obj.hashCode(); }
var id = 17 * uniqueIdCounter++;
obj.hashCode = function () { return id; };
return id;
};
}());
function newEntry() {
return { key: null, value: null, next: 0, hashCode: 0 };
}
function Dictionary(capacity, comparer) {
if (capacity < 0) { throw new 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) {
this._insert(key, value, true);
};
dictionaryProto._insert = function (key, value, add) {
if (!this.buckets) { this._initialize(0); }
var index3,
num = getHashCode(key) & 2147483647,
index1 = num % this.buckets.length;
for (var index2 = this.buckets[index1]; index2 >= 0; index2 = this.entries[index2].next) {
if (this.entries[index2].hashCode === num && this.comparer(this.entries[index2].key, key)) {
if (add) { throw new Error(duplicatekey); }
this.entries[index2].value = value;
return;
}
}
if (this.freeCount > 0) {
index3 = this.freeList;
this.freeList = this.entries[index3].next;
--this.freeCount;
} else {
if (this.size === this.entries.length) {
this._resize();
index1 = num % this.buckets.length;
}
index3 = this.size;
++this.size;
}
this.entries[index3].hashCode = num;
this.entries[index3].next = this.buckets[index1];
this.entries[index3].key = key;
this.entries[index3].value = value;
this.buckets[index1] = index3;
};
dictionaryProto._resize = function () {
var prime = getPrime(this.size * 2),
numArray = new Array(prime);
for (index = 0; index < numArray.length; ++index) { numArray[index] = -1; }
var entryArray = new Array(prime);
for (index = 0; index < this.size; ++index) { entryArray[index] = this.entries[index]; }
for (var index = this.size; index < prime; ++index) { entryArray[index] = newEntry(); }
for (var index1 = 0; index1 < this.size; ++index1) {
var index2 = entryArray[index1].hashCode % prime;
entryArray[index1].next = numArray[index2];
numArray[index2] = index1;
}
this.buckets = numArray;
this.entries = entryArray;
};
dictionaryProto.remove = function (key) {
if (this.buckets) {
var num = getHashCode(key) & 2147483647,
index1 = num % this.buckets.length,
index2 = -1;
for (var index3 = this.buckets[index1]; index3 >= 0; index3 = this.entries[index3].next) {
if (this.entries[index3].hashCode === num && this.comparer(this.entries[index3].key, key)) {
if (index2 < 0) {
this.buckets[index1] = this.entries[index3].next;
} else {
this.entries[index2].next = this.entries[index3].next;
}
this.entries[index3].hashCode = -1;
this.entries[index3].next = this.freeList;
this.entries[index3].key = null;
this.entries[index3].value = null;
this.freeList = index3;
++this.freeCount;
return true;
} else {
index2 = index3;
}
}
}
return false;
};
dictionaryProto.clear = function () {
var index, len;
if (this.size <= 0) { return; }
for (index = 0, len = this.buckets.length; index < len; ++index) {
this.buckets[index] = -1;
}
for (index = 0; index < this.size; ++index) {
this.entries[index] = newEntry();
}
this.freeList = -1;
this.size = 0;
};
dictionaryProto._findEntry = function (key) {
if (this.buckets) {
var num = getHashCode(key) & 2147483647;
for (var index = this.buckets[num % this.buckets.length]; index >= 0; index = this.entries[index].next) {
if (this.entries[index].hashCode === num && this.comparer(this.entries[index].key, key)) {
return index;
}
}
}
return -1;
};
dictionaryProto.count = function () {
return this.size - this.freeCount;
};
dictionaryProto.tryGetValue = function (key) {
var entry = this._findEntry(key);
return entry >= 0 ?
this.entries[entry].value :
undefined;
};
dictionaryProto.getValues = function () {
var index = 0, results = [];
if (this.entries) {
for (var index1 = 0; index1 < this.size; index1++) {
if (this.entries[index1].hashCode >= 0) {
results[index++] = this.entries[index1].value;
}
}
}
return results;
};
dictionaryProto.get = function (key) {
var entry = this._findEntry(key);
if (entry >= 0) { return this.entries[entry].value; }
throw new Error(noSuchkey);
};
dictionaryProto.set = function (key, value) {
this._insert(key, value, false);
};
dictionaryProto.containskey = function (key) {
return this._findEntry(key) >= 0;
};
return Dictionary;
}());
/**
* Correlates the elements of two sequences based on overlapping durations.
*
* @param {Observable} right The right observable sequence to join elements for.
* @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap.
* @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap.
* @param {Function} resultSelector A function invoked to compute a result element for any two overlapping elements of the left and right observable sequences. The parameters passed to the function correspond with the elements from the left and right source sequences for which overlap occurs.
* @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration.
*/
observableProto.join = function (right, leftDurationSelector, rightDurationSelector, resultSelector) {
var left = this;
return new AnonymousObservable(function (observer) {
var group = new CompositeDisposable();
var leftDone = false, rightDone = false;
var leftId = 0, rightId = 0;
var leftMap = new Dictionary(), rightMap = new Dictionary();
group.add(left.subscribe(
function (value) {
var id = leftId++;
var md = new SingleAssignmentDisposable();
leftMap.add(id, value);
group.add(md);
var expire = function () {
leftMap.remove(id) && leftMap.count() === 0 && leftDone && observer.onCompleted();
group.remove(md);
};
var duration;
try {
duration = leftDurationSelector(value);
} catch (e) {
observer.onError(e);
return;
}
md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire));
rightMap.getValues().forEach(function (v) {
var result;
try {
result = resultSelector(value, v);
} catch (exn) {
observer.onError(exn);
return;
}
observer.onNext(result);
});
},
observer.onError.bind(observer),
function () {
leftDone = true;
(rightDone || leftMap.count() === 0) && observer.onCompleted();
})
);
group.add(right.subscribe(
function (value) {
var id = rightId++;
var md = new SingleAssignmentDisposable();
rightMap.add(id, value);
group.add(md);
var expire = function () {
rightMap.remove(id) && rightMap.count() === 0 && rightDone && observer.onCompleted();
group.remove(md);
};
var duration;
try {
duration = rightDurationSelector(value);
} catch (e) {
observer.onError(e);
return;
}
md.setDisposable(duration.take(1).subscribe(noop, observer.onError.bind(observer), expire));
leftMap.getValues().forEach(function (v) {
var result;
try {
result = resultSelector(v, value);
} catch (exn) {
observer.onError(exn);
return;
}
observer.onNext(result);
});
},
observer.onError.bind(observer),
function () {
rightDone = true;
(leftDone || rightMap.count() === 0) && observer.onCompleted();
})
);
return group;
}, left);
};
/**
* Correlates the elements of two sequences based on overlapping durations, and groups the results.
*
* @param {Observable} right The right observable sequence to join elements for.
* @param {Function} leftDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the left observable sequence, used to determine overlap.
* @param {Function} rightDurationSelector A function to select the duration (expressed as an observable sequence) of each element of the right observable sequence, used to determine overlap.
* @param {Function} resultSelector A function invoked to compute a result element for any element of the left sequence with overlapping elements from the right observable sequence. The first parameter passed to the function is an element of the left sequence. The second parameter passed to the function is an observable sequence with elements from the right sequence that overlap with the left sequence's element.
* @returns {Observable} An observable sequence that contains result elements computed from source elements that have an overlapping duration.
*/
observableProto.groupJoin = function (right, leftDurationSelector, rightDurationSelector, resultSelector) {
var left = this;
return new AnonymousObservable(function (observer) {
var group = new CompositeDisposable();
var r = new RefCountDisposable(group);
var leftMap = new Dictionary(), rightMap = new Dictionary();
var leftId = 0, rightId = 0;
function handleError(e) { return function (v) { v.onError(e); }; };
group.add(left.subscribe(
function (value) {
var s = new Subject();
var id = leftId++;
leftMap.add(id, s);
var result;
try {
result = resultSelector(value, addRef(s, r));
} catch (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
observer.onNext(result);
rightMap.getValues().forEach(function (v) { s.onNext(v); });
var md = new SingleAssignmentDisposable();
group.add(md);
var expire = function () {
leftMap.remove(id) && s.onCompleted();
group.remove(md);
};
var duration;
try {
duration = leftDurationSelector(value);
} catch (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
md.setDisposable(duration.take(1).subscribe(
noop,
function (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
},
expire)
);
},
function (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
},
observer.onCompleted.bind(observer))
);
group.add(right.subscribe(
function (value) {
var id = rightId++;
rightMap.add(id, value);
var md = new SingleAssignmentDisposable();
group.add(md);
var expire = function () {
rightMap.remove(id);
group.remove(md);
};
var duration;
try {
duration = rightDurationSelector(value);
} catch (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
return;
}
md.setDisposable(duration.take(1).subscribe(
noop,
function (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
},
expire)
);
leftMap.getValues().forEach(function (v) { v.onNext(value); });
},
function (e) {
leftMap.getValues().forEach(handleError(e));
observer.onError(e);
})
);
return r;
}, left);
};
/**
* Projects each element of an observable sequence into zero or more buffers.
*
* @param {Mixed} bufferOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows).
* @param {Function} [bufferClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.buffer = function (bufferOpeningsOrClosingSelector, bufferClosingSelector) {
return this.window.apply(this, arguments).selectMany(function (x) { return x.toArray(); });
};
/**
* Projects each element of an observable sequence into zero or more windows.
*
* @param {Mixed} windowOpeningsOrClosingSelector Observable sequence whose elements denote the creation of new windows, or, a function invoked to define the boundaries of the produced windows (a new window is started when the previous one is closed, resulting in non-overlapping windows).
* @param {Function} [windowClosingSelector] A function invoked to define the closing of each produced window. If a closing selector function is specified for the first parameter, this parameter is ignored.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.window = function (windowOpeningsOrClosingSelector, windowClosingSelector) {
if (arguments.length === 1 && typeof arguments[0] !== 'function') {
return observableWindowWithBoundaries.call(this, windowOpeningsOrClosingSelector);
}
return typeof windowOpeningsOrClosingSelector === 'function' ?
observableWindowWithClosingSelector.call(this, windowOpeningsOrClosingSelector) :
observableWindowWithOpenings.call(this, windowOpeningsOrClosingSelector, windowClosingSelector);
};
function observableWindowWithOpenings(windowOpenings, windowClosingSelector) {
return windowOpenings.groupJoin(this, windowClosingSelector, observableEmpty, function (_, win) {
return win;
});
}
function observableWindowWithBoundaries(windowBoundaries) {
var source = this;
return new AnonymousObservable(function (observer) {
var win = new Subject(),
d = new CompositeDisposable(),
r = new RefCountDisposable(d);
observer.onNext(addRef(win, r));
d.add(source.subscribe(function (x) {
win.onNext(x);
}, function (err) {
win.onError(err);
observer.onError(err);
}, function () {
win.onCompleted();
observer.onCompleted();
}));
isPromise(windowBoundaries) && (windowBoundaries = observableFromPromise(windowBoundaries));
d.add(windowBoundaries.subscribe(function (w) {
win.onCompleted();
win = new Subject();
observer.onNext(addRef(win, r));
}, function (err) {
win.onError(err);
observer.onError(err);
}, function () {
win.onCompleted();
observer.onCompleted();
}));
return r;
}, source);
}
function observableWindowWithClosingSelector(windowClosingSelector) {
var source = this;
return new AnonymousObservable(function (observer) {
var m = new SerialDisposable(),
d = new CompositeDisposable(m),
r = new RefCountDisposable(d),
win = new Subject();
observer.onNext(addRef(win, r));
d.add(source.subscribe(function (x) {
win.onNext(x);
}, function (err) {
win.onError(err);
observer.onError(err);
}, function () {
win.onCompleted();
observer.onCompleted();
}));
function createWindowClose () {
var windowClose;
try {
windowClose = windowClosingSelector();
} catch (e) {
observer.onError(e);
return;
}
isPromise(windowClose) && (windowClose = observableFromPromise(windowClose));
var m1 = new SingleAssignmentDisposable();
m.setDisposable(m1);
m1.setDisposable(windowClose.take(1).subscribe(noop, function (err) {
win.onError(err);
observer.onError(err);
}, function () {
win.onCompleted();
win = new Subject();
observer.onNext(addRef(win, r));
createWindowClose();
}));
}
createWindowClose();
return r;
}, source);
}
/**
* Returns a new observable that triggers on the second and subsequent triggerings of the input observable.
* The Nth triggering of the input observable passes the arguments from the N-1th and Nth triggering as a pair.
* The argument passed to the N-1th triggering is held in hidden internal state until the Nth triggering occurs.
* @returns {Observable} An observable that triggers on successive pairs of observations from the input observable as an array.
*/
observableProto.pairwise = function () {
var source = this;
return new AnonymousObservable(function (observer) {
var previous, hasPrevious = false;
return source.subscribe(
function (x) {
if (hasPrevious) {
observer.onNext([previous, x]);
} else {
hasPrevious = true;
}
previous = x;
},
observer.onError.bind(observer),
observer.onCompleted.bind(observer));
}, source);
};
/**
* Returns two observables which partition the observations of the source by the given function.
* The first will trigger observations for those values for which the predicate returns true.
* The second will trigger observations for those values where the predicate returns false.
* The predicate is executed once for each subscribed observer.
* Both also propagate all error observations arising from the source and each completes
* when the source completes.
* @param {Function} predicate
* The function to determine which output Observable will trigger a particular observation.
* @returns {Array}
* An array of observables. The first triggers when the predicate returns true,
* and the second triggers when the predicate returns false.
*/
observableProto.partition = function(predicate, thisArg) {
return [
this.filter(predicate, thisArg),
this.filter(function (x, i, o) { return !predicate.call(thisArg, x, i, o); })
];
};
function enumerableWhile(condition, source) {
return new Enumerable(function () {
return new Enumerator(function () {
return condition() ?
{ done: false, value: source } :
{ done: true, value: undefined };
});
});
}
/**
* Returns an observable sequence that is the result of invoking the selector on the source sequence, without sharing subscriptions.
* This operator allows for a fluent style of writing queries that use the same sequence multiple times.
*
* @param {Function} selector Selector function which can use the source sequence as many times as needed, without sharing subscriptions to the source sequence.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.letBind = observableProto['let'] = function (func) {
return func(this);
};
/**
* Determines whether an observable collection contains values. There is an alias for this method called 'ifThen' for browsers <IE9
*
* @example
* 1 - res = Rx.Observable.if(condition, obs1);
* 2 - res = Rx.Observable.if(condition, obs1, obs2);
* 3 - res = Rx.Observable.if(condition, obs1, scheduler);
* @param {Function} condition The condition which determines if the thenSource or elseSource will be run.
* @param {Observable} thenSource The observable sequence or Promise that will be run if the condition function returns true.
* @param {Observable} [elseSource] The observable sequence or Promise that will be run if the condition function returns false. If this is not provided, it defaults to Rx.Observabe.Empty with the specified scheduler.
* @returns {Observable} An observable sequence which is either the thenSource or elseSource.
*/
Observable['if'] = Observable.ifThen = function (condition, thenSource, elseSourceOrScheduler) {
return observableDefer(function () {
elseSourceOrScheduler || (elseSourceOrScheduler = observableEmpty());
isPromise(thenSource) && (thenSource = observableFromPromise(thenSource));
isPromise(elseSourceOrScheduler) && (elseSourceOrScheduler = observableFromPromise(elseSourceOrScheduler));
// Assume a scheduler for empty only
typeof elseSourceOrScheduler.now === 'function' && (elseSourceOrScheduler = observableEmpty(elseSourceOrScheduler));
return condition() ? thenSource : elseSourceOrScheduler;
});
};
/**
* Concatenates the observable sequences obtained by running the specified result selector for each element in source.
* There is an alias for this method called 'forIn' for browsers <IE9
* @param {Array} sources An array of values to turn into an observable sequence.
* @param {Function} resultSelector A function to apply to each item in the sources array to turn it into an observable sequence.
* @returns {Observable} An observable sequence from the concatenated observable sequences.
*/
Observable['for'] = Observable.forIn = function (sources, resultSelector, thisArg) {
return enumerableOf(sources, resultSelector, thisArg).concat();
};
/**
* Repeats source as long as condition holds emulating a while loop.
* There is an alias for this method called 'whileDo' for browsers <IE9
*
* @param {Function} condition The condition which determines if the source will be repeated.
* @param {Observable} source The observable sequence that will be run if the condition function returns true.
* @returns {Observable} An observable sequence which is repeated as long as the condition holds.
*/
var observableWhileDo = Observable['while'] = Observable.whileDo = function (condition, source) {
isPromise(source) && (source = observableFromPromise(source));
return enumerableWhile(condition, source).concat();
};
/**
* Repeats source as long as condition holds emulating a do while loop.
*
* @param {Function} condition The condition which determines if the source will be repeated.
* @param {Observable} source The observable sequence that will be run if the condition function returns true.
* @returns {Observable} An observable sequence which is repeated as long as the condition holds.
*/
observableProto.doWhile = function (condition) {
return observableConcat([this, observableWhileDo(condition, this)]);
};
/**
* Uses selector to determine which source in sources to use.
* There is an alias 'switchCase' for browsers <IE9.
*
* @example
* 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 });
* 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, obs0);
* 1 - res = Rx.Observable.case(selector, { '1': obs1, '2': obs2 }, scheduler);
*
* @param {Function} selector The function which extracts the value for to test in a case statement.
* @param {Array} sources A object which has keys which correspond to the case statement labels.
* @param {Observable} [elseSource] The observable sequence or Promise that will be run if the sources are not matched. If this is not provided, it defaults to Rx.Observabe.empty with the specified scheduler.
*
* @returns {Observable} An observable sequence which is determined by a case statement.
*/
Observable['case'] = Observable.switchCase = function (selector, sources, defaultSourceOrScheduler) {
return observableDefer(function () {
isPromise(defaultSourceOrScheduler) && (defaultSourceOrScheduler = observableFromPromise(defaultSourceOrScheduler));
defaultSourceOrScheduler || (defaultSourceOrScheduler = observableEmpty());
typeof defaultSourceOrScheduler.now === 'function' && (defaultSourceOrScheduler = observableEmpty(defaultSourceOrScheduler));
var result = sources[selector()];
isPromise(result) && (result = observableFromPromise(result));
return result || defaultSourceOrScheduler;
});
};
/**
* Expands an observable sequence by recursively invoking selector.
*
* @param {Function} selector Selector function to invoke for each produced element, resulting in another sequence to which the selector will be invoked recursively again.
* @param {Scheduler} [scheduler] Scheduler on which to perform the expansion. If not provided, this defaults to the current thread scheduler.
* @returns {Observable} An observable sequence containing all the elements produced by the recursive expansion.
*/
observableProto.expand = function (selector, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
var source = this;
return new AnonymousObservable(function (observer) {
var q = [],
m = new SerialDisposable(),
d = new CompositeDisposable(m),
activeCount = 0,
isAcquired = false;
var ensureActive = function () {
var isOwner = false;
if (q.length > 0) {
isOwner = !isAcquired;
isAcquired = true;
}
if (isOwner) {
m.setDisposable(scheduler.scheduleRecursive(function (self) {
var work;
if (q.length > 0) {
work = q.shift();
} else {
isAcquired = false;
return;
}
var m1 = new SingleAssignmentDisposable();
d.add(m1);
m1.setDisposable(work.subscribe(function (x) {
observer.onNext(x);
var result = null;
try {
result = selector(x);
} catch (e) {
observer.onError(e);
}
q.push(result);
activeCount++;
ensureActive();
}, observer.onError.bind(observer), function () {
d.remove(m1);
activeCount--;
if (activeCount === 0) {
observer.onCompleted();
}
}));
self();
}));
}
};
q.push(source);
activeCount++;
ensureActive();
return d;
}, this);
};
/**
* Runs all observable sequences in parallel and collect their last elements.
*
* @example
* 1 - res = Rx.Observable.forkJoin([obs1, obs2]);
* 1 - res = Rx.Observable.forkJoin(obs1, obs2, ...);
* @returns {Observable} An observable sequence with an array collecting the last elements of all the input sequences.
*/
Observable.forkJoin = function () {
var allSources = [];
if (Array.isArray(arguments[0])) {
allSources = arguments[0];
} else {
for(var i = 0, len = arguments.length; i < len; i++) { allSources.push(arguments[i]); }
}
return new AnonymousObservable(function (subscriber) {
var count = allSources.length;
if (count === 0) {
subscriber.onCompleted();
return disposableEmpty;
}
var group = new CompositeDisposable(),
finished = false,
hasResults = new Array(count),
hasCompleted = new Array(count),
results = new Array(count);
for (var idx = 0; idx < count; idx++) {
(function (i) {
var source = allSources[i];
isPromise(source) && (source = observableFromPromise(source));
group.add(
source.subscribe(
function (value) {
if (!finished) {
hasResults[i] = true;
results[i] = value;
}
},
function (e) {
finished = true;
subscriber.onError(e);
group.dispose();
},
function () {
if (!finished) {
if (!hasResults[i]) {
subscriber.onCompleted();
return;
}
hasCompleted[i] = true;
for (var ix = 0; ix < count; ix++) {
if (!hasCompleted[ix]) { return; }
}
finished = true;
subscriber.onNext(results);
subscriber.onCompleted();
}
}));
})(idx);
}
return group;
});
};
/**
* Runs two observable sequences in parallel and combines their last elemenets.
*
* @param {Observable} second Second observable sequence.
* @param {Function} resultSelector Result selector function to invoke with the last elements of both sequences.
* @returns {Observable} An observable sequence with the result of calling the selector function with the last elements of both input sequences.
*/
observableProto.forkJoin = function (second, resultSelector) {
var first = this;
return new AnonymousObservable(function (observer) {
var leftStopped = false, rightStopped = false,
hasLeft = false, hasRight = false,
lastLeft, lastRight,
leftSubscription = new SingleAssignmentDisposable(), rightSubscription = new SingleAssignmentDisposable();
isPromise(second) && (second = observableFromPromise(second));
leftSubscription.setDisposable(
first.subscribe(function (left) {
hasLeft = true;
lastLeft = left;
}, function (err) {
rightSubscription.dispose();
observer.onError(err);
}, function () {
leftStopped = true;
if (rightStopped) {
if (!hasLeft) {
observer.onCompleted();
} else if (!hasRight) {
observer.onCompleted();
} else {
var result;
try {
result = resultSelector(lastLeft, lastRight);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
observer.onCompleted();
}
}
})
);
rightSubscription.setDisposable(
second.subscribe(function (right) {
hasRight = true;
lastRight = right;
}, function (err) {
leftSubscription.dispose();
observer.onError(err);
}, function () {
rightStopped = true;
if (leftStopped) {
if (!hasLeft) {
observer.onCompleted();
} else if (!hasRight) {
observer.onCompleted();
} else {
var result;
try {
result = resultSelector(lastLeft, lastRight);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
observer.onCompleted();
}
}
})
);
return new CompositeDisposable(leftSubscription, rightSubscription);
}, first);
};
/**
* Comonadic bind operator.
* @param {Function} selector A transform function to apply to each element.
* @param {Object} scheduler Scheduler used to execute the operation. If not specified, defaults to the ImmediateScheduler.
* @returns {Observable} An observable sequence which results from the comonadic bind operation.
*/
observableProto.manySelect = function (selector, scheduler) {
isScheduler(scheduler) || (scheduler = immediateScheduler);
var source = this;
return observableDefer(function () {
var chain;
return source
.map(function (x) {
var curr = new ChainObservable(x);
chain && chain.onNext(x);
chain = curr;
return curr;
})
.tap(
noop,
function (e) { chain && chain.onError(e); },
function () { chain && chain.onCompleted(); }
)
.observeOn(scheduler)
.map(selector);
}, source);
};
var ChainObservable = (function (__super__) {
function subscribe (observer) {
var self = this, g = new CompositeDisposable();
g.add(currentThreadScheduler.schedule(function () {
observer.onNext(self.head);
g.add(self.tail.mergeAll().subscribe(observer));
}));
return g;
}
inherits(ChainObservable, __super__);
function ChainObservable(head) {
__super__.call(this, subscribe);
this.head = head;
this.tail = new AsyncSubject();
}
addProperties(ChainObservable.prototype, Observer, {
onCompleted: function () {
this.onNext(Observable.empty());
},
onError: function (e) {
this.onNext(Observable.throwException(e));
},
onNext: function (v) {
this.tail.onNext(v);
this.tail.onCompleted();
}
});
return ChainObservable;
}(Observable));
/** @private */
var Map = root.Map || (function () {
function Map() {
this._keys = [];
this._values = [];
}
Map.prototype.get = function (key) {
var i = this._keys.indexOf(key);
return i !== -1 ? this._values[i] : undefined;
};
Map.prototype.set = function (key, value) {
var i = this._keys.indexOf(key);
i !== -1 && (this._values[i] = value);
this._values[this._keys.push(key) - 1] = value;
};
Map.prototype.forEach = function (callback, thisArg) {
for (var i = 0, len = this._keys.length; i < len; i++) {
callback.call(thisArg, this._values[i], this._keys[i]);
}
};
return Map;
}());
/**
* @constructor
* Represents a join pattern over observable sequences.
*/
function Pattern(patterns) {
this.patterns = patterns;
}
/**
* Creates a pattern that matches the current plan matches and when the specified observable sequences has an available value.
* @param other Observable sequence to match in addition to the current pattern.
* @return {Pattern} Pattern object that matches when all observable sequences in the pattern have an available value.
*/
Pattern.prototype.and = function (other) {
return new Pattern(this.patterns.concat(other));
};
/**
* Matches when all observable sequences in the pattern (specified using a chain of and operators) have an available value and projects the values.
* @param {Function} selector Selector that will be invoked with available values from the source sequences, in the same order of the sequences in the pattern.
* @return {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator.
*/
Pattern.prototype.thenDo = function (selector) {
return new Plan(this, selector);
};
function Plan(expression, selector) {
this.expression = expression;
this.selector = selector;
}
Plan.prototype.activate = function (externalSubscriptions, observer, deactivate) {
var self = this;
var joinObservers = [];
for (var i = 0, len = this.expression.patterns.length; i < len; i++) {
joinObservers.push(planCreateObserver(externalSubscriptions, this.expression.patterns[i], observer.onError.bind(observer)));
}
var activePlan = new ActivePlan(joinObservers, function () {
var result;
try {
result = self.selector.apply(self, arguments);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
}, function () {
for (var j = 0, jlen = joinObservers.length; j < jlen; j++) {
joinObservers[j].removeActivePlan(activePlan);
}
deactivate(activePlan);
});
for (i = 0, len = joinObservers.length; i < len; i++) {
joinObservers[i].addActivePlan(activePlan);
}
return activePlan;
};
function planCreateObserver(externalSubscriptions, observable, onError) {
var entry = externalSubscriptions.get(observable);
if (!entry) {
var observer = new JoinObserver(observable, onError);
externalSubscriptions.set(observable, observer);
return observer;
}
return entry;
}
function ActivePlan(joinObserverArray, onNext, onCompleted) {
this.joinObserverArray = joinObserverArray;
this.onNext = onNext;
this.onCompleted = onCompleted;
this.joinObservers = new Map();
for (var i = 0, len = this.joinObserverArray.length; i < len; i++) {
var joinObserver = this.joinObserverArray[i];
this.joinObservers.set(joinObserver, joinObserver);
}
}
ActivePlan.prototype.dequeue = function () {
this.joinObservers.forEach(function (v) { v.queue.shift(); });
};
ActivePlan.prototype.match = function () {
var i, len, hasValues = true;
for (i = 0, len = this.joinObserverArray.length; i < len; i++) {
if (this.joinObserverArray[i].queue.length === 0) {
hasValues = false;
break;
}
}
if (hasValues) {
var firstValues = [],
isCompleted = false;
for (i = 0, len = this.joinObserverArray.length; i < len; i++) {
firstValues.push(this.joinObserverArray[i].queue[0]);
this.joinObserverArray[i].queue[0].kind === 'C' && (isCompleted = true);
}
if (isCompleted) {
this.onCompleted();
} else {
this.dequeue();
var values = [];
for (i = 0, len = firstValues.length; i < firstValues.length; i++) {
values.push(firstValues[i].value);
}
this.onNext.apply(this, values);
}
}
};
var JoinObserver = (function (__super__) {
inherits(JoinObserver, __super__);
function JoinObserver(source, onError) {
__super__.call(this);
this.source = source;
this.onError = onError;
this.queue = [];
this.activePlans = [];
this.subscription = new SingleAssignmentDisposable();
this.isDisposed = false;
}
var JoinObserverPrototype = JoinObserver.prototype;
JoinObserverPrototype.next = function (notification) {
if (!this.isDisposed) {
if (notification.kind === 'E') {
return this.onError(notification.exception);
}
this.queue.push(notification);
var activePlans = this.activePlans.slice(0);
for (var i = 0, len = activePlans.length; i < len; i++) {
activePlans[i].match();
}
}
};
JoinObserverPrototype.error = noop;
JoinObserverPrototype.completed = noop;
JoinObserverPrototype.addActivePlan = function (activePlan) {
this.activePlans.push(activePlan);
};
JoinObserverPrototype.subscribe = function () {
this.subscription.setDisposable(this.source.materialize().subscribe(this));
};
JoinObserverPrototype.removeActivePlan = function (activePlan) {
this.activePlans.splice(this.activePlans.indexOf(activePlan), 1);
this.activePlans.length === 0 && this.dispose();
};
JoinObserverPrototype.dispose = function () {
__super__.prototype.dispose.call(this);
if (!this.isDisposed) {
this.isDisposed = true;
this.subscription.dispose();
}
};
return JoinObserver;
} (AbstractObserver));
/**
* Creates a pattern that matches when both observable sequences have an available value.
*
* @param right Observable sequence to match with the current sequence.
* @return {Pattern} Pattern object that matches when both observable sequences have an available value.
*/
observableProto.and = function (right) {
return new Pattern([this, right]);
};
/**
* Matches when the observable sequence has an available value and projects the value.
*
* @param {Function} selector Selector that will be invoked for values in the source sequence.
* @returns {Plan} Plan that produces the projected values, to be fed (with other plans) to the when operator.
*/
observableProto.thenDo = function (selector) {
return new Pattern([this]).thenDo(selector);
};
/**
* Joins together the results from several patterns.
*
* @param plans A series of plans (specified as an Array of as a series of arguments) created by use of the Then operator on patterns.
* @returns {Observable} Observable sequence with the results form matching several patterns.
*/
Observable.when = function () {
var plans = [];
if (Array.isArray(arguments[0])) {
plans = arguments[0];
} else {
for(var i = 0, len = arguments.length; i < len; i++) { plans.push(arguments[i]); }
}
return new AnonymousObservable(function (observer) {
var activePlans = [],
externalSubscriptions = new Map();
var outObserver = observerCreate(
observer.onNext.bind(observer),
function (err) {
externalSubscriptions.forEach(function (v) { v.onError(err); });
observer.onError(err);
},
observer.onCompleted.bind(observer)
);
try {
for (var i = 0, len = plans.length; i < len; i++) {
activePlans.push(plans[i].activate(externalSubscriptions, outObserver, function (activePlan) {
var idx = activePlans.indexOf(activePlan);
activePlans.splice(idx, 1);
activePlans.length === 0 && observer.onCompleted();
}));
}
} catch (e) {
observableThrow(e).subscribe(observer);
}
var group = new CompositeDisposable();
externalSubscriptions.forEach(function (joinObserver) {
joinObserver.subscribe();
group.add(joinObserver);
});
return group;
});
};
function observableTimerDate(dueTime, scheduler) {
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithAbsolute(dueTime, function () {
observer.onNext(0);
observer.onCompleted();
});
});
}
function observableTimerDateAndPeriod(dueTime, period, scheduler) {
return new AnonymousObservable(function (observer) {
var d = dueTime, p = normalizeTime(period);
return scheduler.scheduleRecursiveWithAbsoluteAndState(0, d, function (count, self) {
if (p > 0) {
var now = scheduler.now();
d = d + p;
d <= now && (d = now + p);
}
observer.onNext(count);
self(count + 1, d);
});
});
}
function observableTimerTimeSpan(dueTime, scheduler) {
return new AnonymousObservable(function (observer) {
return scheduler.scheduleWithRelative(normalizeTime(dueTime), function () {
observer.onNext(0);
observer.onCompleted();
});
});
}
function observableTimerTimeSpanAndPeriod(dueTime, period, scheduler) {
return dueTime === period ?
new AnonymousObservable(function (observer) {
return scheduler.schedulePeriodicWithState(0, period, function (count) {
observer.onNext(count);
return count + 1;
});
}) :
observableDefer(function () {
return observableTimerDateAndPeriod(scheduler.now() + dueTime, period, scheduler);
});
}
/**
* Returns an observable sequence that produces a value after each period.
*
* @example
* 1 - res = Rx.Observable.interval(1000);
* 2 - res = Rx.Observable.interval(1000, Rx.Scheduler.timeout);
*
* @param {Number} period Period for producing the values in the resulting sequence (specified as an integer denoting milliseconds).
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, Rx.Scheduler.timeout is used.
* @returns {Observable} An observable sequence that produces a value after each period.
*/
var observableinterval = Observable.interval = function (period, scheduler) {
return observableTimerTimeSpanAndPeriod(period, period, isScheduler(scheduler) ? scheduler : timeoutScheduler);
};
/**
* Returns an observable sequence that produces a value after dueTime has elapsed and then after each period.
* @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value.
* @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period.
*/
var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) {
var period;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') {
period = periodOrScheduler;
} else if (isScheduler(periodOrScheduler)) {
scheduler = periodOrScheduler;
}
if (dueTime instanceof Date && period === undefined) {
return observableTimerDate(dueTime.getTime(), scheduler);
}
if (dueTime instanceof Date && period !== undefined) {
period = periodOrScheduler;
return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler);
}
return period === undefined ?
observableTimerTimeSpan(dueTime, scheduler) :
observableTimerTimeSpanAndPeriod(dueTime, period, scheduler);
};
function observableDelayTimeSpan(source, dueTime, scheduler) {
return new AnonymousObservable(function (observer) {
var active = false,
cancelable = new SerialDisposable(),
exception = null,
q = [],
running = false,
subscription;
subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) {
var d, shouldRun;
if (notification.value.kind === 'E') {
q = [];
q.push(notification);
exception = notification.value.exception;
shouldRun = !running;
} else {
q.push({ value: notification.value, timestamp: notification.timestamp + dueTime });
shouldRun = !active;
active = true;
}
if (shouldRun) {
if (exception !== null) {
observer.onError(exception);
} else {
d = new SingleAssignmentDisposable();
cancelable.setDisposable(d);
d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) {
var e, recurseDueTime, result, shouldRecurse;
if (exception !== null) {
return;
}
running = true;
do {
result = null;
if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) {
result = q.shift().value;
}
if (result !== null) {
result.accept(observer);
}
} while (result !== null);
shouldRecurse = false;
recurseDueTime = 0;
if (q.length > 0) {
shouldRecurse = true;
recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now());
} else {
active = false;
}
e = exception;
running = false;
if (e !== null) {
observer.onError(e);
} else if (shouldRecurse) {
self(recurseDueTime);
}
}));
}
}
});
return new CompositeDisposable(subscription, cancelable);
}, source);
}
function observableDelayDate(source, dueTime, scheduler) {
return observableDefer(function () {
return observableDelayTimeSpan(source, dueTime - scheduler.now(), scheduler);
});
}
/**
* Time shifts the observable sequence by dueTime. The relative time intervals between the values are preserved.
*
* @example
* 1 - res = Rx.Observable.delay(new Date());
* 2 - res = Rx.Observable.delay(new Date(), Rx.Scheduler.timeout);
*
* 3 - res = Rx.Observable.delay(5000);
* 4 - res = Rx.Observable.delay(5000, 1000, Rx.Scheduler.timeout);
* @memberOf Observable#
* @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) by which to shift the observable sequence.
* @param {Scheduler} [scheduler] Scheduler to run the delay timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} Time-shifted sequence.
*/
observableProto.delay = function (dueTime, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return dueTime instanceof Date ?
observableDelayDate(this, dueTime.getTime(), scheduler) :
observableDelayTimeSpan(this, dueTime, scheduler);
};
/**
* Ignores values from an observable sequence which are followed by another value before dueTime.
* @param {Number} dueTime Duration of the debounce period for each value (specified as an integer denoting milliseconds).
* @param {Scheduler} [scheduler] Scheduler to run the debounce timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} The debounced sequence.
*/
observableProto.debounce = observableProto.throttleWithTimeout = function (dueTime, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this;
return new AnonymousObservable(function (observer) {
var cancelable = new SerialDisposable(), hasvalue = false, value, id = 0;
var subscription = source.subscribe(
function (x) {
hasvalue = true;
value = x;
id++;
var currentId = id,
d = new SingleAssignmentDisposable();
cancelable.setDisposable(d);
d.setDisposable(scheduler.scheduleWithRelative(dueTime, function () {
hasvalue && id === currentId && observer.onNext(value);
hasvalue = false;
}));
},
function (e) {
cancelable.dispose();
observer.onError(e);
hasvalue = false;
id++;
},
function () {
cancelable.dispose();
hasvalue && observer.onNext(value);
observer.onCompleted();
hasvalue = false;
id++;
});
return new CompositeDisposable(subscription, cancelable);
}, this);
};
/**
* @deprecated use #debounce or #throttleWithTimeout instead.
*/
observableProto.throttle = function(dueTime, scheduler) {
//deprecate('throttle', 'debounce or throttleWithTimeout');
return this.debounce(dueTime, scheduler);
};
/**
* Projects each element of an observable sequence into zero or more windows which are produced based on timing information.
* @param {Number} timeSpan Length of each window (specified as an integer denoting milliseconds).
* @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive windows (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent windows.
* @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.windowWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) {
var source = this, timeShift;
timeShiftOrScheduler == null && (timeShift = timeSpan);
isScheduler(scheduler) || (scheduler = timeoutScheduler);
if (typeof timeShiftOrScheduler === 'number') {
timeShift = timeShiftOrScheduler;
} else if (isScheduler(timeShiftOrScheduler)) {
timeShift = timeSpan;
scheduler = timeShiftOrScheduler;
}
return new AnonymousObservable(function (observer) {
var groupDisposable,
nextShift = timeShift,
nextSpan = timeSpan,
q = [],
refCountDisposable,
timerD = new SerialDisposable(),
totalTime = 0;
groupDisposable = new CompositeDisposable(timerD),
refCountDisposable = new RefCountDisposable(groupDisposable);
function createTimer () {
var m = new SingleAssignmentDisposable(),
isSpan = false,
isShift = false;
timerD.setDisposable(m);
if (nextSpan === nextShift) {
isSpan = true;
isShift = true;
} else if (nextSpan < nextShift) {
isSpan = true;
} else {
isShift = true;
}
var newTotalTime = isSpan ? nextSpan : nextShift,
ts = newTotalTime - totalTime;
totalTime = newTotalTime;
if (isSpan) {
nextSpan += timeShift;
}
if (isShift) {
nextShift += timeShift;
}
m.setDisposable(scheduler.scheduleWithRelative(ts, function () {
if (isShift) {
var s = new Subject();
q.push(s);
observer.onNext(addRef(s, refCountDisposable));
}
isSpan && q.shift().onCompleted();
createTimer();
}));
};
q.push(new Subject());
observer.onNext(addRef(q[0], refCountDisposable));
createTimer();
groupDisposable.add(source.subscribe(
function (x) {
for (var i = 0, len = q.length; i < len; i++) { q[i].onNext(x); }
},
function (e) {
for (var i = 0, len = q.length; i < len; i++) { q[i].onError(e); }
observer.onError(e);
},
function () {
for (var i = 0, len = q.length; i < len; i++) { q[i].onCompleted(); }
observer.onCompleted();
}
));
return refCountDisposable;
}, source);
};
/**
* Projects each element of an observable sequence into a window that is completed when either it's full or a given amount of time has elapsed.
* @param {Number} timeSpan Maximum time length of a window.
* @param {Number} count Maximum element count of a window.
* @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.windowWithTimeOrCount = function (timeSpan, count, scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var timerD = new SerialDisposable(),
groupDisposable = new CompositeDisposable(timerD),
refCountDisposable = new RefCountDisposable(groupDisposable),
n = 0,
windowId = 0,
s = new Subject();
function createTimer(id) {
var m = new SingleAssignmentDisposable();
timerD.setDisposable(m);
m.setDisposable(scheduler.scheduleWithRelative(timeSpan, function () {
if (id !== windowId) { return; }
n = 0;
var newId = ++windowId;
s.onCompleted();
s = new Subject();
observer.onNext(addRef(s, refCountDisposable));
createTimer(newId);
}));
}
observer.onNext(addRef(s, refCountDisposable));
createTimer(0);
groupDisposable.add(source.subscribe(
function (x) {
var newId = 0, newWindow = false;
s.onNext(x);
if (++n === count) {
newWindow = true;
n = 0;
newId = ++windowId;
s.onCompleted();
s = new Subject();
observer.onNext(addRef(s, refCountDisposable));
}
newWindow && createTimer(newId);
},
function (e) {
s.onError(e);
observer.onError(e);
}, function () {
s.onCompleted();
observer.onCompleted();
}
));
return refCountDisposable;
}, source);
};
/**
* Projects each element of an observable sequence into zero or more buffers which are produced based on timing information.
*
* @example
* 1 - res = xs.bufferWithTime(1000, scheduler); // non-overlapping segments of 1 second
* 2 - res = xs.bufferWithTime(1000, 500, scheduler; // segments of 1 second with time shift 0.5 seconds
*
* @param {Number} timeSpan Length of each buffer (specified as an integer denoting milliseconds).
* @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive buffers (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent buffers.
* @param {Scheduler} [scheduler] Scheduler to run buffer timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of buffers.
*/
observableProto.bufferWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) {
return this.windowWithTime.apply(this, arguments).selectMany(function (x) { return x.toArray(); });
};
/**
* Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed.
*
* @example
* 1 - res = source.bufferWithTimeOrCount(5000, 50); // 5s or 50 items in an array
* 2 - res = source.bufferWithTimeOrCount(5000, 50, scheduler); // 5s or 50 items in an array
*
* @param {Number} timeSpan Maximum time length of a buffer.
* @param {Number} count Maximum element count of a buffer.
* @param {Scheduler} [scheduler] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of buffers.
*/
observableProto.bufferWithTimeOrCount = function (timeSpan, count, scheduler) {
return this.windowWithTimeOrCount(timeSpan, count, scheduler).selectMany(function (x) {
return x.toArray();
});
};
/**
* Records the time interval between consecutive values in an observable sequence.
*
* @example
* 1 - res = source.timeInterval();
* 2 - res = source.timeInterval(Rx.Scheduler.timeout);
*
* @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence with time interval information on values.
*/
observableProto.timeInterval = function (scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return observableDefer(function () {
var last = scheduler.now();
return source.map(function (x) {
var now = scheduler.now(), span = now - last;
last = now;
return { value: x, interval: span };
});
});
};
/**
* Records the timestamp for each value in an observable sequence.
*
* @example
* 1 - res = source.timestamp(); // produces { value: x, timestamp: ts }
* 2 - res = source.timestamp(Rx.Scheduler.timeout);
*
* @param {Scheduler} [scheduler] Scheduler used to compute timestamps. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence with timestamp information on values.
*/
observableProto.timestamp = function (scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return this.map(function (x) {
return { value: x, timestamp: scheduler.now() };
});
};
function sampleObservable(source, sampler) {
return new AnonymousObservable(function (observer) {
var atEnd, value, hasValue;
function sampleSubscribe() {
if (hasValue) {
hasValue = false;
observer.onNext(value);
}
atEnd && observer.onCompleted();
}
return new CompositeDisposable(
source.subscribe(function (newValue) {
hasValue = true;
value = newValue;
}, observer.onError.bind(observer), function () {
atEnd = true;
}),
sampler.subscribe(sampleSubscribe, observer.onError.bind(observer), sampleSubscribe)
);
}, source);
}
/**
* Samples the observable sequence at each interval.
*
* @example
* 1 - res = source.sample(sampleObservable); // Sampler tick sequence
* 2 - res = source.sample(5000); // 5 seconds
* 2 - res = source.sample(5000, Rx.Scheduler.timeout); // 5 seconds
*
* @param {Mixed} intervalOrSampler Interval at which to sample (specified as an integer denoting milliseconds) or Sampler Observable.
* @param {Scheduler} [scheduler] Scheduler to run the sampling timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} Sampled observable sequence.
*/
observableProto.sample = observableProto.throttleLatest = function (intervalOrSampler, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return typeof intervalOrSampler === 'number' ?
sampleObservable(this, observableinterval(intervalOrSampler, scheduler)) :
sampleObservable(this, intervalOrSampler);
};
/**
* Returns the source observable sequence or the other observable sequence if dueTime elapses.
* @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) when a timeout occurs.
* @param {Observable} [other] Sequence to return in case of a timeout. If not specified, a timeout error throwing sequence will be used.
* @param {Scheduler} [scheduler] Scheduler to run the timeout timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} The source sequence switching to the other sequence in case of a timeout.
*/
observableProto.timeout = function (dueTime, other, scheduler) {
(other == null || typeof other === 'string') && (other = observableThrow(new Error(other || 'Timeout')));
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this, schedulerMethod = dueTime instanceof Date ?
'scheduleWithAbsolute' :
'scheduleWithRelative';
return new AnonymousObservable(function (observer) {
var id = 0,
original = new SingleAssignmentDisposable(),
subscription = new SerialDisposable(),
switched = false,
timer = new SerialDisposable();
subscription.setDisposable(original);
function createTimer() {
var myId = id;
timer.setDisposable(scheduler[schedulerMethod](dueTime, function () {
if (id === myId) {
isPromise(other) && (other = observableFromPromise(other));
subscription.setDisposable(other.subscribe(observer));
}
}));
}
createTimer();
original.setDisposable(source.subscribe(function (x) {
if (!switched) {
id++;
observer.onNext(x);
createTimer();
}
}, function (e) {
if (!switched) {
id++;
observer.onError(e);
}
}, function () {
if (!switched) {
id++;
observer.onCompleted();
}
}));
return new CompositeDisposable(subscription, timer);
}, source);
};
/**
* Generates an observable sequence by iterating a state from an initial state until the condition fails.
*
* @example
* res = source.generateWithAbsoluteTime(0,
* function (x) { return return true; },
* function (x) { return x + 1; },
* function (x) { return x; },
* function (x) { return new Date(); }
* });
*
* @param {Mixed} initialState Initial state.
* @param {Function} condition Condition to terminate generation (upon returning false).
* @param {Function} iterate Iteration step function.
* @param {Function} resultSelector Selector function for results produced in the sequence.
* @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning Date values.
* @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used.
* @returns {Observable} The generated sequence.
*/
Observable.generateWithAbsoluteTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var first = true,
hasResult = false,
result,
state = initialState,
time;
return scheduler.scheduleRecursiveWithAbsolute(scheduler.now(), function (self) {
hasResult && observer.onNext(result);
try {
if (first) {
first = false;
} else {
state = iterate(state);
}
hasResult = condition(state);
if (hasResult) {
result = resultSelector(state);
time = timeSelector(state);
}
} catch (e) {
observer.onError(e);
return;
}
if (hasResult) {
self(time);
} else {
observer.onCompleted();
}
});
});
};
/**
* Generates an observable sequence by iterating a state from an initial state until the condition fails.
*
* @example
* res = source.generateWithRelativeTime(0,
* function (x) { return return true; },
* function (x) { return x + 1; },
* function (x) { return x; },
* function (x) { return 500; }
* );
*
* @param {Mixed} initialState Initial state.
* @param {Function} condition Condition to terminate generation (upon returning false).
* @param {Function} iterate Iteration step function.
* @param {Function} resultSelector Selector function for results produced in the sequence.
* @param {Function} timeSelector Time selector function to control the speed of values being produced each iteration, returning integer values denoting milliseconds.
* @param {Scheduler} [scheduler] Scheduler on which to run the generator loop. If not specified, the timeout scheduler is used.
* @returns {Observable} The generated sequence.
*/
Observable.generateWithRelativeTime = function (initialState, condition, iterate, resultSelector, timeSelector, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var first = true,
hasResult = false,
result,
state = initialState,
time;
return scheduler.scheduleRecursiveWithRelative(0, function (self) {
hasResult && observer.onNext(result);
try {
if (first) {
first = false;
} else {
state = iterate(state);
}
hasResult = condition(state);
if (hasResult) {
result = resultSelector(state);
time = timeSelector(state);
}
} catch (e) {
observer.onError(e);
return;
}
if (hasResult) {
self(time);
} else {
observer.onCompleted();
}
});
});
};
/**
* Time shifts the observable sequence by delaying the subscription.
*
* @example
* 1 - res = source.delaySubscription(5000); // 5s
* 2 - res = source.delaySubscription(5000, Rx.Scheduler.timeout); // 5 seconds
*
* @param {Number} dueTime Absolute or relative time to perform the subscription at.
* @param {Scheduler} [scheduler] Scheduler to run the subscription delay timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} Time-shifted sequence.
*/
observableProto.delaySubscription = function (dueTime, scheduler) {
return this.delayWithSelector(observableTimer(dueTime, isScheduler(scheduler) ? scheduler : timeoutScheduler), observableEmpty);
};
/**
* Time shifts the observable sequence based on a subscription delay and a delay selector function for each element.
*
* @example
* 1 - res = source.delayWithSelector(function (x) { return Rx.Scheduler.timer(5000); }); // with selector only
* 1 - res = source.delayWithSelector(Rx.Observable.timer(2000), function (x) { return Rx.Observable.timer(x); }); // with delay and selector
*
* @param {Observable} [subscriptionDelay] Sequence indicating the delay for the subscription to the source.
* @param {Function} delayDurationSelector Selector function to retrieve a sequence indicating the delay for each given element.
* @returns {Observable} Time-shifted sequence.
*/
observableProto.delayWithSelector = function (subscriptionDelay, delayDurationSelector) {
var source = this, subDelay, selector;
if (typeof subscriptionDelay === 'function') {
selector = subscriptionDelay;
} else {
subDelay = subscriptionDelay;
selector = delayDurationSelector;
}
return new AnonymousObservable(function (observer) {
var delays = new CompositeDisposable(), atEnd = false, done = function () {
if (atEnd && delays.length === 0) { observer.onCompleted(); }
}, subscription = new SerialDisposable(), start = function () {
subscription.setDisposable(source.subscribe(function (x) {
var delay;
try {
delay = selector(x);
} catch (error) {
observer.onError(error);
return;
}
var d = new SingleAssignmentDisposable();
delays.add(d);
d.setDisposable(delay.subscribe(function () {
observer.onNext(x);
delays.remove(d);
done();
}, observer.onError.bind(observer), function () {
observer.onNext(x);
delays.remove(d);
done();
}));
}, observer.onError.bind(observer), function () {
atEnd = true;
subscription.dispose();
done();
}));
};
if (!subDelay) {
start();
} else {
subscription.setDisposable(subDelay.subscribe(start, observer.onError.bind(observer), start));
}
return new CompositeDisposable(subscription, delays);
}, this);
};
/**
* Returns the source observable sequence, switching to the other observable sequence if a timeout is signaled.
* @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never().
* @param {Function} timeoutDurationSelector Selector to retrieve an observable sequence that represents the timeout between the current element and the next element.
* @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException().
* @returns {Observable} The source sequence switching to the other sequence in case of a timeout.
*/
observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) {
if (arguments.length === 1) {
timeoutdurationSelector = firstTimeout;
firstTimeout = observableNever();
}
other || (other = observableThrow(new Error('Timeout')));
var source = this;
return new AnonymousObservable(function (observer) {
var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable();
subscription.setDisposable(original);
var id = 0, switched = false;
function setTimer(timeout) {
var myId = id;
function timerWins () {
return id === myId;
}
var d = new SingleAssignmentDisposable();
timer.setDisposable(d);
d.setDisposable(timeout.subscribe(function () {
timerWins() && subscription.setDisposable(other.subscribe(observer));
d.dispose();
}, function (e) {
timerWins() && observer.onError(e);
}, function () {
timerWins() && subscription.setDisposable(other.subscribe(observer));
}));
};
setTimer(firstTimeout);
function observerWins() {
var res = !switched;
if (res) { id++; }
return res;
}
original.setDisposable(source.subscribe(function (x) {
if (observerWins()) {
observer.onNext(x);
var timeout;
try {
timeout = timeoutdurationSelector(x);
} catch (e) {
observer.onError(e);
return;
}
setTimer(isPromise(timeout) ? observableFromPromise(timeout) : timeout);
}
}, function (e) {
observerWins() && observer.onError(e);
}, function () {
observerWins() && observer.onCompleted();
}));
return new CompositeDisposable(subscription, timer);
}, source);
};
/**
* Ignores values from an observable sequence which are followed by another value within a computed throttle duration.
* @param {Function} durationSelector Selector function to retrieve a sequence indicating the throttle duration for each given element.
* @returns {Observable} The debounced sequence.
*/
observableProto.debounceWithSelector = function (durationSelector) {
var source = this;
return new AnonymousObservable(function (observer) {
var value, hasValue = false, cancelable = new SerialDisposable(), id = 0;
var subscription = source.subscribe(function (x) {
var throttle;
try {
throttle = durationSelector(x);
} catch (e) {
observer.onError(e);
return;
}
isPromise(throttle) && (throttle = observableFromPromise(throttle));
hasValue = true;
value = x;
id++;
var currentid = id, d = new SingleAssignmentDisposable();
cancelable.setDisposable(d);
d.setDisposable(throttle.subscribe(function () {
hasValue && id === currentid && observer.onNext(value);
hasValue = false;
d.dispose();
}, observer.onError.bind(observer), function () {
hasValue && id === currentid && observer.onNext(value);
hasValue = false;
d.dispose();
}));
}, function (e) {
cancelable.dispose();
observer.onError(e);
hasValue = false;
id++;
}, function () {
cancelable.dispose();
hasValue && observer.onNext(value);
observer.onCompleted();
hasValue = false;
id++;
});
return new CompositeDisposable(subscription, cancelable);
}, source);
};
observableProto.throttleWithSelector = function () {
//deprecate('throttleWithSelector', 'debounceWithSelector');
return this.debounceWithSelector.apply(this, arguments);
};
/**
* Skips elements for the specified duration from the end of the observable source sequence, using the specified scheduler to run timers.
*
* 1 - res = source.skipLastWithTime(5000);
* 2 - res = source.skipLastWithTime(5000, scheduler);
*
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for skipping elements from the end of the sequence.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout
* @returns {Observable} An observable sequence with the elements skipped during the specified duration from the end of the source sequence.
*/
observableProto.skipLastWithTime = function (duration, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this;
return new AnonymousObservable(function (o) {
var q = [];
return source.subscribe(function (x) {
var now = scheduler.now();
q.push({ interval: now, value: x });
while (q.length > 0 && now - q[0].interval >= duration) {
o.onNext(q.shift().value);
}
}, function (e) { o.onError(e); }, function () {
var now = scheduler.now();
while (q.length > 0 && now - q[0].interval >= duration) {
o.onNext(q.shift().value);
}
o.onCompleted();
});
}, source);
};
/**
* Returns elements within the specified duration from the end of the observable source sequence, using the specified schedulers to run timers and to drain the collected elements.
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for taking elements from the end of the sequence.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements taken during the specified duration from the end of the source sequence.
*/
observableProto.takeLastWithTime = function (duration, scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (o) {
var q = [];
return source.subscribe(function (x) {
var now = scheduler.now();
q.push({ interval: now, value: x });
while (q.length > 0 && now - q[0].interval >= duration) {
q.shift();
}
}, function (e) { o.onError(e); }, function () {
var now = scheduler.now();
while (q.length > 0) {
var next = q.shift();
if (now - next.interval <= duration) { o.onNext(next.value); }
}
o.onCompleted();
});
}, source);
};
/**
* Returns an array with the elements within the specified duration from the end of the observable source sequence, using the specified scheduler to run timers.
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for taking elements from the end of the sequence.
* @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence containing a single array with the elements taken during the specified duration from the end of the source sequence.
*/
observableProto.takeLastBufferWithTime = function (duration, scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (o) {
var q = [];
return source.subscribe(function (x) {
var now = scheduler.now();
q.push({ interval: now, value: x });
while (q.length > 0 && now - q[0].interval >= duration) {
q.shift();
}
}, function (e) { o.onError(e); }, function () {
var now = scheduler.now(), res = [];
while (q.length > 0) {
var next = q.shift();
now - next.interval <= duration && res.push(next.value);
}
o.onNext(res);
o.onCompleted();
});
}, source);
};
/**
* Takes elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
*
* @example
* 1 - res = source.takeWithTime(5000, [optional scheduler]);
* @description
* This operator accumulates a queue with a length enough to store elements received during the initial duration window.
* As more elements are received, elements older than the specified duration are taken from the queue and produced on the
* result sequence. This causes elements to be delayed with duration.
* @param {Number} duration Duration for taking elements from the start of the sequence.
* @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements taken during the specified duration from the start of the source sequence.
*/
observableProto.takeWithTime = function (duration, scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (o) {
return new CompositeDisposable(scheduler.scheduleWithRelative(duration, function () { o.onCompleted(); }), source.subscribe(o));
}, source);
};
/**
* Skips elements for the specified duration from the start of the observable source sequence, using the specified scheduler to run timers.
*
* @example
* 1 - res = source.skipWithTime(5000, [optional scheduler]);
*
* @description
* Specifying a zero value for duration doesn't guarantee no elements will be dropped from the start of the source sequence.
* This is a side-effect of the asynchrony introduced by the scheduler, where the action that causes callbacks from the source sequence to be forwarded
* may not execute immediately, despite the zero due time.
*
* Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the duration.
* @param {Number} duration Duration for skipping elements from the start of the sequence.
* @param {Scheduler} scheduler Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements skipped during the specified duration from the start of the source sequence.
*/
observableProto.skipWithTime = function (duration, scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var open = false;
return new CompositeDisposable(
scheduler.scheduleWithRelative(duration, function () { open = true; }),
source.subscribe(function (x) { open && observer.onNext(x); }, observer.onError.bind(observer), observer.onCompleted.bind(observer)));
}, source);
};
/**
* Skips elements from the observable source sequence until the specified start time, using the specified scheduler to run timers.
* Errors produced by the source sequence are always forwarded to the result sequence, even if the error occurs before the start time.
*
* @examples
* 1 - res = source.skipUntilWithTime(new Date(), [scheduler]);
* 2 - res = source.skipUntilWithTime(5000, [scheduler]);
* @param {Date|Number} startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements skipped until the specified start time.
*/
observableProto.skipUntilWithTime = function (startTime, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this, schedulerMethod = startTime instanceof Date ?
'scheduleWithAbsolute' :
'scheduleWithRelative';
return new AnonymousObservable(function (o) {
var open = false;
return new CompositeDisposable(
scheduler[schedulerMethod](startTime, function () { open = true; }),
source.subscribe(
function (x) { open && o.onNext(x); },
function (e) { o.onError(e); }, function () { o.onCompleted(); }));
}, source);
};
/**
* Takes elements for the specified duration until the specified end time, using the specified scheduler to run timers.
* @param {Number | Date} endTime Time to stop taking elements from the source sequence. If this value is less than or equal to new Date(), the result stream will complete immediately.
* @param {Scheduler} [scheduler] Scheduler to run the timer on.
* @returns {Observable} An observable sequence with the elements taken until the specified end time.
*/
observableProto.takeUntilWithTime = function (endTime, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this, schedulerMethod = endTime instanceof Date ?
'scheduleWithAbsolute' :
'scheduleWithRelative';
return new AnonymousObservable(function (o) {
return new CompositeDisposable(
scheduler[schedulerMethod](endTime, function () { o.onCompleted(); }),
source.subscribe(o));
}, source);
};
/**
* Returns an Observable that emits only the first item emitted by the source Observable during sequential time windows of a specified duration.
* @param {Number} windowDuration time to wait before emitting another item after emitting the last item
* @param {Scheduler} [scheduler] the Scheduler to use internally to manage the timers that handle timeout for each item. If not provided, defaults to Scheduler.timeout.
* @returns {Observable} An Observable that performs the throttle operation.
*/
observableProto.throttleFirst = function (windowDuration, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var duration = +windowDuration || 0;
if (duration <= 0) { throw new RangeError('windowDuration cannot be less or equal zero.'); }
var source = this;
return new AnonymousObservable(function (o) {
var lastOnNext = 0;
return source.subscribe(
function (x) {
var now = scheduler.now();
if (lastOnNext === 0 || now - lastOnNext >= duration) {
lastOnNext = now;
o.onNext(x);
}
},function (e) { o.onError(e); }, function () { o.onCompleted(); }
);
}, source);
};
/*
* Performs a exclusive waiting for the first to finish before subscribing to another observable.
* Observables that come in between subscriptions will be dropped on the floor.
* @returns {Observable} A exclusive observable with only the results that happen when subscribed.
*/
observableProto.exclusive = function () {
var sources = this;
return new AnonymousObservable(function (observer) {
var hasCurrent = false,
isStopped = false,
m = new SingleAssignmentDisposable(),
g = new CompositeDisposable();
g.add(m);
m.setDisposable(sources.subscribe(
function (innerSource) {
if (!hasCurrent) {
hasCurrent = true;
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
var innerSubscription = new SingleAssignmentDisposable();
g.add(innerSubscription);
innerSubscription.setDisposable(innerSource.subscribe(
observer.onNext.bind(observer),
observer.onError.bind(observer),
function () {
g.remove(innerSubscription);
hasCurrent = false;
if (isStopped && g.length === 1) {
observer.onCompleted();
}
}));
}
},
observer.onError.bind(observer),
function () {
isStopped = true;
if (!hasCurrent && g.length === 1) {
observer.onCompleted();
}
}));
return g;
}, this);
};
/*
* Performs a exclusive map waiting for the first to finish before subscribing to another observable.
* Observables that come in between subscriptions will be dropped on the floor.
* @param {Function} selector Selector to invoke for every item in the current subscription.
* @param {Any} [thisArg] An optional context to invoke with the selector parameter.
* @returns {Observable} An exclusive observable with only the results that happen when subscribed.
*/
observableProto.exclusiveMap = function (selector, thisArg) {
var sources = this,
selectorFunc = bindCallback(selector, thisArg, 3);
return new AnonymousObservable(function (observer) {
var index = 0,
hasCurrent = false,
isStopped = true,
m = new SingleAssignmentDisposable(),
g = new CompositeDisposable();
g.add(m);
m.setDisposable(sources.subscribe(
function (innerSource) {
if (!hasCurrent) {
hasCurrent = true;
innerSubscription = new SingleAssignmentDisposable();
g.add(innerSubscription);
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
innerSubscription.setDisposable(innerSource.subscribe(
function (x) {
var result;
try {
result = selectorFunc(x, index++, innerSource);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(result);
},
function (e) { observer.onError(e); },
function () {
g.remove(innerSubscription);
hasCurrent = false;
if (isStopped && g.length === 1) {
observer.onCompleted();
}
}));
}
},
function (e) { observer.onError(e); },
function () {
isStopped = true;
if (g.length === 1 && !hasCurrent) {
observer.onCompleted();
}
}));
return g;
}, this);
};
/**
* Executes a transducer to transform the observable sequence
* @param {Transducer} transducer A transducer to execute
* @returns {Observable} An Observable sequence containing the results from the transducer.
*/
observableProto.transduce = function(transducer) {
var source = this;
function transformForObserver(observer) {
return {
init: function() {
return observer;
},
step: function(obs, input) {
return obs.onNext(input);
},
result: function(obs) {
return obs.onCompleted();
}
};
}
return new AnonymousObservable(function(observer) {
var xform = transducer(transformForObserver(observer));
return source.subscribe(
function(v) {
try {
xform.step(observer, v);
} catch (e) {
observer.onError(e);
}
},
observer.onError.bind(observer),
function() { xform.result(observer); }
);
}, source);
};
/** Provides a set of extension methods for virtual time scheduling. */
Rx.VirtualTimeScheduler = (function (__super__) {
function 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 setDisposable(s, state) {
var ado = state[0], subscribe = state[1];
try {
ado.setDisposable(fixSubscriber(subscribe(ado)));
} catch (e) {
if (!ado.fail(e)) { throw e; }
}
}
function AnonymousObservable(subscribe, parent) {
this.source = parent;
function s(observer) {
var ado = new AutoDetachObserver(observer), state = [ado, subscribe];
if (currentThreadScheduler.scheduleRequired()) {
currentThreadScheduler.scheduleWithState(state, setDisposable);
} else {
setDisposable(null, state);
}
return ado;
}
__super__.call(this, s);
}
return AnonymousObservable;
}(Observable));
var AutoDetachObserver = (function (__super__) {
inherits(AutoDetachObserver, __super__);
function AutoDetachObserver(observer) {
__super__.call(this);
this.observer = observer;
this.m = new SingleAssignmentDisposable();
}
var AutoDetachObserverPrototype = AutoDetachObserver.prototype;
AutoDetachObserverPrototype.next = function (value) {
var noError = false;
try {
this.observer.onNext(value);
noError = true;
} catch (e) {
throw e;
} finally {
!noError && this.dispose();
}
};
AutoDetachObserverPrototype.error = function (err) {
try {
this.observer.onError(err);
} catch (e) {
throw e;
} finally {
this.dispose();
}
};
AutoDetachObserverPrototype.completed = function () {
try {
this.observer.onCompleted();
} catch (e) {
throw e;
} finally {
this.dispose();
}
};
AutoDetachObserverPrototype.setDisposable = function (value) { this.m.setDisposable(value); };
AutoDetachObserverPrototype.getDisposable = function () { return this.m.getDisposable(); };
AutoDetachObserverPrototype.dispose = function () {
__super__.prototype.dispose.call(this);
this.m.dispose();
};
return AutoDetachObserver;
}(AbstractObserver));
var GroupedObservable = (function (__super__) {
inherits(GroupedObservable, __super__);
function subscribe(observer) {
return this.underlyingObservable.subscribe(observer);
}
function GroupedObservable(key, underlyingObservable, mergedDisposable) {
__super__.call(this, subscribe);
this.key = key;
this.underlyingObservable = !mergedDisposable ?
underlyingObservable :
new AnonymousObservable(function (observer) {
return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer));
});
}
return GroupedObservable;
}(Observable));
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed observers.
*/
var Subject = Rx.Subject = (function (__super__) {
function subscribe(observer) {
checkDisposed(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
if (this.hasError) {
observer.onError(this.error);
return disposableEmpty;
}
observer.onCompleted();
return disposableEmpty;
}
inherits(Subject, __super__);
/**
* Creates a subject.
*/
function Subject() {
__super__.call(this, subscribe);
this.isDisposed = false,
this.isStopped = false,
this.observers = [];
this.hasError = false;
}
addProperties(Subject.prototype, Observer.prototype, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () { return this.observers.length > 0; },
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed(this);
if (!this.isStopped) {
this.isStopped = true;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onCompleted();
}
this.observers.length = 0;
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (error) {
checkDisposed(this);
if (!this.isStopped) {
this.isStopped = true;
this.error = error;
this.hasError = true;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers.length = 0;
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed(this);
if (!this.isStopped) {
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onNext(value);
}
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
}
});
/**
* Creates a subject from the specified observer and observable.
* @param {Observer} observer The observer used to send messages to the subject.
* @param {Observable} observable The observable used to subscribe to messages sent from the subject.
* @returns {Subject} Subject implemented using the given observer and observable.
*/
Subject.create = function (observer, observable) {
return new AnonymousSubject(observer, observable);
};
return Subject;
}(Observable));
/**
* Represents the result of an asynchronous operation.
* The last value before the OnCompleted notification, or the error received through OnError, is sent to all subscribed observers.
*/
var AsyncSubject = Rx.AsyncSubject = (function (__super__) {
function subscribe(observer) {
checkDisposed(this);
if (!this.isStopped) {
this.observers.push(observer);
return new InnerSubscription(this, observer);
}
if (this.hasError) {
observer.onError(this.error);
} else if (this.hasValue) {
observer.onNext(this.value);
observer.onCompleted();
} else {
observer.onCompleted();
}
return disposableEmpty;
}
inherits(AsyncSubject, __super__);
/**
* Creates a subject that can only receive one value and that value is cached for all future observations.
* @constructor
*/
function AsyncSubject() {
__super__.call(this, subscribe);
this.isDisposed = false;
this.isStopped = false;
this.hasValue = false;
this.observers = [];
this.hasError = false;
}
addProperties(AsyncSubject.prototype, Observer, {
/**
* Indicates whether the subject has observers subscribed to it.
* @returns {Boolean} Indicates whether the subject has observers subscribed to it.
*/
hasObservers: function () {
checkDisposed(this);
return this.observers.length > 0;
},
/**
* Notifies all subscribed observers about the end of the sequence, also causing the last received value to be sent out (if any).
*/
onCompleted: function () {
var i, len;
checkDisposed(this);
if (!this.isStopped) {
this.isStopped = true;
var os = cloneArray(this.observers), len = os.length;
if (this.hasValue) {
for (i = 0; i < len; i++) {
var o = os[i];
o.onNext(this.value);
o.onCompleted();
}
} else {
for (i = 0; i < len; i++) {
os[i].onCompleted();
}
}
this.observers.length = 0;
}
},
/**
* Notifies all subscribed observers about the error.
* @param {Mixed} error The Error to send to all observers.
*/
onError: function (error) {
checkDisposed(this);
if (!this.isStopped) {
this.isStopped = true;
this.hasError = true;
this.error = error;
for (var i = 0, os = cloneArray(this.observers), len = os.length; i < len; i++) {
os[i].onError(error);
}
this.observers.length = 0;
}
},
/**
* Sends a value to the subject. The last value received before successful termination will be sent to all subscribed and future observers.
* @param {Mixed} value The value to store in the subject.
*/
onNext: function (value) {
checkDisposed(this);
if (this.isStopped) { return; }
this.value = value;
this.hasValue = true;
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
this.exception = null;
this.value = null;
}
});
return AsyncSubject;
}(Observable));
var AnonymousSubject = Rx.AnonymousSubject = (function (__super__) {
inherits(AnonymousSubject, __super__);
function subscribe(observer) {
return this.observable.subscribe(observer);
}
function AnonymousSubject(observer, observable) {
this.observer = observer;
this.observable = observable;
__super__.call(this, subscribe);
}
addProperties(AnonymousSubject.prototype, Observer.prototype, {
onCompleted: function () {
this.observer.onCompleted();
},
onError: function (error) {
this.observer.onError(error);
},
onNext: function (value) {
this.observer.onNext(value);
}
});
return AnonymousSubject;
}(Observable));
/**
* Used to pause and resume streams.
*/
Rx.Pauser = (function (__super__) {
inherits(Pauser, __super__);
function Pauser() {
__super__.call(this);
}
/**
* Pauses the underlying sequence.
*/
Pauser.prototype.pause = function () { this.onNext(false); };
/**
* Resumes the underlying sequence.
*/
Pauser.prototype.resume = function () { this.onNext(true); };
return Pauser;
}(Subject));
if (typeof define == 'function' && typeof define.amd == 'object' && define.amd) {
root.Rx = Rx;
define(function() {
return Rx;
});
} else if (freeExports && freeModule) {
// in Node.js or RingoJS
if (moduleExports) {
(freeModule.exports = Rx).Rx = Rx;
} else {
freeExports.Rx = Rx;
}
} else {
// in a browser or Rhino
root.Rx = Rx;
}
// All code before this point will be filtered from stack traces.
var rEndingLine = captureLine();
}.call(this));
|
node_modules/material-ui/svg-icons/communication/import-export.js | Rabbit884/reactapp | 'use strict';
Object.defineProperty(exports, "__esModule", {
value: true
});
var _react = require('react');
var _react2 = _interopRequireDefault(_react);
var _pure = require('recompose/pure');
var _pure2 = _interopRequireDefault(_pure);
var _SvgIcon = require('../../SvgIcon');
var _SvgIcon2 = _interopRequireDefault(_SvgIcon);
function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }
var CommunicationImportExport = function CommunicationImportExport(props) {
return _react2.default.createElement(
_SvgIcon2.default,
props,
_react2.default.createElement('path', { d: 'M9 3L5 6.99h3V14h2V6.99h3L9 3zm7 14.01V10h-2v7.01h-3L15 21l4-3.99h-3z' })
);
};
CommunicationImportExport = (0, _pure2.default)(CommunicationImportExport);
CommunicationImportExport.displayName = 'CommunicationImportExport';
CommunicationImportExport.muiName = 'SvgIcon';
exports.default = CommunicationImportExport; |
node_modules/semantic-ui-react/src/modules/Sidebar/SidebarPushable.js | mowbell/clickdelivery-fed-test | import cx from 'classnames'
import PropTypes from 'prop-types'
import React from 'react'
import {
customPropTypes,
getElementType,
getUnhandledProps,
META,
} from '../../lib'
/**
* A pushable sub-component for Sidebar.
*/
function SidebarPushable(props) {
const { className, children } = props
const classes = cx('pushable', className)
const rest = getUnhandledProps(SidebarPushable, props)
const ElementType = getElementType(SidebarPushable, props)
return <ElementType {...rest} className={classes}>{children}</ElementType>
}
SidebarPushable._meta = {
name: 'SidebarPushable',
type: META.TYPES.MODULE,
parent: 'Sidebar',
}
SidebarPushable.propTypes = {
/** An element type to render as (string or function). */
as: customPropTypes.as,
/** Primary content. */
children: PropTypes.node,
/** Additional classes. */
className: PropTypes.string,
}
export default SidebarPushable
|
server/routers/main.js | ShpuntiK/AnimeStorage | var React = require('react');
var Router = require('react-router');
var DocumentTitle = require('react-document-title');
var api = require('../services/api');
var getInitialData = require('../services/get-initial-data');
var routes = require('../../assets/js/router/routes');
var Layout = require('../views/layout');
function router(req, res) {
var router = Router.create({
routes,
location: req.url,
onAbort(options) {
var {to, params, query} = options;
var destination = router.makePath(to, params, query);
res.redirect(302, destination);
},
onError: function (err) {
console.log('Routing error: ' + err);
}
});
router.run((Handler, state) => {
getInitialData(state).then(data => {
var layout = renderLayout(Handler, data);
res.send(layout);
});
//api.search('bleach').done(function (data) {
// var layout = renderLayout({items: data}, Handler);
// res.send(layout);
//}, function (err) {
// var layout = renderLayout({items: []}, Handler);
// res.send(layout);
//});
});
}
function renderLayout(Handler, data) {
var storesInitialDataScript = 'var storesInitialData = ' + JSON.stringify(data) + ';';
var component = React.renderToString(<Handler storesInitialData={data}/>);
return React.renderToStaticMarkup(
<Layout environment={process.env.NODE_ENV}
title={DocumentTitle.rewind()}
component={component}
storesInitialDataScript={storesInitialDataScript}/>
);
}
module.exports = router; |
examples/browserify-gulp-example/src/app/Main.js | ngbrown/material-ui | /**
* In this file, we create a React component
* which incorporates components providedby material-ui.
*/
import React from 'react';
import RaisedButton from 'material-ui/RaisedButton';
import Dialog from 'material-ui/Dialog';
import {deepOrange500} from 'material-ui/styles/colors';
import FlatButton from 'material-ui/FlatButton';
import getMuiTheme from 'material-ui/styles/getMuiTheme';
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
const styles = {
container: {
textAlign: 'center',
paddingTop: 200,
},
};
const muiTheme = getMuiTheme({
palette: {
accent1Color: deepOrange500,
},
});
class Main extends React.Component {
constructor(props, context) {
super(props, context);
this.handleRequestClose = this.handleRequestClose.bind(this);
this.handleTouchTap = this.handleTouchTap.bind(this);
this.state = {
open: false,
};
}
handleRequestClose() {
this.setState({
open: false,
});
}
handleTouchTap() {
this.setState({
open: true,
});
}
render() {
const standardActions = (
<FlatButton
label="Ok"
secondary={true}
onTouchTap={this.handleRequestClose}
/>
);
return (
<MuiThemeProvider muiTheme={muiTheme}>
<div style={styles.container}>
<Dialog
open={this.state.open}
title="Super Secret Password"
actions={standardActions}
onRequestClose={this.handleRequestClose}
>
1-2-3-4-5
</Dialog>
<h1>material-ui</h1>
<h2>example project</h2>
<RaisedButton
label="Super Secret Password"
primary={true}
onTouchTap={this.handleTouchTap}
/>
</div>
</MuiThemeProvider>
);
}
}
export default Main;
|
src/js/components/Article.js | primozs/grommet | // (C) Copyright 2014-2015 Hewlett Packard Enterprise Development LP
import React, { Component, PropTypes, Children } from 'react';
import {findDOMNode} from 'react-dom';
import Box from './Box';
import KeyboardAccelerators from '../utils/KeyboardAccelerators';
import DOMUtils from '../utils/DOM';
import Props from '../utils/Props';
import Scroll from '../utils/Scroll';
import Responsive from '../utils/Responsive';
// import CarouselControls from './CarouselControls';
import Button from './Button';
import NextIcon from './icons/base/LinkNext';
import PreviousIcon from './icons/base/LinkPrevious';
import UpIcon from './icons/base/Up';
import DownIcon from './icons/base/Down';
import CSSClassnames from '../utils/CSSClassnames';
const CLASS_ROOT = CSSClassnames.ARTICLE;
const DEFAULT_PLAY_INTERVAL = 10000; // 10s
export default class Article extends Component {
constructor(props) {
super(props);
this._onFocusChange = this._onFocusChange.bind(this);
this._onScroll = this._onScroll.bind(this);
this._onWheel = this._onWheel.bind(this);
this._onTouchStart = this._onTouchStart.bind(this);
this._onTouchMove = this._onTouchMove.bind(this);
this._onResize = this._onResize.bind(this);
this._onNext = this._onNext.bind(this);
this._onPrevious = this._onPrevious.bind(this);
this._onTogglePlay = this._onTogglePlay.bind(this);
this._onSelect = this._onSelect.bind(this);
this._checkControls = this._checkControls.bind(this);
this._checkPreviousNextControls = this._checkPreviousNextControls.bind(this);
this._onResponsive = this._onResponsive.bind(this);
this._updateHiddenElements = this._updateHiddenElements.bind(this);
// Necessary to detect for Firefox or Edge to implement accessibility tabbing
const accessibilityTabbingCompatible = typeof navigator !== 'undefined' && navigator.userAgent.indexOf("Firefox") === -1 && navigator.userAgent.indexOf("Edge") === -1;
this.state = {
selectedIndex: props.selected || 0,
playing: false,
showControls: this.props.controls,
accessibilityTabbingCompatible: accessibilityTabbingCompatible
};
}
componentDidMount () {
if (this.props.scrollStep) {
this._keys = {up: this._onPrevious, down: this._onNext};
if ('row' === this.props.direction) {
this._keys = {
left: this._onPrevious,
right: this._onNext
};
if (this.state.accessibilityTabbingCompatible) {
this._updateHiddenElements();
}
}
//keys.space = this._onTogglePlay;
KeyboardAccelerators.startListeningToKeyboard(this, this._keys);
document.addEventListener('wheel', this._onWheel);
window.addEventListener('resize', this._onResize);
this._scrollParent = findDOMNode(this.refs.component);
this._checkControls();
if ('row' === this.props.direction && this.props.scrollStep) {
this._responsive = Responsive.start(this._onResponsive);
}
}
this._onSelect(this.state.selectedIndex);
}
componentWillReceiveProps (nextProps) {
// allow updates to selected props to trigger new chapter select
if ((typeof nextProps.selected !== 'undefined') && (nextProps.selected !== null) && (nextProps.selected !== this.state.selectedIndex)) {
this._onSelect(nextProps.selected);
}
}
componentWillUnmount () {
if (this.props.scrollStep) {
KeyboardAccelerators.stopListeningToKeyboard(this, this._keys);
document.removeEventListener('wheel', this._onWheel);
window.removeEventListener('resize', this._onResize);
}
if (this._responsive) {
this._responsive.stop();
}
}
_checkPreviousNextControls (currentScroll, nextProp, prevProp) {
if (currentScroll > 0) {
const nextStepNode = findDOMNode(
this.refs[this.state.selectedIndex + 1]
);
const previousStepNode = findDOMNode(
this.refs[this.state.selectedIndex - 1]
);
if (nextStepNode) {
const nextStepPosition = (
nextStepNode.getBoundingClientRect()[nextProp]
) * (this.state.selectedIndex + 1);
if (currentScroll > nextStepPosition) {
this.setState({selectedIndex: this.state.selectedIndex + 1});
}
}
if (previousStepNode) {
const previousStepPosition = (
previousStepNode.getBoundingClientRect()[prevProp]
) * this.state.selectedIndex;
if (currentScroll < previousStepPosition) {
this.setState({selectedIndex: this.state.selectedIndex - 1});
}
}
}
}
_checkControls () {
if (this.props.direction === 'row') {
const currentScroll = this.refs.component.refs.boxContainer.scrollLeft;
this._checkPreviousNextControls(currentScroll, 'left', 'right');
} else {
const currentScroll = this.refs.component.refs.boxContainer.scrollTop;
this._checkPreviousNextControls(currentScroll, 'top', 'bottom');
}
}
_visibleIndexes () {
const { children, direction } = this.props;
let result = [];
const childCount = React.Children.count(children);
const limit = ('row' === direction) ? window.innerWidth : window.innerHeight;
for (let index = 0; index < childCount; index += 1) {
const childElement = findDOMNode(this.refs[index]);
const rect = childElement.getBoundingClientRect();
// ignore small drifts of 10 pixels on either end
if ('row' === direction) {
if (rect.right > 10 && rect.left < (limit - 10)) {
result.push(index);
} else if (result.length > 0) {
break;
}
} else {
if (rect.bottom > 10 && rect.top < (limit - 10)) {
result.push(index);
} else if (result.length > 0) {
break;
}
}
}
return result;
}
_shortTimer (name, duration) {
if (! this[name]) {
this[name] = true;
}
const timerName = `${this[name]}Timer`;
clearTimeout(this[timerName]);
this[timerName] = setTimeout(() => {
this[name] = false;
}, duration);
}
_onWheel (event) {
if ('row' === this.props.direction) {
if (this._scrollingHorizontally) {
// no-op
} else if (! this._scrollingVertically) {
if (Math.abs(event.deltaY * 2) > Math.abs(event.deltaX)) {
// user is scrolling vertically
this._shortTimer('_scrollingVertically', 1000);
}
}
} else {
// Give the user lots of control.
const delta = event.deltaY;
if (Math.abs(delta) > 100) {
// The user is expressing a resolute interest in controlling the
// scrolling behavior. Stop doing any of our scroll step aligning
// until he stops expressing such interest.
clearInterval(this._wheelTimer);
clearInterval(this._wheelLongTimer);
this._wheelLongTimer = setTimeout(() => {
this._wheelLongTimer = null;
}, 2000);
} else if (! this._wheelLongTimer) {
if (delta > 10) {
clearInterval(this._wheelTimer);
this._wheelTimer = setTimeout(this._onNext, 200);
} else if (delta < -10) {
clearInterval(this._wheelTimer);
this._wheelTimer = setTimeout(this._onPrevious, 200);
} else {
clearInterval(this._controlTimer);
this._controlTimer = setTimeout(this._checkControls, 200);
}
}
}
}
_onScroll (event) {
if ('row' === this.props.direction) {
const { selectedIndex } = this.state;
const childElement = findDOMNode(this.refs[selectedIndex]);
let rect = childElement.getBoundingClientRect();
if (event.target === this._scrollParent) {
// scrolling Article
if (this._scrollingVertically) {
// prevent Article horizontal scrolling while scrolling vertically
this._scrollParent.scrollLeft += rect.left;
} else {
const scrollingRight = this._priorScrollLeft < this._scrollParent.scrollLeft;
// once we stop scrolling, align with child boundaries
clearTimeout(this._scrollTimer);
this._scrollTimer = setTimeout(() => {
if (! this._resizing) {
const indexes = this._visibleIndexes();
if (indexes.length > 1 && scrollingRight) {
this._onSelect(indexes[1]);
} else {
this._onSelect(indexes[0]);
}
}
}, 100);
this._priorScrollLeft = this._scrollParent.scrollLeft;
}
} else if (event.target.parentNode === this._scrollParent) {
// scrolling child
// Has it scrolled near the bottom?
if (this.state.accessibilityTabbingCompatible) {
// only use lastGrandChild logic if we're not using Firefox or IE.
// causes flashing in Firefox, but required for Safari scrolling.
const grandchildren = event.target.children;
const lastGrandChild = grandchildren[grandchildren.length - 1];
rect = lastGrandChild.getBoundingClientRect();
}
if (rect.bottom <= (window.innerHeight + 24)) {
// at the bottom
this.setState({ atBottom: true });
} else {
// not at the bottom
this.setState({ atBottom: false });
}
}
}
}
_onTouchStart (event) {
const touched = event.changedTouches[0];
this._touchStartX = touched.clientX;
this._touchStartY = touched.clientY;
}
_onTouchMove (event) {
if (! this.state.ignoreScroll) {
const touched = event.changedTouches[0];
const deltaX = touched.clientX - this._touchStartX;
const deltaY = touched.clientY - this._touchStartY;
// Only step if the user isn't scrolling vertically, bias vertically
if (Math.abs(deltaY) < Math.abs(deltaX * 2)) {
if (deltaX < 0) {
this._onNext();
} else {
this._onPrevious();
}
}
}
}
_onResize () {
clearTimeout(this._resizeTimer);
this._resizeTimer = setTimeout(() => {
this._onSelect(this.state.selectedIndex);
this._shortTimer('_resizing', 1000);
}, 50);
}
_onNext (event, wrap) {
// only process if the focus is NOT in a form element
if (!DOMUtils.isFormElement(document.activeElement)) {
const { children } = this.props;
const { selectedIndex } = this.state;
const childCount = React.Children.count(children);
if (event) {
this._stop();
event.preventDefault();
}
const targetIndex = this._visibleIndexes()[0] + 1;
if (targetIndex !== selectedIndex) {
if (targetIndex < childCount) {
this._onSelect(Math.min(childCount - 1, targetIndex));
} else if (wrap) {
this._onSelect(1);
}
}
}
}
_onPrevious (event) {
// only process if the focus is NOT in a form element
if (!DOMUtils.isFormElement(document.activeElement)) {
const { selectedIndex } = this.state;
if (event) {
this._stop();
event.preventDefault();
}
const targetIndex = this._visibleIndexes()[0] - 1;
if (targetIndex !== selectedIndex) {
this._onSelect(Math.max(0, targetIndex));
}
}
}
_start () {
this._playTimer = setInterval(() => {
this._onNext(null, true);
}, DEFAULT_PLAY_INTERVAL);
this.setState({playing: true});
}
_stop () {
clearInterval(this._playTimer);
this.setState({playing: false});
}
_onTogglePlay (event) {
event.preventDefault();
if (this.state.playing) {
this._stop();
} else {
this._start();
}
}
_onSelect (selectedIndex) {
const childElement = findDOMNode(this.refs[selectedIndex]);
const windowHeight = window.innerHeight + 24;
if (childElement) {
const parentElement = childElement.parentNode;
const atBottom = (Math.round(parentElement.scrollTop) >= parentElement.scrollHeight - parentElement.clientHeight);
if (selectedIndex !== this.state.selectedIndex) {
// scroll child to top
childElement.scrollTop = 0;
// ensures controls are displayed when selecting a new index and
// scrollbar is at bottom of article
this.setState({
selectedIndex: selectedIndex,
atBottom: atBottom
}, () => {
if (this.props.onSelect) {
this.props.onSelect(selectedIndex);
}
// Necessary to detect for Firefox or Edge to implement accessibility tabbing
if (this.props.direction === 'row' && this.state.accessibilityTabbingCompatible) {
this.refs.anchorStep.focus();
this._updateHiddenElements();
}
});
} else if (childElement.scrollHeight <= windowHeight) {
// on initial chapter load, ensure arrows are rendered
// when there are no scrollbars
this.setState({ atBottom: true });
}
const rect = childElement.getBoundingClientRect();
if ('row' === this.props.direction) {
if (rect.left !== 0) {
this._scrollingHorizontally = true;
Scroll.scrollBy(this._scrollParent, 'scrollLeft', rect.left, () => {
this._scrollingHorizontally = false;
});
}
} else {
if (rect.top !== 0) {
this._scrollingVertically = true;
Scroll.scrollBy(this._scrollParent, 'scrollTop', rect.top, () => {
this._scrollingVertically = false;
});
}
}
}
}
_onFocusChange (e) {
React.Children.forEach(this.props.children, (element, index) => {
let parent = findDOMNode(this.refs[index]);
if (parent && parent.contains(e.target)) {
this._onSelect(index);
return false;
}
});
}
_onResponsive (small) {
this.setState({ narrow: small });
}
_toggleDisableChapter (chapter, disabled) {
const elements = DOMUtils.filterByFocusable(
chapter.getElementsByTagName('*')
);
if (elements) {
elements.forEach((element) => {
if (disabled) {
element.setAttribute('disabled', 'disabled');
} else {
element.removeAttribute('disabled');
}
element.setAttribute('tabindex', disabled ? '-1' : '0');
});
}
}
_updateHiddenElements () {
const component = findDOMNode(this.refs.component);
const children = component.children;
for (let i = 0; i < children.length; i++) {
const child = children[i];
if (child.getAttribute('aria-hidden')) {
this._toggleDisableChapter(child, true);
} else {
this._toggleDisableChapter(child, false);
}
}
}
_renderControls () {
const CONTROL_CLASS_PREFIX =
`${CLASS_ROOT}__control ${CLASS_ROOT}__control`;
const childCount = React.Children.count(this.props.children);
let controls = [
// Don't use CarouselControls for now
// <CarouselControls key="carousel"
// className={CONTROL_CLASS_PREFIX + "carousel"}
// count={childCount}
// direction={this.props.direction}
// selected={this.state.selectedIndex} onChange={this._onSelect} />
];
const a11yTitle = this.props.a11yTitle || {};
if ('row' === this.props.direction) {
if (! this.state.narrow || this.state.atBottom) {
if (this.state.selectedIndex > 0) {
controls.push(
<Button key="previous" ref='previous'
plain={true} a11yTitle={a11yTitle.previous}
className={`${CONTROL_CLASS_PREFIX}-left`}
onClick={this._onPrevious} icon={<PreviousIcon
a11yTitle='article-previous-title'
a11yTitleId='article-previous-title-id'
size="large" />
} />
);
}
if (this.state.selectedIndex < (childCount - 1)) {
controls.push(
<Button key="next" ref='next'
plain={true} a11yTitle={a11yTitle.next}
className={`${CONTROL_CLASS_PREFIX}-right`}
onClick={this._onNext} icon={<NextIcon size="large"
a11yTitle='article-next-title'
a11yTitleId='article-next-title-id' />
} />
);
}
}
} else {
if (this.state.selectedIndex > 0) {
controls.push(
<Button key="previous" ref='previous'
plain={true} a11yTitle={a11yTitle.previous}
className={`${CONTROL_CLASS_PREFIX}-up`}
onClick={this._onPrevious}><UpIcon /></Button>
);
}
if (this.state.selectedIndex < (childCount - 1)) {
controls.push(
<Button key="next" ref='next' plain={true} a11yTitle={a11yTitle.next}
className={`${CONTROL_CLASS_PREFIX}-down`}
onClick={this._onNext}><DownIcon a11yTitle='article-down'
a11yTitleId='article-down-id' /></Button>
);
}
}
return controls;
}
render () {
let classes = [CLASS_ROOT];
const boxProps = Props.pick(this.props, Object.keys(Box.propTypes));
const restProps = Props.omit(this.props, Object.keys(Article.propTypes));
if (this.props.scrollStep) {
classes.push(`${CLASS_ROOT}--scroll-step`);
}
if (this.props.className) {
classes.push(this.props.className);
}
let controls;
if (this.props.controls) {
controls = this._renderControls();
}
let anchorStepNode;
if (this.state.accessibilityTabbingCompatible) {
anchorStepNode = (
<a tabIndex="-1" aria-hidden='true' ref='anchorStep' />
);
}
let children = this.props.children;
if (this.props.scrollStep || this.props.controls) {
children = Children.map(this.props.children, (element, index) => {
if (element) {
const elementClone = React.cloneElement(element, {
ref: index
});
let elementNode = elementClone;
let ariaHidden;
if (this.state.selectedIndex !== index && this.state.accessibilityTabbingCompatible) {
ariaHidden = 'true';
}
if (this.props.controls) {
elementNode = (
<div aria-hidden={ariaHidden}>
{elementClone}
</div>
);
}
return elementNode;
}
return undefined;
}, this);
}
delete boxProps.a11yTitle;
return (
<Box {...restProps} {...boxProps} ref="component" tag="article"
className={classes.join(' ')} onFocus={this._onFocusChange}
onScroll={this._onScroll} onTouchStart={this._onTouchStart}
onTouchMove={this._onTouchMove} primary={this.props.primary}>
{anchorStepNode}
{children}
{controls}
</Box>
);
}
}
Article.propTypes = {
controls: PropTypes.bool,
primary: PropTypes.bool,
scrollStep: PropTypes.bool,
...Box.propTypes,
a11yTitle: PropTypes.shape({
next: PropTypes.string,
previous: PropTypes.string
}),
onSelect: PropTypes.func,
selected: PropTypes.number
};
Article.defaultProps = {
pad: 'none',
direction: 'column'
};
|
src/App.js | battaile/time-tracking | import React, { Component } from 'react';
import ReactDOM from 'react-dom';
import Project from './Project';
import AddProject from './AddProject';
import Footer from './Footer';
import ErrorBoundary from './ErrorBoundary';
import * as db from './database';
import { appName } from './constants';
import './App.css';
export const renderApp = () => {
ReactDOM.render(<App />, document.getElementById('root'));
db.update(appName, window.state);
};
class App extends Component {
render() {
if (!window.state) {
window.state = {};
}
return (
<ErrorBoundary>
<div className="App">
<div>
{window.state.projects &&
window.state.projects.map(p => (
<Project key={p.name} project={p} refresh={renderApp} />
))}
</div>
<AddProject refresh={renderApp} />
<Footer />
</div>
</ErrorBoundary>
);
}
}
export default App;
|
desktop-site/components/ServiceStopped.js | goominc/goommerce-react | // Copyright (C) 2016 Goom Inc. All rights reserved.
import React from 'react';
import { constants } from 'commons/utils/constants';
export default React.createClass({
render() {
return (
<div className="service-stopped-container">
<img src={`${constants.resourceRoot}/banner/service_stopped_160428.jpg`} />
</div>
);
},
});
|
src/views/hr-view/components/experience-section.js | vynogradskyi/resume | import React from 'react';
import classnames from 'classnames';
import styles from 'css-modules/hr-view/experience-section.scss';
//components
import Ul from './ul';
export default ({item}) => {
return (
<div className={styles.item}>
<div className={styles.vertical}/>
<div className={styles.content}>
<h5 className={styles.title}>{item.position}</h5>
<span
className={classnames(styles.info, 'text-grey')}>{`${item.company} / ${item.city} / ${item.date}`}</span>
<p className={styles.text}>{item.description}</p>
<Ul points={item.points}/>
</div>
</div>
);
} |
src/components/Dna-Strand.js | justrdk/glowing-bassoon | import React from 'react';
const DnaStrand = ({ dnas, addDna, validateDna, clearDnas }) => {
let input;
const validateDnas = () => {
dnas.forEach((dna, index) => {
validateDna(dna, index);
});
}
return (
<div style={{marginTop: 10}}>
<div className="ui form">
<div className="two fields">
<div className="field">
<div className="ui labeled input">
<div className="ui label">DNA Strand:</div>
<input type="text" ref={node => { input = node }} placeholder="Type DNA Strand here..." />
</div>
</div>
</div>
<div className="ui positive button" onClick={() => addDna(input.value)}>Add DNA</div>
<div className="ui primary button" onClick={() => validateDnas()}>Validate DNAS</div>
<div className="ui primary button" onClick={() => clearDnas()}>Clear DNAS</div>
</div>
<table className="ui celled single line fixed table">
<thead>
<tr>
<th>DNA</th>
<th>Valid</th>
</tr>
{dnas.map((dna, index) => {
return (<tr key={index}>
<td>{dna.dna}</td>
<td>{dna.valid ? 'YES': 'NO'}</td>
</tr>)
})}
</thead>
</table>
</div>
);
};
export default DnaStrand;
|
examples/todos-with-undo/src/components/Footer.js | bvasko/redux | import React from 'react'
import FilterLink from '../containers/FilterLink'
const Footer = () => (
<p>
Show:
{" "}
<FilterLink filter="SHOW_ALL">
All
</FilterLink>
{", "}
<FilterLink filter="SHOW_ACTIVE">
Active
</FilterLink>
{", "}
<FilterLink filter="SHOW_COMPLETED">
Completed
</FilterLink>
</p>
)
export default Footer
|
src/NavItem.js | cgvarela/react-bootstrap | import React from 'react';
import classNames from 'classnames';
import BootstrapMixin from './BootstrapMixin';
import SafeAnchor from './SafeAnchor';
const NavItem = React.createClass({
mixins: [BootstrapMixin],
propTypes: {
linkId: React.PropTypes.string,
onSelect: React.PropTypes.func,
active: React.PropTypes.bool,
disabled: React.PropTypes.bool,
href: React.PropTypes.string,
role: React.PropTypes.string,
title: React.PropTypes.node,
eventKey: React.PropTypes.any,
target: React.PropTypes.string,
'aria-controls': React.PropTypes.string
},
getDefaultProps() {
return {
active: false,
disabled: false
};
},
render() {
let {
role,
linkId,
disabled,
active,
href,
title,
target,
children,
tabIndex, //eslint-disable-line
'aria-controls': ariaControls,
...props } = this.props;
let classes = {
active,
disabled
};
let linkProps = {
role,
href,
title,
target,
tabIndex,
id: linkId,
onClick: this.handleClick
};
if (!role && href === '#') {
linkProps.role = 'button';
}
return (
<li {...props} role="presentation" className={classNames(props.className, classes)}>
<SafeAnchor {...linkProps} aria-selected={active} aria-controls={ariaControls}>
{ children }
</SafeAnchor>
</li>
);
},
handleClick(e) {
if (this.props.onSelect) {
e.preventDefault();
if (!this.props.disabled) {
this.props.onSelect(this.props.eventKey, this.props.href, this.props.target);
}
}
}
});
export default NavItem;
|
client/app/components/Layout/Header.js | ngenerio/unredis | import React, { Component } from 'react';
export default class Header extends Component {
render () {
return (
<nav className="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div className="container-fluid">
<div className="navbar-header">
<button type="button" className="navbar-toggle collapsed" data-toggle="collapse" data-target="#sidebar-collapse">
<span className="sr-only">Toggle navigation</span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
<span className="icon-bar"></span>
</button>
<a className="navbar-brand" href="#"><span>Un</span>Redis</a>
</div>
</div>
</nav>
);
}
}
|
client/components/bulk-select/test/index.js | allendav/wp-calypso | /**
* External dependencies
*/
import { assert } from 'chai';
import React from 'react';
import { shallow } from 'enzyme';
import noop from 'lodash/noop';
/**
* Internal dependencies
*/
import BulkSelect from '../index';
describe( 'index', function() {
require( 'test/helpers/use-fake-dom' )();
it( 'should have BulkSelect class', function() {
const bulkSelect = shallow( <BulkSelect selectedElements={ 0 } totalElements={ 3 } onToggle={ noop } /> );
assert.equal( 1, bulkSelect.find( '.bulk-select' ).length );
} );
it( 'should not be checked when initialized without selectedElements', function() {
const bulkSelect = shallow( <BulkSelect selectedElements={ 0 } totalElements={ 3 } onToggle={ noop } /> );
assert.equal( 0, bulkSelect.find( '.is-checked' ).length );
} );
it( 'should be checked when initialized with all elements selected', function() {
const bulkSelect = shallow( <BulkSelect selectedElements={ 3 } totalElements={ 3 } onToggle={ noop } /> );
assert.equal( 1, bulkSelect.find( '.is-checked' ).length );
} );
it( 'should not be checked when initialized with some elements selected', function() {
const bulkSelect = shallow( <BulkSelect selectedElements={ 2 } totalElements={ 3 } onToggle={ noop } /> );
assert.equal( 0, bulkSelect.find( '.is-checked' ).length );
} );
it( 'should render line gridicon when initialized with some elements selected', function() {
const bulkSelect = shallow( <BulkSelect selectedElements={ 2 } totalElements={ 3 } onToggle={ noop } /> );
assert.equal( 1, bulkSelect.find( '.bulk-select__some-checked-icon' ).length );
} );
it( 'should be call onToggle when clicked', function() {
let hasBeenCalled = false;
const callback = function() {
hasBeenCalled = true;
};
const bulkSelect = shallow( <BulkSelect selectedElements={ 0 } totalElements={ 3 } onToggle={ callback } /> );
bulkSelect.simulate( 'click' );
assert.equal( hasBeenCalled, true );
} );
it( 'should be call onToggle with the new state when there are no selected elements', function( done ) {
const callback = function( newState ) {
assert.equal( newState, true );
done();
};
const bulkSelect = shallow( <BulkSelect selectedElements={ 0 } totalElements={ 3 } onToggle={ callback } /> );
bulkSelect.simulate( 'click' );
} );
it( 'should be call onToggle with the new state when there are some selected elements', function( done ) {
const callback = function( newState ) {
assert.equal( newState, false );
done();
};
const bulkSelect = shallow( <BulkSelect selectedElements={ 1 } totalElements={ 3 } onToggle={ callback } /> );
bulkSelect.simulate( 'click' );
} );
it( 'should be call onToggle with the new state when there all elements are selected', function( done ) {
const callback = function( newState ) {
assert.equal( newState, false );
done();
};
const bulkSelect = shallow( <BulkSelect selectedElements={ 3 } totalElements={ 3 } onToggle={ callback } /> );
bulkSelect.simulate( 'click' );
} );
} );
|
app/renderer/containers/OutfittingPage/index.js | project-sothis/project-sothis | import React, { Component } from 'react'
// import { bindActionCreators } from 'redux'
import { connect } from 'react-redux'
import autoBind from 'react-autobind'
import { Link } from 'react-router'
// import styles from './styles.scss'
class OutfittingPage extends Component {
constructor (props) {
super(props)
autoBind(this)
}
render () {
return (
<div>
<h1>Outfitting</h1>
<p><Link to='/'>Back to home</Link></p>
</div>
)
}
}
function mapStateToProps (state) {
return {
//
}
}
function mapDispatchToProps (dispatch) {
return {
//
}
}
export default connect(mapStateToProps, mapDispatchToProps)(OutfittingPage)
|
ajax/libs/bla/1.1.0/bla.js | maruilian11/cdnjs | /**
* @module vow
* @author Filatov Dmitry <[email protected]>
* @version 0.4.6
* @license
* Dual licensed under the MIT and GPL licenses:
* * http://www.opensource.org/licenses/mit-license.php
* * http://www.gnu.org/licenses/gpl.html
*/
(function(global) {
/**
* @class Deferred
* @exports vow:Deferred
* @description
* The `Deferred` class is used to encapsulate newly-created promise object along with functions that resolve, reject or notify it.
*/
/**
* @constructor
* @description
* You can use `vow.defer()` instead of using this constructor.
*
* `new vow.Deferred()` gives the same result as `vow.defer()`.
*/
var Deferred = function() {
this._promise = new Promise();
};
Deferred.prototype = /** @lends Deferred.prototype */{
/**
* Returns corresponding promise.
*
* @returns {vow:Promise}
*/
promise : function() {
return this._promise;
},
/**
* Resolves corresponding promise with given `value`.
*
* @param {*} value
*
* @example
* ```js
* var defer = vow.defer(),
* promise = defer.promise();
*
* promise.then(function(value) {
* // value is "'success'" here
* });
*
* defer.resolve('success');
* ```
*/
resolve : function(value) {
this._promise.isResolved() || this._promise._resolve(value);
},
/**
* Rejects corresponding promise with given `reason`.
*
* @param {*} reason
*
* @example
* ```js
* var defer = vow.defer(),
* promise = defer.promise();
*
* promise.fail(function(reason) {
* // reason is "'something is wrong'" here
* });
*
* defer.reject('something is wrong');
* ```
*/
reject : function(reason) {
if(this._promise.isResolved()) {
return;
}
if(vow.isPromise(reason)) {
reason = reason.then(function(val) {
var defer = vow.defer();
defer.reject(val);
return defer.promise();
});
this._promise._resolve(reason);
}
else {
this._promise._reject(reason);
}
},
/**
* Notifies corresponding promise with given `value`.
*
* @param {*} value
*
* @example
* ```js
* var defer = vow.defer(),
* promise = defer.promise();
*
* promise.progress(function(value) {
* // value is "'20%'", "'40%'" here
* });
*
* defer.notify('20%');
* defer.notify('40%');
* ```
*/
notify : function(value) {
this._promise.isResolved() || this._promise._notify(value);
}
};
var PROMISE_STATUS = {
PENDING : 0,
RESOLVED : 1,
FULFILLED : 2,
REJECTED : 3
};
/**
* @class Promise
* @exports vow:Promise
* @description
* The `Promise` class is used when you want to give to the caller something to subscribe to,
* but not the ability to resolve or reject the deferred.
*/
/**
* @constructor
* @param {Function} resolver See https://github.com/domenic/promises-unwrapping/blob/master/README.md#the-promise-constructor for details.
* @description
* You should use this constructor directly only if you are going to use `vow` as DOM Promises implementation.
* In other case you should use `vow.defer()` and `defer.promise()` methods.
* @example
* ```js
* function fetchJSON(url) {
* return new vow.Promise(function(resolve, reject, notify) {
* var xhr = new XMLHttpRequest();
* xhr.open('GET', url);
* xhr.responseType = 'json';
* xhr.send();
* xhr.onload = function() {
* if(xhr.response) {
* resolve(xhr.response);
* }
* else {
* reject(new TypeError());
* }
* };
* });
* }
* ```
*/
var Promise = function(resolver) {
this._value = undef;
this._status = PROMISE_STATUS.PENDING;
this._fulfilledCallbacks = [];
this._rejectedCallbacks = [];
this._progressCallbacks = [];
if(resolver) { // NOTE: see https://github.com/domenic/promises-unwrapping/blob/master/README.md
var _this = this,
resolverFnLen = resolver.length;
resolver(
function(val) {
_this.isResolved() || _this._resolve(val);
},
resolverFnLen > 1?
function(reason) {
_this.isResolved() || _this._reject(reason);
} :
undef,
resolverFnLen > 2?
function(val) {
_this.isResolved() || _this._notify(val);
} :
undef);
}
};
Promise.prototype = /** @lends Promise.prototype */ {
/**
* Returns value of fulfilled promise or reason in case of rejection.
*
* @returns {*}
*/
valueOf : function() {
return this._value;
},
/**
* Returns `true` if promise is resolved.
*
* @returns {Boolean}
*/
isResolved : function() {
return this._status !== PROMISE_STATUS.PENDING;
},
/**
* Returns `true` if promise is fulfilled.
*
* @returns {Boolean}
*/
isFulfilled : function() {
return this._status === PROMISE_STATUS.FULFILLED;
},
/**
* Returns `true` if promise is rejected.
*
* @returns {Boolean}
*/
isRejected : function() {
return this._status === PROMISE_STATUS.REJECTED;
},
/**
* Adds reactions to promise.
*
* @param {Function} [onFulfilled] Callback that will to be invoked with the value after promise has been fulfilled
* @param {Function} [onRejected] Callback that will to be invoked with the reason after promise has been rejected
* @param {Function} [onProgress] Callback that will to be invoked with the value after promise has been notified
* @param {Object} [ctx] Context of callbacks execution
* @returns {vow:Promise} A new promise, see https://github.com/promises-aplus/promises-spec for details
*/
then : function(onFulfilled, onRejected, onProgress, ctx) {
var defer = new Deferred();
this._addCallbacks(defer, onFulfilled, onRejected, onProgress, ctx);
return defer.promise();
},
/**
* Adds rejection reaction only. It is shortcut for `promise.then(undefined, onRejected)`.
*
* @param {Function} onRejected Callback to be called with the value after promise has been rejected
* @param {Object} [ctx] Context of callback execution
* @returns {vow:Promise}
*/
'catch' : function(onRejected, ctx) {
return this.then(undef, onRejected, ctx);
},
/**
* Adds rejection reaction only. It is shortcut for `promise.then(null, onRejected)`. It's alias for `catch`.
*
* @param {Function} onRejected Callback to be called with the value after promise has been rejected
* @param {Object} [ctx] Context of callback execution
* @returns {vow:Promise}
*/
fail : function(onRejected, ctx) {
return this.then(undef, onRejected, ctx);
},
/**
* Adds resolving reaction (to fulfillment and rejection both).
*
* @param {Function} onResolved Callback that to be called with the value after promise has been rejected
* @param {Object} [ctx] Context of callback execution
* @returns {vow:Promise}
*/
always : function(onResolved, ctx) {
var _this = this,
cb = function() {
return onResolved.call(this, _this);
};
return this.then(cb, cb, ctx);
},
/**
* Adds progress reaction.
*
* @param {Function} onProgress Callback to be called with the value when promise has been notified
* @param {Object} [ctx] Context of callback execution
* @returns {vow:Promise}
*/
progress : function(onProgress, ctx) {
return this.then(undef, undef, onProgress, ctx);
},
/**
* Like `promise.then`, but "spreads" the array into a variadic value handler.
* It is useful with `vow.all` and `vow.allResolved` methods.
*
* @param {Function} [onFulfilled] Callback that will to be invoked with the value after promise has been fulfilled
* @param {Function} [onRejected] Callback that will to be invoked with the reason after promise has been rejected
* @param {Object} [ctx] Context of callbacks execution
* @returns {vow:Promise}
*
* @example
* ```js
* var defer1 = vow.defer(),
* defer2 = vow.defer();
*
* vow.all([defer1.promise(), defer2.promise()]).spread(function(arg1, arg2) {
* // arg1 is "1", arg2 is "'two'" here
* });
*
* defer1.resolve(1);
* defer2.resolve('two');
* ```
*/
spread : function(onFulfilled, onRejected, ctx) {
return this.then(
function(val) {
return onFulfilled.apply(this, val);
},
onRejected,
ctx);
},
/**
* Like `then`, but terminates a chain of promises.
* If the promise has been rejected, throws it as an exception in a future turn of the event loop.
*
* @param {Function} [onFulfilled] Callback that will to be invoked with the value after promise has been fulfilled
* @param {Function} [onRejected] Callback that will to be invoked with the reason after promise has been rejected
* @param {Function} [onProgress] Callback that will to be invoked with the value after promise has been notified
* @param {Object} [ctx] Context of callbacks execution
*
* @example
* ```js
* var defer = vow.defer();
* defer.reject(Error('Internal error'));
* defer.promise().done(); // exception to be thrown
* ```
*/
done : function(onFulfilled, onRejected, onProgress, ctx) {
this
.then(onFulfilled, onRejected, onProgress, ctx)
.fail(throwException);
},
/**
* Returns a new promise that will be fulfilled in `delay` milliseconds if the promise is fulfilled,
* or immediately rejected if promise is rejected.
*
* @param {Number} delay
* @returns {vow:Promise}
*/
delay : function(delay) {
var timer,
promise = this.then(function(val) {
var defer = new Deferred();
timer = setTimeout(
function() {
defer.resolve(val);
},
delay);
return defer.promise();
});
promise.always(function() {
clearTimeout(timer);
});
return promise;
},
/**
* Returns a new promise that will be rejected in `timeout` milliseconds
* if the promise is not resolved beforehand.
*
* @param {Number} timeout
* @returns {vow:Promise}
*
* @example
* ```js
* var defer = vow.defer(),
* promiseWithTimeout1 = defer.promise().timeout(50),
* promiseWithTimeout2 = defer.promise().timeout(200);
*
* setTimeout(
* function() {
* defer.resolve('ok');
* },
* 100);
*
* promiseWithTimeout1.fail(function(reason) {
* // promiseWithTimeout to be rejected in 50ms
* });
*
* promiseWithTimeout2.then(function(value) {
* // promiseWithTimeout to be fulfilled with "'ok'" value
* });
* ```
*/
timeout : function(timeout) {
var defer = new Deferred(),
timer = setTimeout(
function() {
defer.reject(Error('timed out'));
},
timeout);
this.then(
function(val) {
defer.resolve(val);
},
function(reason) {
defer.reject(reason);
});
defer.promise().always(function() {
clearTimeout(timer);
});
return defer.promise();
},
_vow : true,
_resolve : function(val) {
if(this._status > PROMISE_STATUS.RESOLVED) {
return;
}
if(val === this) {
this._reject(TypeError('Can\'t resolve promise with itself'));
return;
}
this._status = PROMISE_STATUS.RESOLVED;
if(val && !!val._vow) { // shortpath for vow.Promise
val.isFulfilled()?
this._fulfill(val.valueOf()) :
val.isRejected()?
this._reject(val.valueOf()) :
val.then(
this._fulfill,
this._reject,
this._notify,
this);
return;
}
if(isObject(val) || isFunction(val)) {
var then;
try {
then = val.then;
}
catch(e) {
this._reject(e);
return;
}
if(isFunction(then)) {
var _this = this,
isResolved = false;
try {
then.call(
val,
function(val) {
if(isResolved) {
return;
}
isResolved = true;
_this._resolve(val);
},
function(err) {
if(isResolved) {
return;
}
isResolved = true;
_this._reject(err);
},
function(val) {
_this._notify(val);
});
}
catch(e) {
isResolved || this._reject(e);
}
return;
}
}
this._fulfill(val);
},
_fulfill : function(val) {
if(this._status > PROMISE_STATUS.RESOLVED) {
return;
}
this._status = PROMISE_STATUS.FULFILLED;
this._value = val;
this._callCallbacks(this._fulfilledCallbacks, val);
this._fulfilledCallbacks = this._rejectedCallbacks = this._progressCallbacks = undef;
},
_reject : function(reason) {
if(this._status > PROMISE_STATUS.RESOLVED) {
return;
}
this._status = PROMISE_STATUS.REJECTED;
this._value = reason;
this._callCallbacks(this._rejectedCallbacks, reason);
this._fulfilledCallbacks = this._rejectedCallbacks = this._progressCallbacks = undef;
},
_notify : function(val) {
this._callCallbacks(this._progressCallbacks, val);
},
_addCallbacks : function(defer, onFulfilled, onRejected, onProgress, ctx) {
if(onRejected && !isFunction(onRejected)) {
ctx = onRejected;
onRejected = undef;
}
else if(onProgress && !isFunction(onProgress)) {
ctx = onProgress;
onProgress = undef;
}
var cb;
if(!this.isRejected()) {
cb = { defer : defer, fn : isFunction(onFulfilled)? onFulfilled : undef, ctx : ctx };
this.isFulfilled()?
this._callCallbacks([cb], this._value) :
this._fulfilledCallbacks.push(cb);
}
if(!this.isFulfilled()) {
cb = { defer : defer, fn : onRejected, ctx : ctx };
this.isRejected()?
this._callCallbacks([cb], this._value) :
this._rejectedCallbacks.push(cb);
}
if(this._status <= PROMISE_STATUS.RESOLVED) {
this._progressCallbacks.push({ defer : defer, fn : onProgress, ctx : ctx });
}
},
_callCallbacks : function(callbacks, arg) {
var len = callbacks.length;
if(!len) {
return;
}
var isResolved = this.isResolved(),
isFulfilled = this.isFulfilled();
nextTick(function() {
var i = 0, cb, defer, fn;
while(i < len) {
cb = callbacks[i++];
defer = cb.defer;
fn = cb.fn;
if(fn) {
var ctx = cb.ctx,
res;
try {
res = ctx? fn.call(ctx, arg) : fn(arg);
}
catch(e) {
defer.reject(e);
continue;
}
isResolved?
defer.resolve(res) :
defer.notify(res);
}
else {
isResolved?
isFulfilled?
defer.resolve(arg) :
defer.reject(arg) :
defer.notify(arg);
}
}
});
}
};
/** @lends Promise */
var staticMethods = {
/**
* Coerces given `value` to a promise, or returns the `value` if it's already a promise.
*
* @param {*} value
* @returns {vow:Promise}
*/
cast : function(value) {
return vow.cast(value);
},
/**
* Returns a promise to be fulfilled only after all the items in `iterable` are fulfilled,
* or to be rejected when any of the `iterable` is rejected.
*
* @param {Array|Object} iterable
* @returns {vow:Promise}
*/
all : function(iterable) {
return vow.all(iterable);
},
/**
* Returns a promise to be fulfilled only when any of the items in `iterable` are fulfilled,
* or to be rejected when the first item is rejected.
*
* @param {Array} iterable
* @returns {vow:Promise}
*/
race : function(iterable) {
return vow.anyResolved(iterable);
},
/**
* Returns a promise that has already been resolved with the given `value`.
* If `value` is a promise, returned promise will be adopted with the state of given promise.
*
* @param {*} value
* @returns {vow:Promise}
*/
resolve : function(value) {
return vow.resolve(value);
},
/**
* Returns a promise that has already been rejected with the given `reason`.
*
* @param {*} reason
* @returns {vow:Promise}
*/
reject : function(reason) {
return vow.reject(reason);
}
};
for(var prop in staticMethods) {
staticMethods.hasOwnProperty(prop) &&
(Promise[prop] = staticMethods[prop]);
}
var vow = /** @exports vow */ {
Deferred : Deferred,
Promise : Promise,
/**
* Creates a new deferred. This method is a factory method for `vow:Deferred` class.
* It's equivalent to `new vow.Deferred()`.
*
* @returns {vow:Deferred}
*/
defer : function() {
return new Deferred();
},
/**
* Static equivalent to `promise.then`.
* If given `value` is not a promise, then `value` is equivalent to fulfilled promise.
*
* @param {*} value
* @param {Function} [onFulfilled] Callback that will to be invoked with the value after promise has been fulfilled
* @param {Function} [onRejected] Callback that will to be invoked with the reason after promise has been rejected
* @param {Function} [onProgress] Callback that will to be invoked with the value after promise has been notified
* @param {Object} [ctx] Context of callbacks execution
* @returns {vow:Promise}
*/
when : function(value, onFulfilled, onRejected, onProgress, ctx) {
return vow.cast(value).then(onFulfilled, onRejected, onProgress, ctx);
},
/**
* Static equivalent to `promise.fail`.
* If given `value` is not a promise, then `value` is equivalent to fulfilled promise.
*
* @param {*} value
* @param {Function} onRejected Callback that will to be invoked with the reason after promise has been rejected
* @param {Object} [ctx] Context of callback execution
* @returns {vow:Promise}
*/
fail : function(value, onRejected, ctx) {
return vow.when(value, undef, onRejected, ctx);
},
/**
* Static equivalent to `promise.always`.
* If given `value` is not a promise, then `value` is equivalent to fulfilled promise.
*
* @param {*} value
* @param {Function} onResolved Callback that will to be invoked with the reason after promise has been resolved
* @param {Object} [ctx] Context of callback execution
* @returns {vow:Promise}
*/
always : function(value, onResolved, ctx) {
return vow.when(value).always(onResolved, ctx);
},
/**
* Static equivalent to `promise.progress`.
* If given `value` is not a promise, then `value` is equivalent to fulfilled promise.
*
* @param {*} value
* @param {Function} onProgress Callback that will to be invoked with the reason after promise has been notified
* @param {Object} [ctx] Context of callback execution
* @returns {vow:Promise}
*/
progress : function(value, onProgress, ctx) {
return vow.when(value).progress(onProgress, ctx);
},
/**
* Static equivalent to `promise.spread`.
* If given `value` is not a promise, then `value` is equivalent to fulfilled promise.
*
* @param {*} value
* @param {Function} [onFulfilled] Callback that will to be invoked with the value after promise has been fulfilled
* @param {Function} [onRejected] Callback that will to be invoked with the reason after promise has been rejected
* @param {Object} [ctx] Context of callbacks execution
* @returns {vow:Promise}
*/
spread : function(value, onFulfilled, onRejected, ctx) {
return vow.when(value).spread(onFulfilled, onRejected, ctx);
},
/**
* Static equivalent to `promise.done`.
* If given `value` is not a promise, then `value` is equivalent to fulfilled promise.
*
* @param {*} value
* @param {Function} [onFulfilled] Callback that will to be invoked with the value after promise has been fulfilled
* @param {Function} [onRejected] Callback that will to be invoked with the reason after promise has been rejected
* @param {Function} [onProgress] Callback that will to be invoked with the value after promise has been notified
* @param {Object} [ctx] Context of callbacks execution
*/
done : function(value, onFulfilled, onRejected, onProgress, ctx) {
vow.when(value).done(onFulfilled, onRejected, onProgress, ctx);
},
/**
* Checks whether the given `value` is a promise-like object
*
* @param {*} value
* @returns {Boolean}
*
* @example
* ```js
* vow.isPromise('something'); // returns false
* vow.isPromise(vow.defer().promise()); // returns true
* vow.isPromise({ then : function() { }); // returns true
* ```
*/
isPromise : function(value) {
return isObject(value) && isFunction(value.then);
},
/**
* Coerces given `value` to a promise, or returns the `value` if it's already a promise.
*
* @param {*} value
* @returns {vow:Promise}
*/
cast : function(value) {
return vow.isPromise(value)?
value :
vow.resolve(value);
},
/**
* Static equivalent to `promise.valueOf`.
* If given `value` is not an instance of `vow.Promise`, then `value` is equivalent to fulfilled promise.
*
* @param {*} value
* @returns {*}
*/
valueOf : function(value) {
return value && isFunction(value.valueOf)? value.valueOf() : value;
},
/**
* Static equivalent to `promise.isFulfilled`.
* If given `value` is not an instance of `vow.Promise`, then `value` is equivalent to fulfilled promise.
*
* @param {*} value
* @returns {Boolean}
*/
isFulfilled : function(value) {
return value && isFunction(value.isFulfilled)? value.isFulfilled() : true;
},
/**
* Static equivalent to `promise.isRejected`.
* If given `value` is not an instance of `vow.Promise`, then `value` is equivalent to fulfilled promise.
*
* @param {*} value
* @returns {Boolean}
*/
isRejected : function(value) {
return value && isFunction(value.isRejected)? value.isRejected() : false;
},
/**
* Static equivalent to `promise.isResolved`.
* If given `value` is not a promise, then `value` is equivalent to fulfilled promise.
*
* @param {*} value
* @returns {Boolean}
*/
isResolved : function(value) {
return value && isFunction(value.isResolved)? value.isResolved() : true;
},
/**
* Returns a promise that has already been resolved with the given `value`.
* If `value` is a promise, returned promise will be adopted with the state of given promise.
*
* @param {*} value
* @returns {vow:Promise}
*/
resolve : function(value) {
var res = vow.defer();
res.resolve(value);
return res.promise();
},
/**
* Returns a promise that has already been fulfilled with the given `value`.
* If `value` is a promise, returned promise will be fulfilled with fulfill/rejection value of given promise.
*
* @param {*} value
* @returns {vow:Promise}
*/
fulfill : function(value) {
var defer = vow.defer(),
promise = defer.promise();
defer.resolve(value);
return promise.isFulfilled()?
promise :
promise.then(null, function(reason) {
return reason;
});
},
/**
* Returns a promise that has already been rejected with the given `reason`.
* If `reason` is a promise, returned promise will be rejected with fulfill/rejection value of given promise.
*
* @param {*} reason
* @returns {vow:Promise}
*/
reject : function(reason) {
var defer = vow.defer();
defer.reject(reason);
return defer.promise();
},
/**
* Invokes a given function `fn` with arguments `args`
*
* @param {Function} fn
* @param {...*} [args]
* @returns {vow:Promise}
*
* @example
* ```js
* var promise1 = vow.invoke(function(value) {
* return value;
* }, 'ok'),
* promise2 = vow.invoke(function() {
* throw Error();
* });
*
* promise1.isFulfilled(); // true
* promise1.valueOf(); // 'ok'
* promise2.isRejected(); // true
* promise2.valueOf(); // instance of Error
* ```
*/
invoke : function(fn, args) {
var len = Math.max(arguments.length - 1, 0),
callArgs;
if(len) { // optimization for V8
callArgs = Array(len);
var i = 0;
while(i < len) {
callArgs[i++] = arguments[i];
}
}
try {
return vow.resolve(callArgs?
fn.apply(global, callArgs) :
fn.call(global));
}
catch(e) {
return vow.reject(e);
}
},
/**
* Returns a promise to be fulfilled only after all the items in `iterable` are fulfilled,
* or to be rejected when any of the `iterable` is rejected.
*
* @param {Array|Object} iterable
* @returns {vow:Promise}
*
* @example
* with array:
* ```js
* var defer1 = vow.defer(),
* defer2 = vow.defer();
*
* vow.all([defer1.promise(), defer2.promise(), 3])
* .then(function(value) {
* // value is "[1, 2, 3]" here
* });
*
* defer1.resolve(1);
* defer2.resolve(2);
* ```
*
* @example
* with object:
* ```js
* var defer1 = vow.defer(),
* defer2 = vow.defer();
*
* vow.all({ p1 : defer1.promise(), p2 : defer2.promise(), p3 : 3 })
* .then(function(value) {
* // value is "{ p1 : 1, p2 : 2, p3 : 3 }" here
* });
*
* defer1.resolve(1);
* defer2.resolve(2);
* ```
*/
all : function(iterable) {
var defer = new Deferred(),
isPromisesArray = isArray(iterable),
keys = isPromisesArray?
getArrayKeys(iterable) :
getObjectKeys(iterable),
len = keys.length,
res = isPromisesArray? [] : {};
if(!len) {
defer.resolve(res);
return defer.promise();
}
var i = len;
vow._forEach(
iterable,
function() {
if(!--i) {
var j = 0;
while(j < len) {
res[keys[j]] = vow.valueOf(iterable[keys[j++]]);
}
defer.resolve(res);
}
},
defer.reject,
defer.notify,
defer,
keys);
return defer.promise();
},
/**
* Returns a promise to be fulfilled only after all the items in `iterable` are resolved.
*
* @param {Array|Object} iterable
* @returns {vow:Promise}
*
* @example
* ```js
* var defer1 = vow.defer(),
* defer2 = vow.defer();
*
* vow.allResolved([defer1.promise(), defer2.promise()]).spread(function(promise1, promise2) {
* promise1.isRejected(); // returns true
* promise1.valueOf(); // returns "'error'"
* promise2.isFulfilled(); // returns true
* promise2.valueOf(); // returns "'ok'"
* });
*
* defer1.reject('error');
* defer2.resolve('ok');
* ```
*/
allResolved : function(iterable) {
var defer = new Deferred(),
isPromisesArray = isArray(iterable),
keys = isPromisesArray?
getArrayKeys(iterable) :
getObjectKeys(iterable),
i = keys.length,
res = isPromisesArray? [] : {};
if(!i) {
defer.resolve(res);
return defer.promise();
}
var onResolved = function() {
--i || defer.resolve(iterable);
};
vow._forEach(
iterable,
onResolved,
onResolved,
defer.notify,
defer,
keys);
return defer.promise();
},
allPatiently : function(iterable) {
return vow.allResolved(iterable).then(function() {
var isPromisesArray = isArray(iterable),
keys = isPromisesArray?
getArrayKeys(iterable) :
getObjectKeys(iterable),
rejectedPromises, fulfilledPromises,
len = keys.length, i = 0, key, promise;
if(!len) {
return isPromisesArray? [] : {};
}
while(i < len) {
key = keys[i++];
promise = iterable[key];
if(vow.isRejected(promise)) {
rejectedPromises || (rejectedPromises = isPromisesArray? [] : {});
isPromisesArray?
rejectedPromises.push(promise.valueOf()) :
rejectedPromises[key] = promise.valueOf();
}
else if(!rejectedPromises) {
(fulfilledPromises || (fulfilledPromises = isPromisesArray? [] : {}))[key] = vow.valueOf(promise);
}
}
if(rejectedPromises) {
throw rejectedPromises;
}
return fulfilledPromises;
});
},
/**
* Returns a promise to be fulfilled only when any of the items in `iterable` are fulfilled,
* or to be rejected when all the items are rejected (with the reason of the first rejected item).
*
* @param {Array} iterable
* @returns {vow:Promise}
*/
any : function(iterable) {
var defer = new Deferred(),
len = iterable.length;
if(!len) {
defer.reject(Error());
return defer.promise();
}
var i = 0, reason;
vow._forEach(
iterable,
defer.resolve,
function(e) {
i || (reason = e);
++i === len && defer.reject(reason);
},
defer.notify,
defer);
return defer.promise();
},
/**
* Returns a promise to be fulfilled only when any of the items in `iterable` are fulfilled,
* or to be rejected when the first item is rejected.
*
* @param {Array} iterable
* @returns {vow:Promise}
*/
anyResolved : function(iterable) {
var defer = new Deferred(),
len = iterable.length;
if(!len) {
defer.reject(Error());
return defer.promise();
}
vow._forEach(
iterable,
defer.resolve,
defer.reject,
defer.notify,
defer);
return defer.promise();
},
/**
* Static equivalent to `promise.delay`.
* If given `value` is not a promise, then `value` is equivalent to fulfilled promise.
*
* @param {*} value
* @param {Number} delay
* @returns {vow:Promise}
*/
delay : function(value, delay) {
return vow.resolve(value).delay(delay);
},
/**
* Static equivalent to `promise.timeout`.
* If given `value` is not a promise, then `value` is equivalent to fulfilled promise.
*
* @param {*} value
* @param {Number} timeout
* @returns {vow:Promise}
*/
timeout : function(value, timeout) {
return vow.resolve(value).timeout(timeout);
},
_forEach : function(promises, onFulfilled, onRejected, onProgress, ctx, keys) {
var len = keys? keys.length : promises.length,
i = 0;
while(i < len) {
vow.when(promises[keys? keys[i] : i], onFulfilled, onRejected, onProgress, ctx);
++i;
}
}
};
var undef,
nextTick = (function() {
var fns = [],
enqueueFn = function(fn) {
return fns.push(fn) === 1;
},
callFns = function() {
var fnsToCall = fns, i = 0, len = fns.length;
fns = [];
while(i < len) {
fnsToCall[i++]();
}
};
if(typeof setImmediate === 'function') { // ie10, nodejs >= 0.10
return function(fn) {
enqueueFn(fn) && setImmediate(callFns);
};
}
if(typeof process === 'object' && process.nextTick) { // nodejs < 0.10
return function(fn) {
enqueueFn(fn) && process.nextTick(callFns);
};
}
if(global.postMessage) { // modern browsers
var isPostMessageAsync = true;
if(global.attachEvent) {
var checkAsync = function() {
isPostMessageAsync = false;
};
global.attachEvent('onmessage', checkAsync);
global.postMessage('__checkAsync', '*');
global.detachEvent('onmessage', checkAsync);
}
if(isPostMessageAsync) {
var msg = '__promise' + +new Date,
onMessage = function(e) {
if(e.data === msg) {
e.stopPropagation && e.stopPropagation();
callFns();
}
};
global.addEventListener?
global.addEventListener('message', onMessage, true) :
global.attachEvent('onmessage', onMessage);
return function(fn) {
enqueueFn(fn) && global.postMessage(msg, '*');
};
}
}
var doc = global.document;
if('onreadystatechange' in doc.createElement('script')) { // ie6-ie8
var createScript = function() {
var script = doc.createElement('script');
script.onreadystatechange = function() {
script.parentNode.removeChild(script);
script = script.onreadystatechange = null;
callFns();
};
(doc.documentElement || doc.body).appendChild(script);
};
return function(fn) {
enqueueFn(fn) && createScript();
};
}
return function(fn) { // old browsers
enqueueFn(fn) && setTimeout(callFns, 0);
};
})(),
throwException = function(e) {
nextTick(function() {
throw e;
});
},
isFunction = function(obj) {
return typeof obj === 'function';
},
isObject = function(obj) {
return obj !== null && typeof obj === 'object';
},
toStr = Object.prototype.toString,
isArray = Array.isArray || function(obj) {
return toStr.call(obj) === '[object Array]';
},
getArrayKeys = function(arr) {
var res = [],
i = 0, len = arr.length;
while(i < len) {
res.push(i++);
}
return res;
},
getObjectKeys = Object.keys || function(obj) {
var res = [];
for(var i in obj) {
obj.hasOwnProperty(i) && res.push(i);
}
return res;
};
var defineAsGlobal = true;
if(typeof module === 'object' && typeof module.exports === 'object') {
module.exports = vow;
defineAsGlobal = false;
}
if(typeof modules === 'object') {
modules.define('vow', function(provide) {
provide(vow);
});
defineAsGlobal = false;
}
if(typeof define === 'function') {
define(function(require, exports, module) {
module.exports = vow;
});
defineAsGlobal = false;
}
defineAsGlobal && (global.vow = vow);
})(this);
(function (global) {
/**
* API error.
*
* @param {String} type Error type.
* @param {String} message Human-readable description of the error.
*/
function ApiError(type, message) {
this.name = 'ApiError';
this.type = type;
this.message = message;
if (Error.captureStackTrace) {
Error.captureStackTrace(this, this.constructor);
}
}
ApiError.prototype = Object.create(Error.prototype, {
constructor: {
value: ApiError
}
});
/**
* Invalid or missed parameter.
*/
ApiError.BAD_REQUEST = 'BAD_REQUEST';
/**
* Unspecified error or server logic error.
*/
ApiError.INTERNAL_ERROR = 'INTERNAL_ERROR';
/**
* API middleware wasn't found.
*/
ApiError.NOT_FOUND = 'NOT_FOUND';
var defineAsGlobal = true;
/**
* @see https://github.com/ymaps/modules
*/
if (typeof global.modules === 'object') {
global.modules.define('bla-error', function (provide) {
provide(ApiError);
});
defineAsGlobal = false;
}
/**
* @see requirejs.org
*/
if (typeof global.define === 'function') {
global.define('bla-error', function () {
return ApiError;
});
defineAsGlobal = false;
}
if (defineAsGlobal) {
global.bla = global.bla || {};
global.bla.ApiError = ApiError;
}
}(window));
(function (global) {
/**
* Returns API class based on dependencies.
*
* @param {Object} vow
* @param {Object} ApiError
* @returns {Function}
*/
function createApiClass(vow, ApiError) {
/**
* Makes an ajax request.
*
* @param {String} url A string containing the URL to which the request is sent.
* @param {String} data Data to be sent to the server.
* @returns {vow.Promise}
*/
function sendAjaxRequest(url, data) {
var xhr = new XMLHttpRequest();
var d = vow.defer();
xhr.onreadystatechange = function () {
if (xhr.readyState === XMLHttpRequest.DONE) {
if (xhr.status === 200) {
d.resolve(JSON.parse(xhr.responseText));
} else {
d.reject(xhr);
}
}
};
xhr.open('POST', url, true);
xhr.setRequestHeader('Accept', 'application/json, text/javascript, */*; q=0.01');
xhr.setRequestHeader('Content-type', 'application/json');
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xhr.send(data);
return d.promise();
}
/*
* Set of predefined API errors.
*/
var XHR_ERRORS = {
404: new ApiError(ApiError.NOT_FOUND, 'API middleware wasn\'t found')
};
/**
* Api provider.
*
* @param {String} basePath Url path to the middleware root.
* @param {Object} [options] Extra options.
* @param {Boolean} [options.enableBatching=true] Enables batching.
*/
function Api(basePath, options) {
this._basePath = basePath;
options = options || {};
this._options = {
enableBatching: options.hasOwnProperty('enableBatching') ?
options.enableBatching :
true
};
this._batch = [];
this._deferreds = {};
}
Api.prototype = {
constructor: Api,
/**
* Executes api by path with specified parameters.
*
* @param {String} methodName Method name.
* @param {Object} params Data should be sent to the method.
* @param {Object} [execOptions] Exec-specific options.
* @param {Boolean} [execOptions.enableBatching=true] Should the current call of the method be batched.
* method be batched.
* @returns {vow.Promise}
*/
exec: function (methodName, params, execOptions) {
execOptions = execOptions || {};
var enableBatching = execOptions.hasOwnProperty('enableBatching') ?
execOptions.enableBatching :
this._options.enableBatching;
return enableBatching ?
this._execWithBatching(methodName, params) :
this._execWithoutBatching(methodName, params);
},
/**
* Executes method immediately.
*
* @param {String} methodName Method name.
* @param {Object} params Data should be sent to the method.
* @returns {vow.Promise}
*/
_execWithoutBatching: function (methodName, params) {
var defer = vow.defer();
var url = this._basePath + methodName;
var data = JSON.stringify(params);
sendAjaxRequest(url, data).then(
this._resolvePromise.bind(this, defer),
this._rejectPromise.bind(this, defer)
);
return defer.promise();
},
/**
* Executes method with a little delay, adding it to batch.
*
* @param {String} methodName Method name.
* @param {Object} params Data should be sent to the method.
* @returns {vow.Promise}
*/
_execWithBatching: function (methodName, params) {
var requestId = this._getRequestId(methodName, params);
var promise = this._getRequestPromise(requestId);
if (!promise) {
this._addToBatch(methodName, params);
promise = this._createPromise(requestId);
this._run();
}
return promise;
},
/**
* Generates an ID for a method request.
*
* @param {String} methodName
* @param {Object} params
* @returns {String}
*/
_getRequestId: function (methodName, params) {
var stringifiedParams = JSON.stringify(params) || '';
return methodName + stringifiedParams;
},
/**
* Gets the promise object for given request ID.
*
* @param {String} requestId Request ID for which promise is retrieved.
* @returns {vow.Promise|undefined}
*/
_getRequestPromise: function (requestId) {
var defer = this._deferreds[requestId];
return defer && defer.promise();
},
/**
* Appends data to the batch array.
*
* @param {String} methodName
* @param {Object} params
*/
_addToBatch: function (methodName, params) {
this._batch.push({
method: methodName,
params: params
});
},
/**
* Creates new deferred promise.
*
* @param {String} requestId Request ID for which promise is generated.
* @returns {vow.Promise}
*/
_createPromise: function (requestId) {
var defer = vow.defer();
this._deferreds[requestId] = defer;
return defer.promise();
},
/**
* Initializes async batch request.
*/
_run: function () {
// The collecting requests for the batch will start when a first request is received.
// That's why the batch length is checked there.
if (this._batch.length === 1) {
vow.resolve().then(this._sendBatchRequest, this);
}
},
/**
* Performs batch request.
*/
_sendBatchRequest: function () {
var url = this._basePath + 'batch';
var data = JSON.stringify({methods: this._batch});
sendAjaxRequest(url, data).then(
this._resolvePromises.bind(this, this._batch),
this._rejectPromises.bind(this, this._batch)
);
this._batch = [];
},
/**
* Resolve deferred promise.
*
* @param {vow.Deferred} defer
* @param {Object} response Server response.
*/
_resolvePromise: function (defer, response) {
var error = response.error;
if (error) {
defer.reject(new ApiError(error.type, error.message));
} else {
defer.resolve(response.data);
}
},
/**
* Resolves deferred promises.
*
* @param {Object[]} batch Batch request data.
* @param {Object} response Server response.
*/
_resolvePromises: function (batch, response) {
var data = response.data;
for (var i = 0, requestId; i < batch.length; i++) {
requestId = this._getRequestId(batch[i].method, batch[i].params);
this._resolvePromise(this._deferreds[requestId], data[i]);
delete this._deferreds[requestId];
}
},
/**
* Rejects deferred promise.
*
* @param {vow.Deferred} defer
* @param {XMLHttpRequest} xhr
*/
_rejectPromise: function (defer, xhr) {
var errorMessage = xhr.message || xhr.statusText || xhr.responseText;
var error = XHR_ERRORS[xhr.status] || new ApiError(ApiError.INTERNAL_ERROR, errorMessage);
defer.reject(error);
},
/**
* Rejects deferred promises.
*
* @param {Object[]} batch Batch request data.
* @param {XMLHttpRequest} xhr
*/
_rejectPromises: function (batch, xhr) {
for (var i = 0, requestId; i < batch.length; i++) {
requestId = this._getRequestId(batch[i].method, batch[i].params);
this._rejectPromise(this._deferreds[requestId], xhr);
delete this._deferreds[requestId];
}
}
};
return Api;
}
var defineAsGlobal = true;
/**
* @see https://github.com/ymaps/modules
*/
if (typeof global.modules === 'object') {
global.modules.define('bla', ['vow', 'bla-error'], function (provide, vow, ApiError) {
var Api = createApiClass(vow, ApiError);
provide(Api);
});
defineAsGlobal = false;
}
/**
* @see requirejs.org
*/
if (typeof global.define === 'function') {
global.define('bla', ['bla-error', 'vow'], function (ApiError, vow) {
return createApiClass(vow, ApiError);
});
defineAsGlobal = false;
}
if (defineAsGlobal) {
global.bla = global.bla || {};
global.bla.Api = createApiClass(global.vow, global.bla.ApiError);
}
}(window));
|
src/examples/button.js | JiaoJian1221/react-mdc-web | import React from 'react';
import {
Checkbox,
Button,
FormField,
FAButton,
ITButton,
} from '../components'
export class ButtonTest extends React.Component {
state = {
dense: false,
primary: false,
compact: false,
accent: false,
raised: true,
}
render() {
let {dense, primary, compact, accent, raised} = this.state;
return (
<section>
<h1>Button</h1>
<div style={{display: 'flex', justifyContent: 'space-between', width: 600}}>
<FormField><Checkbox checked={dense} onClick={({target: {checked}}) => this.setState({dense: checked})}/><label>Dense</label></FormField>
<FormField><Checkbox checked={primary} onClick={({target: {checked}}) => this.setState({primary: checked})}/><label>Primary</label></FormField>
<FormField><Checkbox checked={compact} onClick={({target: {checked}}) => this.setState({compact: checked})}/><label>Compact</label></FormField>
<FormField><Checkbox checked={accent} onClick={({target: {checked}}) => this.setState({accent: checked})}/><label>Accent</label></FormField>
<FormField><Checkbox checked={raised} onClick={({target: {checked}}) => this.setState({raised: checked})}/><label>Raised</label></FormField>
</div>
<Button style={{marginTop: 10}} dense={dense} primary={primary} compact={compact} accent={accent} raised={raised}>Example Button</Button>
<Button tag='div' style={{marginTop: 10, marginLeft: 10}} dense={dense} primary={primary} compact={compact} accent={accent} raised={raised}>Example Button (DIV)</Button>
<h1>Floating Action Button</h1>
<FAButton onClick={e => console.log(e)}>
<svg width="24" height="24" viewBox="0 0 24 24">
<path d="M3 17.25V21h3.75L17.81 9.94l-3.75-3.75L3 17.25zM20.71 7.04c.39-.39.39-1.02 0-1.41l-2.34-2.34c-.39-.39-1.02-.39-1.41 0l-1.83 1.83 3.75 3.75 1.83-1.83z"></path>
</svg>
</FAButton>
<h1>Icon Toggle Button</h1>
<ITButton toggleOnIcon='favorite' toggleOffIcon='favorite_border' onChange={e => console.log(e)} />
</section>
);
}
}
|
client/scripts/components/user/currency-field/index.js | kuali/research-coi | /*
The Conflict of Interest (COI) module of Kuali Research
Copyright © 2005-2016 Kuali, Inc.
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
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
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>
*/
import styles from './style';
import React from 'react';
import TextField from '../text-field';
import {merge} from '../../../merge';
export default class NumericField extends TextField {
constructor() {
super();
this.validateNumeric = this.validateNumeric.bind(this);
}
validateNumeric(e) {
const event = e || window.event;
let key = event.keyCode || event.which;
key = String.fromCharCode( key );
const regex = /[0-9]|\./;
if ( !regex.test(key) ) {
event.returnValue = false;
if (event.preventDefault) {
event.preventDefault();
}
}
}
render() {
const {id, invalid, value = '', styles: style, label} = this.props;
const inputStyle = merge(style.input, {padding: '2px 20px'});
return (
<div style={style.container}>
<label
htmlFor={id}
style={this.getLabelStyle(invalid, style.label)}
>
{label}
</label>
<div style={{position: 'relative'}}>
<span className={styles.currency}>$</span>
<input
id={id}
type='text'
onChange={this.onChange}
name={name}
style={this.getInputStyle(invalid, inputStyle)}
value={value}
onKeyPress={this.validateNumeric}
/>
</div>
</div>
);
}
}
|
ajax/libs/rxjs/2.3.10/rx.all.compat.js | mival/cdnjs | // Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information.
;(function (undefined) {
var objectTypes = {
'boolean': false,
'function': true,
'object': true,
'number': false,
'string': false,
'undefined': false
};
var root = (objectTypes[typeof window] && window) || this,
freeExports = objectTypes[typeof exports] && exports && !exports.nodeType && exports,
freeModule = objectTypes[typeof module] && module && !module.nodeType && module,
moduleExports = freeModule && freeModule.exports === freeExports && freeExports,
freeGlobal = objectTypes[typeof global] && global;
if (freeGlobal && (freeGlobal.global === freeGlobal || freeGlobal.window === freeGlobal)) {
root = freeGlobal;
}
var Rx = {
internals: {},
config: {
Promise: root.Promise // Detect if promise exists
},
helpers: { }
};
// Defaults
var noop = Rx.helpers.noop = function () { },
notDefined = Rx.helpers.notDefined = function (x) { return typeof x === 'undefined'; },
isScheduler = Rx.helpers.isScheduler = function (x) { return x instanceof Rx.Scheduler; },
identity = Rx.helpers.identity = function (x) { return x; },
pluck = Rx.helpers.pluck = function (property) { return function (x) { return x[property]; }; },
just = Rx.helpers.just = function (value) { return function () { return value; }; },
defaultNow = Rx.helpers.defaultNow = (function () { return !!Date.now ? Date.now : function () { return +new Date; }; }()),
defaultComparer = Rx.helpers.defaultComparer = function (x, y) { return isEqual(x, y); },
defaultSubComparer = Rx.helpers.defaultSubComparer = function (x, y) { return x > y ? 1 : (x < y ? -1 : 0); },
defaultKeySerializer = Rx.helpers.defaultKeySerializer = function (x) { return x.toString(); },
defaultError = Rx.helpers.defaultError = function (err) { throw err; },
isPromise = Rx.helpers.isPromise = function (p) { return !!p && typeof p.then === 'function'; },
asArray = Rx.helpers.asArray = function () { return Array.prototype.slice.call(arguments); },
not = Rx.helpers.not = function (a) { return !a; },
isFunction = Rx.helpers.isFunction = (function () {
var isFn = function (value) {
return typeof value == 'function' || false;
}
// fallback for older versions of Chrome and Safari
if (isFn(/x/)) {
isFn = function(value) {
return typeof value == 'function' && toString.call(value) == '[object Function]';
};
}
return isFn;
}());
// Errors
var sequenceContainsNoElements = 'Sequence contains no elements.';
var argumentOutOfRange = 'Argument out of range';
var objectDisposed = 'Object has been disposed';
function checkDisposed() { if (this.isDisposed) { throw new Error(objectDisposed); } }
// 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;
};
}
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
function IndexedItem(id, value) {
this.id = id;
this.value = value;
}
IndexedItem.prototype.compareTo = function (other) {
var c = this.value.compareTo(other.value);
c === 0 && (c = this.id - other.id);
return c;
};
// Priority Queue for Scheduling
var PriorityQueue = Rx.internals.PriorityQueue = function (capacity) {
this.items = new Array(capacity);
this.length = 0;
};
var priorityProto = PriorityQueue.prototype;
priorityProto.isHigherPriority = function (left, right) {
return this.items[left].compareTo(this.items[right]) < 0;
};
priorityProto.percolate = function (index) {
if (index >= this.length || index < 0) { return; }
var parent = index - 1 >> 1;
if (parent < 0 || parent === index) { return; }
if (this.isHigherPriority(index, parent)) {
var temp = this.items[index];
this.items[index] = this.items[parent];
this.items[parent] = temp;
this.percolate(parent);
}
};
priorityProto.heapify = function (index) {
+index || (index = 0);
if (index >= this.length || index < 0) { return; }
var left = 2 * index + 1,
right = 2 * index + 2,
first = index;
if (left < this.length && this.isHigherPriority(left, first)) {
first = left;
}
if (right < this.length && this.isHigherPriority(right, first)) {
first = right;
}
if (first !== index) {
var temp = this.items[index];
this.items[index] = this.items[first];
this.items[first] = temp;
this.heapify(first);
}
};
priorityProto.peek = function () { return this.items[0].value; };
priorityProto.removeAt = function (index) {
this.items[index] = this.items[--this.length];
delete this.items[this.length];
this.heapify();
};
priorityProto.dequeue = function () {
var result = this.peek();
this.removeAt(0);
return result;
};
priorityProto.enqueue = function (item) {
var index = this.length++;
this.items[index] = new IndexedItem(PriorityQueue.count++, item);
this.percolate(index);
};
priorityProto.remove = function (item) {
for (var i = 0; i < this.length; i++) {
if (this.items[i].value === item) {
this.removeAt(i);
return true;
}
}
return false;
};
PriorityQueue.count = 0;
/**
* Represents a group of disposable resources that are disposed together.
* @constructor
*/
var CompositeDisposable = Rx.CompositeDisposable = function () {
this.disposables = argsOrArray(arguments, 0);
this.isDisposed = false;
this.length = this.disposables.length;
};
var CompositeDisposablePrototype = CompositeDisposable.prototype;
/**
* Adds a disposable to the CompositeDisposable or disposes the disposable if the CompositeDisposable is disposed.
* @param {Mixed} item Disposable to add.
*/
CompositeDisposablePrototype.add = function (item) {
if (this.isDisposed) {
item.dispose();
} else {
this.disposables.push(item);
this.length++;
}
};
/**
* Removes and disposes the first occurrence of a disposable from the CompositeDisposable.
* @param {Mixed} item Disposable to remove.
* @returns {Boolean} true if found; false otherwise.
*/
CompositeDisposablePrototype.remove = function (item) {
var shouldDispose = false;
if (!this.isDisposed) {
var idx = this.disposables.indexOf(item);
if (idx !== -1) {
shouldDispose = true;
this.disposables.splice(idx, 1);
this.length--;
item.dispose();
}
}
return shouldDispose;
};
/**
* Disposes all disposables in the group and removes them from the group.
*/
CompositeDisposablePrototype.dispose = function () {
if (!this.isDisposed) {
this.isDisposed = true;
var currentDisposables = this.disposables.slice(0);
this.disposables = [];
this.length = 0;
for (var i = 0, len = currentDisposables.length; i < len; i++) {
currentDisposables[i].dispose();
}
}
};
/**
* Converts the existing CompositeDisposable to an array of disposables
* @returns {Array} An array of disposable objects.
*/
CompositeDisposablePrototype.toArray = function () {
return this.disposables.slice(0);
};
/**
* Provides a set of static methods for creating Disposables.
*
* @constructor
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
*/
var Disposable = Rx.Disposable = function (action) {
this.isDisposed = false;
this.action = action || noop;
};
/** Performs the task of cleaning up resources. */
Disposable.prototype.dispose = function () {
if (!this.isDisposed) {
this.action();
this.isDisposed = true;
}
};
/**
* Creates a disposable object that invokes the specified action when disposed.
* @param {Function} dispose Action to run during the first call to dispose. The action is guaranteed to be run at most once.
* @return {Disposable} The disposable object that runs the given action upon disposal.
*/
var disposableCreate = Disposable.create = function (action) { return new Disposable(action); };
/**
* Gets the disposable that does nothing when disposed.
*/
var disposableEmpty = Disposable.empty = { dispose: noop };
var SingleAssignmentDisposable = Rx.SingleAssignmentDisposable = (function () {
function BooleanDisposable () {
this.isDisposed = false;
this.current = null;
}
var booleanDisposablePrototype = BooleanDisposable.prototype;
/**
* Gets the underlying disposable.
* @return The underlying disposable.
*/
booleanDisposablePrototype.getDisposable = function () {
return this.current;
};
/**
* Sets the underlying disposable.
* @param {Disposable} value The new underlying disposable.
*/
booleanDisposablePrototype.setDisposable = function (value) {
var shouldDispose = this.isDisposed, old;
if (!shouldDispose) {
old = this.current;
this.current = value;
}
old && old.dispose();
shouldDispose && value && value.dispose();
};
/**
* Disposes the underlying disposable as well as all future replacements.
*/
booleanDisposablePrototype.dispose = function () {
var old;
if (!this.isDisposed) {
this.isDisposed = true;
old = this.current;
this.current = null;
}
old && old.dispose();
};
return BooleanDisposable;
}());
var SerialDisposable = Rx.SerialDisposable = SingleAssignmentDisposable;
/**
* Represents a disposable resource that only disposes its underlying disposable resource when all dependent disposable objects have been disposed.
*/
var RefCountDisposable = Rx.RefCountDisposable = (function () {
function InnerDisposable(disposable) {
this.disposable = disposable;
this.disposable.count++;
this.isInnerDisposed = false;
}
InnerDisposable.prototype.dispose = function () {
if (!this.disposable.isDisposed) {
if (!this.isInnerDisposed) {
this.isInnerDisposed = true;
this.disposable.count--;
if (this.disposable.count === 0 && this.disposable.isPrimaryDisposed) {
this.disposable.isDisposed = true;
this.disposable.underlyingDisposable.dispose();
}
}
}
};
/**
* Initializes a new instance of the RefCountDisposable with the specified disposable.
* @constructor
* @param {Disposable} disposable Underlying disposable.
*/
function RefCountDisposable(disposable) {
this.underlyingDisposable = disposable;
this.isDisposed = false;
this.isPrimaryDisposed = false;
this.count = 0;
}
/**
* Disposes the underlying disposable only when all dependent disposables have been disposed
*/
RefCountDisposable.prototype.dispose = function () {
if (!this.isDisposed) {
if (!this.isPrimaryDisposed) {
this.isPrimaryDisposed = true;
if (this.count === 0) {
this.isDisposed = true;
this.underlyingDisposable.dispose();
}
}
}
};
/**
* Returns a dependent disposable that when disposed decreases the refcount on the underlying disposable.
* @returns {Disposable} A dependent disposable contributing to the reference count that manages the underlying disposable's lifetime.
*/
RefCountDisposable.prototype.getDisposable = function () {
return this.isDisposed ? disposableEmpty : new InnerDisposable(this);
};
return RefCountDisposable;
})();
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) {
if (typeof root.setInterval === 'undefined') { throw new Error('Periodic scheduling not supported.'); }
var s = state;
var id = root.setInterval(function () {
s = action(s);
}, period);
return disposableCreate(function () {
root.clearInterval(id);
});
};
}(Scheduler.prototype));
(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;
var localTimer = (function () {
var localSetTimeout, localClearTimeout = noop;
if ('WScript' in this) {
localSetTimeout = function (fn, time) {
WScript.Sleep(time);
fn();
};
} else if (!!root.setTimeout) {
localSetTimeout = root.setTimeout;
localClearTimeout = root.clearTimeout;
} else {
throw new Error('No concurrency detected!');
}
return {
setTimeout: localSetTimeout,
clearTimeout: localClearTimeout
};
}());
var localSetTimeout = localTimer.setTimeout,
localClearTimeout = localTimer.clearTimeout;
(function () {
var reNative = RegExp('^' +
String(toString)
.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')
.replace(/toString| for [^\]]+/g, '.*?') + '$'
);
var setImmediate = typeof (setImmediate = freeGlobal && moduleExports && freeGlobal.setImmediate) == 'function' &&
!reNative.test(setImmediate) && setImmediate,
clearImmediate = typeof (clearImmediate = freeGlobal && moduleExports && freeGlobal.clearImmediate) == 'function' &&
!reNative.test(clearImmediate) && clearImmediate;
function postMessageSupported () {
// Ensure not in a worker
if (!root.postMessage || root.importScripts) { return false; }
var isAsync = false,
oldHandler = root.onmessage;
// Test for async
root.onmessage = function () { isAsync = true; };
root.postMessage('','*');
root.onmessage = oldHandler;
return isAsync;
}
// Use in order, 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 localSetTimeout(action, 0); };
clearMethod = localClearTimeout;
}
}());
/**
* Gets a scheduler that schedules work via a timed callback based upon platform.
*/
var timeoutScheduler = Scheduler.timeout = (function () {
function scheduleNow(state, action) {
var scheduler = this,
disposable = new SingleAssignmentDisposable();
var id = scheduleMethod(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
});
return new CompositeDisposable(disposable, disposableCreate(function () {
clearMethod(id);
}));
}
function scheduleRelative(state, dueTime, action) {
var scheduler = this,
dt = Scheduler.normalize(dueTime);
if (dt === 0) {
return scheduler.scheduleWithState(state, action);
}
var disposable = new SingleAssignmentDisposable();
var id = localSetTimeout(function () {
if (!disposable.isDisposed) {
disposable.setDisposable(action(scheduler, state));
}
}, dt);
return new CompositeDisposable(disposable, disposableCreate(function () {
localClearTimeout(id);
}));
}
function scheduleAbsolute(state, dueTime, action) {
return this.scheduleWithRelativeAndState(state, dueTime - this.now(), action);
}
return new Scheduler(defaultNow, scheduleNow, scheduleRelative, scheduleAbsolute);
})();
/** @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 (err) {
var self = this;
this.queue.push(function () {
self.observer.onError(err);
});
};
ScheduledObserver.prototype.completed = function () {
var self = this;
this.queue.push(function () {
self.observer.onCompleted();
});
};
ScheduledObserver.prototype.ensureActive = function () {
var isOwner = false, parent = this;
if (!this.hasFaulted && this.queue.length > 0) {
isOwner = !this.isAcquired;
this.isAcquired = true;
}
if (isOwner) {
this.disposable.setDisposable(this.scheduler.scheduleRecursive(function (self) {
var work;
if (parent.queue.length > 0) {
work = parent.queue.shift();
} else {
parent.isAcquired = false;
return;
}
try {
work();
} catch (ex) {
parent.queue = [];
parent.hasFaulted = true;
throw ex;
}
self();
}));
}
};
ScheduledObserver.prototype.dispose = function () {
__super__.prototype.dispose.call(this);
this.disposable.dispose();
};
return ScheduledObserver;
}(AbstractObserver));
var ObserveOnObserver = (function (__super__) {
inherits(ObserveOnObserver, __super__);
function ObserveOnObserver() {
__super__.apply(this, arguments);
}
ObserveOnObserver.prototype.next = function (value) {
__super__.prototype.next.call(this, value);
this.ensureActive();
};
ObserveOnObserver.prototype.error = function (e) {
__super__.prototype.error.call(this, e);
this.ensureActive();
};
ObserveOnObserver.prototype.completed = function () {
__super__.prototype.completed.call(this);
this.ensureActive();
};
return ObserveOnObserver;
})(ScheduledObserver);
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 TypeError('Promise type not provided nor in Rx.config.Promise'); }
var source = this;
return new promiseCtor(function (resolve, reject) {
// No cancellation can be done
var value, hasValue = false;
source.subscribe(function (v) {
value = v;
hasValue = true;
}, reject, function () {
hasValue && resolve(value);
});
});
};
/**
* 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 'throwError' for browsers <IE9.
* @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 = Observable.throwError = 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.
* @param {Function} resourceFactory Factory function to obtain a resource object.
* @param {Function} observableFactory Factory function to obtain an observable sequence that depends on the obtained resource.
* @returns {Observable} An observable sequence whose lifetime controls the lifetime of the dependent resource object.
*/
Observable.using = function (resourceFactory, observableFactory) {
return new AnonymousObservable(function (observer) {
var disposable = disposableEmpty, resource, source;
try {
resource = resourceFactory();
resource && (disposable = resource);
source = observableFactory(resource);
} catch (exception) {
return new CompositeDisposable(observableThrow(exception).subscribe(observer), disposable);
}
return new CompositeDisposable(source.subscribe(observer), disposable);
});
};
/**
* Propagates the observable sequence or Promise that reacts first.
* @param {Observable} rightSource Second observable sequence or Promise.
* @returns {Observable} {Observable} An observable sequence that surfaces either of the given sequences, whichever reacted first.
*/
observableProto.amb = function (rightSource) {
var leftSource = this;
return new AnonymousObservable(function (observer) {
var choice,
leftChoice = 'L', rightChoice = 'R',
leftSubscription = new SingleAssignmentDisposable(),
rightSubscription = new SingleAssignmentDisposable();
isPromise(rightSource) && (rightSource = observableFromPromise(rightSource));
function choiceL() {
if (!choice) {
choice = leftChoice;
rightSubscription.dispose();
}
}
function choiceR() {
if (!choice) {
choice = rightChoice;
leftSubscription.dispose();
}
}
leftSubscription.setDisposable(leftSource.subscribe(function (left) {
choiceL();
if (choice === leftChoice) {
observer.onNext(left);
}
}, function (err) {
choiceL();
if (choice === leftChoice) {
observer.onError(err);
}
}, function () {
choiceL();
if (choice === leftChoice) {
observer.onCompleted();
}
}));
rightSubscription.setDisposable(rightSource.subscribe(function (right) {
choiceR();
if (choice === rightChoice) {
observer.onNext(right);
}
}, function (err) {
choiceR();
if (choice === rightChoice) {
observer.onError(err);
}
}, function () {
choiceR();
if (choice === rightChoice) {
observer.onCompleted();
}
}));
return new CompositeDisposable(leftSubscription, rightSubscription);
});
};
/**
* Propagates the observable sequence or Promise that reacts first.
*
* @example
* var = Rx.Observable.amb(xs, ys, zs);
* @returns {Observable} An observable sequence that surfaces any of the given sequences, whichever reacted first.
*/
Observable.amb = function () {
var acc = observableNever(),
items = argsOrArray(arguments, 0);
function func(previous, current) {
return previous.amb(current);
}
for (var i = 0, len = items.length; i < len; i++) {
acc = func(acc, items[i]);
}
return acc;
};
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 for promises support
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
innerSubscription.setDisposable(innerSource.subscribe(observer.onNext.bind(observer), observer.onError.bind(observer), function () {
group.remove(innerSubscription);
isStopped && group.length === 1 && observer.onCompleted();
}));
}, observer.onError.bind(observer), function () {
isStopped = true;
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), self, self));
} else {
observer.onCompleted();
}
});
return new CompositeDisposable(subscription, cancelable);
});
};
/**
* Returns the values from the source observable sequence only after the other observable sequence produces a value.
* @param {Observable | Promise} other The observable sequence or Promise that triggers propagation of elements of the source sequence.
* @returns {Observable} An observable sequence containing the elements of the source sequence starting from the point the other sequence triggered propagation.
*/
observableProto.skipUntil = function (other) {
var source = this;
return new AnonymousObservable(function (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
isPromise(innerSource) && (innerSource = observableFromPromise(innerSource));
d.setDisposable(innerSource.subscribe(
function (x) { latest === id && observer.onNext(x); },
function (e) { latest === id && observer.onError(e); },
function () {
if (latest === id) {
hasLatest = false;
isStopped && observer.onCompleted();
}
}));
},
observer.onError.bind(observer),
function () {
isStopped = true;
!hasLatest && observer.onCompleted();
});
return new CompositeDisposable(subscription, innerSubscription);
});
};
/**
* 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 () {
return new AnonymousObservable(this.subscribe.bind(this));
};
/**
* Projects each element of an observable sequence into zero or more buffers which are produced based on element count information.
*
* @example
* var res = xs.bufferWithCount(10);
* var res = xs.bufferWithCount(10, 1);
* @param {Number} count Length of each buffer.
* @param {Number} [skip] Number of elements to skip between creation of consecutive buffers. If not provided, defaults to the count.
* @returns {Observable} An observable sequence of buffers.
*/
observableProto.bufferWithCount = function (count, skip) {
if (typeof skip !== 'number') {
skip = count;
}
return this.windowWithCount(count, skip).selectMany(function (x) {
return x.toArray();
}).where(function (x) {
return x.length > 0;
});
};
/**
* Dematerializes the explicit notification values of an observable sequence as implicit notifications.
* @returns {Observable} An observable sequence exhibiting the behavior corresponding to the source sequence's notification values.
*/
observableProto.dematerialize = function () {
var source = this;
return new AnonymousObservable(function (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) {
!hasValue && (hasValue = true);
try {
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 () {
!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);
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.
* @example
* var res = source.startWith(1, 2, 3);
* var res = source.startWith(Rx.Scheduler.timeout, 1, 2, 3);
* @param {Arguments} args The specified values to prepend to the observable sequence
* @returns {Observable} The source sequence prepended with the specified values.
*/
observableProto.startWith = function () {
var values, scheduler, start = 0;
if (!!arguments.length && isScheduler(arguments[0])) {
scheduler = arguments[0];
start = 1;
} else {
scheduler = immediateScheduler;
}
values = slice.call(arguments, start);
return enumerableFor([observableFromArray(values, scheduler), this]).concat();
};
/**
* Returns a specified number of contiguous elements from the end of an observable sequence.
* @description
* This operator accumulates a buffer with a length enough to store elements count elements. Upon completion of
* the source sequence, this buffer is drained on the result sequence. This causes the elements to be delayed.
* @param {Number} count Number of elements to take from the end of the source sequence.
* @returns {Observable} An observable sequence containing the specified number of elements from the end of the source sequence.
*/
observableProto.takeLast = function (count) {
var source = this;
return new AnonymousObservable(function (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} prop The property to pluck.
* @returns {Observable} Returns a new Observable sequence of property values.
*/
observableProto.pluck = function (prop) {
return this.map(function (x) { return x[prop]; });
};
function flatMap(source, selector, thisArg) {
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 source = this;
return new AnonymousObservable(function (observer) {
var remaining = count;
return source.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;
}
}
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 RangeError(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) {
observer.onNext(x);
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.
* @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 && isFunction(keySelector) ?
this.map(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 {
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;
if (ql.length > 0) {
var 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 && isFunction(predicate) ?
this.where(predicate, thisArg).single() :
singleOrDefaultAsync(this, false);
};
/**
* Returns the only element of an observable sequence that matches the predicate, or a default value if no such element exists; this method reports an exception if there is more than one element in the observable sequence.
* @example
* var res = res = source.singleOrDefault();
* var res = res = source.singleOrDefault(function (x) { return x === 42; });
* res = source.singleOrDefault(function (x) { return x === 42; }, 0);
* res = source.singleOrDefault(null, 0);
* @memberOf Observable#
* @param {Function} predicate A predicate function to evaluate for elements in the source sequence.
* @param [defaultValue] The default value if the index is outside the bounds of the source sequence.
* @param {Any} [thisArg] Object to use as `this` when executing the predicate.
* @returns {Observable} Sequence containing the single element in the observable sequence that satisfies the condition in the predicate, or a default value if no such element exists.
*/
observableProto.singleOrDefault = function (predicate, defaultValue, thisArg) {
return predicate && isFunction(predicate) ?
this.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);
};
if (!!root.Set) {
/**
* Converts the observable sequence to a Set if it exists.
* @returns {Observable} An observable sequence with a single value of a Set containing the values from the observable sequence.
*/
observableProto.toSet = function () {
var source = this;
return new AnonymousObservable(function (observer) {
var s = new root.Set();
return source.subscribe(
s.add.bind(s),
observer.onError.bind(observer),
function () {
observer.onNext(s);
observer.onCompleted();
});
});
};
}
if (!!root.Map) {
/**
* Converts the observable sequence to a Map if it exists.
* @param {Function} keySelector A function which produces the key for the Map.
* @param {Function} [elementSelector] An optional function which produces the element for the Map. If not present, defaults to the value from the observable sequence.
* @returns {Observable} An observable sequence with a single value of a Map containing the values from the observable sequence.
*/
observableProto.toMap = function (keySelector, elementSelector) {
var source = this;
return new AnonymousObservable(function (observer) {
var m = new root.Map();
return source.subscribe(
function (x) {
var key;
try {
key = keySelector(x);
} catch (e) {
observer.onError(e);
return;
}
var element = x;
if (elementSelector) {
try {
element = elementSelector(x);
} catch (e) {
observer.onError(e);
return;
}
}
m.set(key, element);
},
observer.onError.bind(observer),
function () {
observer.onNext(m);
observer.onCompleted();
});
});
};
}
var fnString = 'function';
function toThunk(obj, ctx) {
if (Array.isArray(obj)) {
return objectToThunk.call(ctx, obj);
}
if (isGeneratorFunction(obj)) {
return observableSpawn(obj.call(ctx));
}
if (isGenerator(obj)) {
return observableSpawn(obj);
}
if (isObservable(obj)) {
return observableToThunk(obj);
}
if (isPromise(obj)) {
return promiseToThunk(obj);
}
if (typeof obj === fnString) {
return obj;
}
if (isObject(obj) || Array.isArray(obj)) {
return objectToThunk.call(ctx, obj);
}
return obj;
}
function objectToThunk(obj) {
var ctx = this;
return function (done) {
var keys = Object.keys(obj),
pending = keys.length,
results = new obj.constructor(),
finished;
if (!pending) {
timeoutScheduler.schedule(function () { done(null, results); });
return;
}
for (var i = 0, len = keys.length; i < len; i++) {
run(obj[keys[i]], keys[i]);
}
function run(fn, key) {
if (finished) { return; }
try {
fn = toThunk(fn, ctx);
if (typeof fn !== fnString) {
results[key] = fn;
return --pending || done(null, results);
}
fn.call(ctx, function(err, res){
if (finished) { return; }
if (err) {
finished = true;
return done(err);
}
results[key] = res;
--pending || done(null, results);
});
} catch (e) {
finished = true;
done(e);
}
}
}
}
function observableToThink(observable) {
return function (fn) {
var value, hasValue = false;
observable.subscribe(
function (v) {
value = v;
hasValue = true;
},
fn,
function () {
hasValue && fn(null, value);
});
}
}
function promiseToThunk(promise) {
return function(fn){
promise.then(function(res) {
fn(null, res);
}, fn);
}
}
function isObservable(obj) {
return obj && obj.prototype.subscribe === fnString;
}
function isGeneratorFunction(obj) {
return obj && obj.constructor && obj.constructor.name === 'GeneratorFunction';
}
function isGenerator(obj) {
return obj && typeof obj.next === fnString && typeof obj.throw === fnString;
}
function isObject(val) {
return val && val.constructor === Object;
}
/*
* Spawns a generator function which allows for Promises, Observable sequences, Arrays, Objects, Generators and functions.
* @param {Function} The spawning function.
* @returns {Function} a function which has a done continuation.
*/
var observableSpawn = Rx.spawn = function (fn) {
var isGenFun = isGeneratorFunction(fn);
return function (done) {
var ctx = this,
gen = fan;
if (isGenFun) {
var args = slice.call(arguments),
len = args.length,
hasCallback = len && typeof args[len - 1] === fnString;
done = hasCallback ? args.pop() : error;
gen = fn.apply(this, args);
} else {
done = done || error;
}
next();
function exit(err, res) {
timeoutScheduler.schedule(done.bind(ctx, err, res));
}
function next(err, res) {
var ret;
// multiple args
if (arguments.length > 2) res = slice.call(arguments, 1);
if (err) {
try {
ret = gen.throw(err);
} catch (e) {
return exit(e);
}
}
if (!err) {
try {
ret = gen.next(res);
} catch (e) {
return exit(e);
}
}
if (ret.done) {
return exit(null, ret.value);
}
ret.value = toThunk(ret.value, ctx);
if (typeof ret.value === fnString) {
var called = false;
try {
ret.value.call(ctx, function(){
if (called) {
return;
}
called = true;
next.apply(ctx, arguments);
});
} catch (e) {
timeoutScheduler.schedule(function () {
if (called) {
return;
}
called = true;
next.call(ctx, e);
});
}
return;
}
// Not supported
next(new TypeError('Rx.spawn only supports a function, Promise, Observable, Object or Array.'));
}
}
};
/**
* Takes a function with a callback and turns it into a thunk.
* @param {Function} A function with a callback such as fs.readFile
* @returns {Function} A function, when executed will continue the state machine.
*/
Rx.denodify = function (fn) {
return function (){
var args = slice.call(arguments),
results,
called,
callback;
args.push(function(){
results = arguments;
if (callback && !called) {
called = true;
cb.apply(this, results);
}
});
fn.apply(this, args);
return function (fn){
callback = fn;
if (results && !called) {
called = true;
fn.apply(this, results);
}
}
}
};
/**
* 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);
}).publishLast().refCount();
};
};
/**
* Converts a Node.js callback style function to an observable sequence. This must be in function (err, ...) format.
* @param {Function} func The function to call
* @param {Mixed} [context] The context for the func parameter to be executed. If not specified, defaults to undefined.
* @param {Function} [selector] A selector which takes the arguments from the callback minus the error to produce a single item to yield on next.
* @returns {Function} An async function which when applied, returns an observable sequence with the callback arguments as an array.
*/
Observable.fromNodeCallback = function (func, context, selector) {
return function () {
var args = slice.call(arguments, 0);
return new AnonymousObservable(function (observer) {
function handler(err) {
if (err) {
observer.onError(err);
return;
}
var results = slice.call(arguments, 1);
if (selector) {
try {
results = selector(results);
} catch (e) {
observer.onError(e);
return;
}
observer.onNext(results);
} else {
if (results.length <= 1) {
observer.onNext.apply(observer, results);
} else {
observer.onNext(results);
}
}
observer.onCompleted();
}
args.push(handler);
func.apply(context, args);
}).publishLast().refCount();
};
};
function fixEvent(event) {
var stopPropagation = function () {
this.cancelBubble = true;
};
var preventDefault = function () {
this.bubbledKeyCode = this.keyCode;
if (this.ctrlKey) {
try {
this.keyCode = 0;
} catch (e) { }
}
this.defaultPrevented = true;
this.returnValue = false;
this.modified = true;
};
event || (event = root.event);
if (!event.target) {
event.target = event.target || event.srcElement;
if (event.type == 'mouseover') {
event.relatedTarget = event.fromElement;
}
if (event.type == 'mouseout') {
event.relatedTarget = event.toElement;
}
// Adding stopPropogation and preventDefault to IE
if (!event.stopPropagation){
event.stopPropagation = stopPropagation;
event.preventDefault = preventDefault;
}
// Normalize key events
switch(event.type){
case 'keypress':
var c = ('charCode' in event ? event.charCode : event.keyCode);
if (c == 10) {
c = 0;
event.keyCode = 13;
} else if (c == 13 || c == 27) {
c = 0;
} else if (c == 3) {
c = 99;
}
event.charCode = c;
event.keyChar = event.charCode ? String.fromCharCode(event.charCode) : '';
break;
}
}
return event;
}
function createListener (element, name, handler) {
// Standards compliant
if (element.addEventListener) {
element.addEventListener(name, handler, false);
return disposableCreate(function () {
element.removeEventListener(name, handler, false);
});
}
if (element.attachEvent) {
// IE Specific
var innerHandler = function (event) {
handler(fixEvent(event));
};
element.attachEvent('on' + name, innerHandler);
return disposableCreate(function () {
element.detachEvent('on' + name, innerHandler);
});
}
// Level 1 DOM Events
element['on' + name] = handler;
return disposableCreate(function () {
element['on' + name] = null;
});
}
function createEventListener (el, eventName, handler) {
var disposables = new CompositeDisposable();
// Asume NodeList
if (Object.prototype.toString.call(el) === '[object NodeList]') {
for (var i = 0, len = el.length; i < len; i++) {
disposables.add(createEventListener(el.item(i), eventName, handler));
}
} else if (el) {
disposables.add(createListener(el, eventName, handler));
}
return disposables;
}
/**
* Configuration option to determine whether to use native events only
*/
Rx.config.useNativeEvents = false;
// Check for Angular/jQuery/Zepto support
var jq =
!!root.angular && !!angular.element ? angular.element :
(!!root.jQuery ? root.jQuery : (
!!root.Zepto ? root.Zepto : null));
// Check for ember
var ember = !!root.Ember && typeof root.Ember.addListener === 'function';
// Check for Backbone.Marionette. Note if using AMD add Marionette as a dependency of rxjs
// for proper loading order!
var marionette = !!root.Backbone && !!root.Backbone.Marionette;
/**
* Creates an observable sequence by adding an event listener to the matching DOMElement or each item in the NodeList.
*
* @example
* var source = Rx.Observable.fromEvent(element, 'mouseup');
*
* @param {Object} element The DOMElement or NodeList to attach a listener.
* @param {String} eventName The event name to attach the observable sequence.
* @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next.
* @returns {Observable} An observable sequence of events from the specified element and the specified event.
*/
Observable.fromEvent = function (element, eventName, selector) {
// Node.js specific
if (element.addListener) {
return fromEventPattern(
function (h) { element.addListener(eventName, h); },
function (h) { element.removeListener(eventName, h); },
selector);
}
// Use only if non-native events are allowed
if (!Rx.config.useNativeEvents) {
if (marionette) {
return fromEventPattern(
function (h) { element.on(eventName, h); },
function (h) { element.off(eventName, h); },
selector);
}
if (ember) {
return fromEventPattern(
function (h) { Ember.addListener(element, eventName, h); },
function (h) { Ember.removeListener(element, eventName, h); },
selector);
}
if (jq) {
var $elem = jq(element);
return fromEventPattern(
function (h) { $elem.on(eventName, h); },
function (h) { $elem.off(eventName, h); },
selector);
}
}
return new AnonymousObservable(function (observer) {
return createEventListener(
element,
eventName,
function handler (e) {
var results = e;
if (selector) {
try {
results = selector(arguments);
} catch (err) {
observer.onError(err);
return
}
}
observer.onNext(results);
});
}).publish().refCount();
};
/**
* Creates an observable sequence from an event emitter via an addHandler/removeHandler pair.
* @param {Function} addHandler The function to add a handler to the emitter.
* @param {Function} [removeHandler] The optional function to remove a handler from an emitter.
* @param {Function} [selector] A selector which takes the arguments from the event handler to produce a single item to yield on next.
* @returns {Observable} An observable sequence which wraps an event from an event emitter
*/
var fromEventPattern = Observable.fromEventPattern = function (addHandler, removeHandler, selector) {
return new AnonymousObservable(function (observer) {
function innerHandler (e) {
var result = e;
if (selector) {
try {
result = selector(arguments);
} catch (err) {
observer.onError(err);
return;
}
}
observer.onNext(result);
}
var returnValue = addHandler(innerHandler);
return disposableCreate(function () {
if (removeHandler) {
removeHandler(innerHandler, returnValue);
}
});
}).publish().refCount();
};
/**
* Invokes the asynchronous function, surfacing the result through an observable sequence.
* @param {Function} functionAsync Asynchronous function which returns a Promise to run.
* @returns {Observable} An observable sequence exposing the function's result value, or an exception.
*/
Observable.startAsync = function (functionAsync) {
var promise;
try {
promise = functionAsync();
} catch (e) {
return observableThrow(e);
}
return observableFromPromise(promise);
}
var PausableObservable = (function (_super) {
inherits(PausableObservable, _super);
function subscribe(observer) {
var conn = this.source.publish(),
subscription = conn.subscribe(observer),
connection = disposableEmpty;
var pausable = this.pauser.distinctUntilChanged().subscribe(function (b) {
if (b) {
connection = conn.connect();
} else {
connection.dispose();
connection = disposableEmpty;
}
});
return new CompositeDisposable(subscription, connection, pausable);
}
function PausableObservable(source, pauser) {
this.source = source;
this.controller = new Subject();
if (pauser && pauser.subscribe) {
this.pauser = this.controller.merge(pauser);
} else {
this.pauser = this.controller;
}
_super.call(this, subscribe);
}
PausableObservable.prototype.pause = function () {
this.controller.onNext(false);
};
PausableObservable.prototype.resume = function () {
this.controller.onNext(true);
};
return PausableObservable;
}(Observable));
/**
* Pauses the underlying observable sequence based upon the observable sequence which yields true/false.
* @example
* var pauser = new Rx.Subject();
* var source = Rx.Observable.interval(100).pausable(pauser);
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.pausable = function (pauser) {
return new PausableObservable(this, pauser);
};
function combineLatestSource(source, subject, resultSelector) {
return new AnonymousObservable(function (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.pauser.distinctUntilChanged().startWith(false),
function (data, shouldFire) {
return { data: data, shouldFire: shouldFire };
})
.subscribe(
function (results) {
if (previousShouldFire !== undefined && results.shouldFire != previousShouldFire) {
previousShouldFire = results.shouldFire;
// change in shouldFire
if (results.shouldFire) {
while (q.length > 0) {
observer.onNext(q.shift());
}
}
} else {
previousShouldFire = results.shouldFire;
// new data
if (results.shouldFire) {
observer.onNext(results.data);
} else {
q.push(results.data);
}
}
},
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();
}
);
return subscription;
}
function PausableBufferedObservable(source, pauser) {
this.source = source;
this.controller = new Subject();
if (pauser && pauser.subscribe) {
this.pauser = this.controller.merge(pauser);
} else {
this.pauser = this.controller;
}
_super.call(this, subscribe);
}
PausableBufferedObservable.prototype.pause = function () {
this.controller.onNext(false);
};
PausableBufferedObservable.prototype.resume = function () {
this.controller.onNext(true);
};
return PausableBufferedObservable;
}(Observable));
/**
* Pauses the underlying observable sequence based upon the observable sequence which yields true/false,
* and yields the values that were buffered while paused.
* @example
* var pauser = new Rx.Subject();
* var source = Rx.Observable.interval(100).pausableBuffered(pauser);
* @param {Observable} pauser The observable sequence used to pause the underlying sequence.
* @returns {Observable} The observable sequence which is paused based upon the pauser.
*/
observableProto.pausableBuffered = function (subject) {
return new PausableBufferedObservable(this, subject);
};
/**
* 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 && isFunction(selector) ?
this.multicast(function () { return new Subject(); }, selector) :
this.multicast(new Subject());
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence.
* This operator is a specialization of publish which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
*
* @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().refCount();
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence containing only the last notification.
* This operator is a specialization of Multicast using a AsyncSubject.
*
* @example
* var res = source.publishLast();
* var res = source.publishLast(function (x) { return x; });
*
* @param selector [Optional] Selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will only receive the last notification of the source.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publishLast = function (selector) {
return selector && isFunction(selector) ?
this.multicast(function () { return new AsyncSubject(); }, selector) :
this.multicast(new AsyncSubject());
};
/**
* Returns an observable sequence that is the result of invoking the selector on a connectable observable sequence that shares a single subscription to the underlying sequence and starts with initialValue.
* This operator is a specialization of Multicast using a BehaviorSubject.
*
* @example
* var res = source.publishValue(42);
* var res = source.publishValue(function (x) { return x.select(function (y) { return y * y; }) }, 42);
*
* @param {Function} [selector] Optional selector function which can use the multicasted source sequence as many times as needed, without causing multiple subscriptions to the source sequence. Subscribers to the given source will receive immediately receive the initial value, followed by all notifications of the source from the time of the subscription on.
* @param {Mixed} initialValue Initial value received by observers upon subscription.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence within a selector function.
*/
observableProto.publishValue = function (initialValueOrSelector, initialValue) {
return arguments.length === 2 ?
this.multicast(function () {
return new BehaviorSubject(initialValue);
}, initialValueOrSelector) :
this.multicast(new BehaviorSubject(initialValueOrSelector));
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence and starts with an initialValue.
* This operator is a specialization of publishValue which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
*
* @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 && isFunction(selector) ?
this.multicast(function () { return new ReplaySubject(bufferSize, window, scheduler); }, selector) :
this.multicast(new ReplaySubject(bufferSize, window, scheduler));
};
/**
* Returns an observable sequence that shares a single subscription to the underlying sequence replaying notifications subject to a maximum time length for the replay buffer.
* This operator is a specialization of replay which creates a subscription when the number of observers goes from zero to one, then shares that subscription with all subsequent observers until the number of observers returns to zero, at which point the subscription is disposed.
*
* @example
* var res = source.shareReplay(3);
* var res = source.shareReplay(3, 500);
* var res = source.shareReplay(3, 500, scheduler);
*
* @param bufferSize [Optional] Maximum element count of the replay buffer.
* @param window [Optional] Maximum time length of the replay buffer.
* @param scheduler [Optional] Scheduler where connected observers within the selector function will be invoked on.
* @returns {Observable} An observable sequence that contains the elements of a sequence produced by multicasting the source sequence.
*/
observableProto.shareReplay = function (bufferSize, window, scheduler) {
return this.replay(null, bufferSize, window, scheduler).refCount();
};
/** @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) { return; }
this.isStopped = true;
for (var i = 0, os = this.observers.slice(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) { return; }
this.isStopped = true;
this.exception = error;
for (var i = 0, os = this.observers.slice(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) { return; }
this.value = value;
for (var i = 0, os = this.observers.slice(0), len = os.length; i < len; i++) {
os[i].onNext(value);
}
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
this.value = null;
this.exception = null;
}
});
return BehaviorSubject;
}(Observable));
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed and future observers, subject to buffer trimming policies.
*/
var ReplaySubject = Rx.ReplaySubject = (function (__super__) {
function createRemovableDisposable(subject, observer) {
return disposableCreate(function () {
observer.dispose();
!subject.isDisposed && subject.observers.splice(subject.observers.indexOf(observer), 1);
});
}
function subscribe(observer) {
var so = new ScheduledObserver(this.scheduler, observer),
subscription = createRemovableDisposable(this, so);
checkDisposed.call(this);
this._trim(this.scheduler.now());
this.observers.push(so);
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;
},
_trim: function (now) {
while (this.q.length > this.bufferSize) {
this.q.shift();
}
while (this.q.length > 0 && (now - this.q[0].interval) > this.windowSize) {
this.q.shift();
}
},
/**
* Notifies all subscribed observers about the arrival of the specified element in the sequence.
* @param {Mixed} value The value to send to all observers.
*/
onNext: function (value) {
checkDisposed.call(this);
if (this.isStopped) { return; }
var now = this.scheduler.now();
this.q.push({ interval: now, value: value });
this._trim(now);
var o = this.observers.slice(0);
for (var i = 0, len = o.length; i < len; i++) {
var observer = o[i];
observer.onNext(value);
observer.ensureActive();
}
},
/**
* Notifies all subscribed observers about the exception.
* @param {Mixed} error The exception to send to all observers.
*/
onError: function (error) {
checkDisposed.call(this);
if (this.isStopped) { return; }
this.isStopped = true;
this.error = error;
this.hasError = true;
var now = this.scheduler.now();
this._trim(now);
var o = this.observers.slice(0);
for (var i = 0, len = o.length; i < len; i++) {
var observer = o[i];
observer.onError(error);
observer.ensureActive();
}
this.observers = [];
},
/**
* Notifies all subscribed observers about the end of the sequence.
*/
onCompleted: function () {
checkDisposed.call(this);
if (this.isStopped) { return; }
this.isStopped = true;
var now = this.scheduler.now();
this._trim(now);
var o = this.observers.slice(0);
for (var i = 0, len = o.length; i < len; i++) {
var observer = o[i];
observer.onCompleted();
observer.ensureActive();
}
this.observers = [];
},
/**
* Unsubscribe all observers and release resources.
*/
dispose: function () {
this.isDisposed = true;
this.observers = null;
}
});
return ReplaySubject;
}(Observable));
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.
* @param {Number} dueTime Absolute (specified as a Date object) or relative time (specified as an integer denoting milliseconds) at which to produce the first value.
* @param {Mixed} [periodOrScheduler] Period to produce subsequent values (specified as an integer denoting milliseconds), or the scheduler to run the timer on. If not specified, the resulting timer is not recurring.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence that produces a value after due time has elapsed and then each period.
*/
var observableTimer = Observable.timer = function (dueTime, periodOrScheduler, scheduler) {
var period;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
if (periodOrScheduler !== undefined && typeof periodOrScheduler === 'number') {
period = periodOrScheduler;
} else if (isScheduler(periodOrScheduler)) {
scheduler = periodOrScheduler;
}
if (dueTime instanceof Date && period === undefined) {
return observableTimerDate(dueTime.getTime(), scheduler);
}
if (dueTime instanceof Date && period !== undefined) {
period = periodOrScheduler;
return observableTimerDateAndPeriod(dueTime.getTime(), period, scheduler);
}
return period === undefined ?
observableTimerTimeSpan(dueTime, scheduler) :
observableTimerTimeSpanAndPeriod(dueTime, period, scheduler);
};
function observableDelayTimeSpan(source, dueTime, scheduler) {
return new AnonymousObservable(function (observer) {
var active = false,
cancelable = new SerialDisposable(),
exception = null,
q = [],
running = false,
subscription;
subscription = source.materialize().timestamp(scheduler).subscribe(function (notification) {
var d, shouldRun;
if (notification.value.kind === 'E') {
q = [];
q.push(notification);
exception = notification.value.exception;
shouldRun = !running;
} else {
q.push({ value: notification.value, timestamp: notification.timestamp + dueTime });
shouldRun = !active;
active = true;
}
if (shouldRun) {
if (exception !== null) {
observer.onError(exception);
} else {
d = new SingleAssignmentDisposable();
cancelable.setDisposable(d);
d.setDisposable(scheduler.scheduleRecursiveWithRelative(dueTime, function (self) {
var e, recurseDueTime, result, shouldRecurse;
if (exception !== null) {
return;
}
running = true;
do {
result = null;
if (q.length > 0 && q[0].timestamp - scheduler.now() <= 0) {
result = q.shift().value;
}
if (result !== null) {
result.accept(observer);
}
} while (result !== null);
shouldRecurse = false;
recurseDueTime = 0;
if (q.length > 0) {
shouldRecurse = true;
recurseDueTime = Math.max(0, q[0].timestamp - scheduler.now());
} else {
active = false;
}
e = exception;
running = false;
if (e !== null) {
observer.onError(e);
} else if (shouldRecurse) {
self(recurseDueTime);
}
}));
}
}
});
return new CompositeDisposable(subscription, cancelable);
});
}
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);
var source = this;
return new AnonymousObservable(function (observer) {
var cancelable = new SerialDisposable(), hasvalue = false, value, id = 0;
var subscription = source.subscribe(
function (x) {
hasvalue = true;
value = x;
id++;
var currentId = id,
d = new SingleAssignmentDisposable();
cancelable.setDisposable(d);
d.setDisposable(scheduler.scheduleWithRelative(dueTime, function () {
hasValue && id === currentId && observer.onNext(value);
hasvalue = false;
}));
},
function (e) {
cancelable.dispose();
observer.onError(e);
hasvalue = false;
id++;
},
function () {
cancelable.dispose();
hasvalue && observer.onNext(value);
observer.onCompleted();
hasvalue = false;
id++;
});
return new CompositeDisposable(subscription, cancelable);
});
};
/**
* Projects each element of an observable sequence into zero or more windows which are produced based on timing information.
*
* @example
* 1 - res = xs.windowWithTime(1000, scheduler); // non-overlapping segments of 1 second
* 2 - res = xs.windowWithTime(1000, 500 , scheduler); // segments of 1 second with time shift 0.5 seconds
*
* @param {Number} timeSpan Length of each window (specified as an integer denoting milliseconds).
* @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive windows (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent windows.
* @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.windowWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) {
var source = this, timeShift;
if (timeShiftOrScheduler === undefined) {
timeShift = timeSpan;
}
isScheduler(scheduler) || (scheduler = timeoutScheduler);
if (typeof timeShiftOrScheduler === 'number') {
timeShift = timeShiftOrScheduler;
} else if (isScheduler(timeShiftOrScheduler)) {
timeShift = timeSpan;
scheduler = timeShiftOrScheduler;
}
return new AnonymousObservable(function (observer) {
var groupDisposable,
nextShift = timeShift,
nextSpan = timeSpan,
q = [],
refCountDisposable,
timerD = new SerialDisposable(),
totalTime = 0;
groupDisposable = new CompositeDisposable(timerD),
refCountDisposable = new RefCountDisposable(groupDisposable);
function createTimer () {
var m = new SingleAssignmentDisposable(),
isSpan = false,
isShift = false;
timerD.setDisposable(m);
if (nextSpan === nextShift) {
isSpan = true;
isShift = true;
} else if (nextSpan < nextShift) {
isSpan = true;
} else {
isShift = true;
}
var newTotalTime = isSpan ? nextSpan : nextShift,
ts = newTotalTime - totalTime;
totalTime = newTotalTime;
if (isSpan) {
nextSpan += timeShift;
}
if (isShift) {
nextShift += timeShift;
}
m.setDisposable(scheduler.scheduleWithRelative(ts, function () {
var s;
if (isShift) {
s = new Subject();
q.push(s);
observer.onNext(addRef(s, refCountDisposable));
}
if (isSpan) {
s = q.shift();
s.onCompleted();
}
createTimer();
}));
};
q.push(new Subject());
observer.onNext(addRef(q[0], refCountDisposable));
createTimer();
groupDisposable.add(source.subscribe(function (x) {
for (var i = 0, len = q.length; i < len; i++) {
q[i].onNext(x);
}
}, function (e) {
for (var i = 0, len = q.length; i < len; i++) {
q[i].onError(e);
}
observer.onError(e);
}, function () {
for (var i = 0, len = q.length; i < len; i++) {
q[i].onCompleted();
}
observer.onCompleted();
}));
return refCountDisposable;
});
};
/**
* Projects each element of an observable sequence into a window that is completed when either it's full or a given amount of time has elapsed.
* @param {Number} timeSpan Maximum time length of a window.
* @param {Number} count Maximum element count of a window.
* @param {Scheduler} [scheduler] Scheduler to run windowing timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of windows.
*/
observableProto.windowWithTimeOrCount = function (timeSpan, count, scheduler) {
var source = this;
isScheduler(scheduler) || (scheduler = timeoutScheduler);
return new AnonymousObservable(function (observer) {
var createTimer,
groupDisposable,
n = 0,
refCountDisposable,
s,
timerD = new SerialDisposable(),
windowId = 0;
groupDisposable = new CompositeDisposable(timerD);
refCountDisposable = new RefCountDisposable(groupDisposable);
createTimer = function (id) {
var m = new SingleAssignmentDisposable();
timerD.setDisposable(m);
m.setDisposable(scheduler.scheduleWithRelative(timeSpan, function () {
var newId;
if (id !== windowId) {
return;
}
n = 0;
newId = ++windowId;
s.onCompleted();
s = new Subject();
observer.onNext(addRef(s, refCountDisposable));
createTimer(newId);
}));
};
s = new Subject();
observer.onNext(addRef(s, refCountDisposable));
createTimer(0);
groupDisposable.add(source.subscribe(function (x) {
var newId = 0, newWindow = false;
s.onNext(x);
n++;
if (n === count) {
newWindow = true;
n = 0;
newId = ++windowId;
s.onCompleted();
s = new Subject();
observer.onNext(addRef(s, refCountDisposable));
}
if (newWindow) {
createTimer(newId);
}
}, function (e) {
s.onError(e);
observer.onError(e);
}, function () {
s.onCompleted();
observer.onCompleted();
}));
return refCountDisposable;
});
};
/**
* Projects each element of an observable sequence into zero or more buffers which are produced based on timing information.
*
* @example
* 1 - res = xs.bufferWithTime(1000, scheduler); // non-overlapping segments of 1 second
* 2 - res = xs.bufferWithTime(1000, 500, scheduler; // segments of 1 second with time shift 0.5 seconds
*
* @param {Number} timeSpan Length of each buffer (specified as an integer denoting milliseconds).
* @param {Mixed} [timeShiftOrScheduler] Interval between creation of consecutive buffers (specified as an integer denoting milliseconds), or an optional scheduler parameter. If not specified, the time shift corresponds to the timeSpan parameter, resulting in non-overlapping adjacent buffers.
* @param {Scheduler} [scheduler] Scheduler to run buffer timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of buffers.
*/
observableProto.bufferWithTime = function (timeSpan, timeShiftOrScheduler, scheduler) {
return this.windowWithTime.apply(this, arguments).selectMany(function (x) { return x.toArray(); });
};
/**
* Projects each element of an observable sequence into a buffer that is completed when either it's full or a given amount of time has elapsed.
*
* @example
* 1 - res = source.bufferWithTimeOrCount(5000, 50); // 5s or 50 items in an array
* 2 - res = source.bufferWithTimeOrCount(5000, 50, scheduler); // 5s or 50 items in an array
*
* @param {Number} timeSpan Maximum time length of a buffer.
* @param {Number} count Maximum element count of a buffer.
* @param {Scheduler} [scheduler] Scheduler to run bufferin timers on. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence of buffers.
*/
observableProto.bufferWithTimeOrCount = function (timeSpan, count, scheduler) {
return this.windowWithTimeOrCount(timeSpan, count, scheduler).selectMany(function (x) {
return x.toArray();
});
};
/**
* Records the time interval between consecutive values in an observable sequence.
*
* @example
* 1 - res = source.timeInterval();
* 2 - res = source.timeInterval(Rx.Scheduler.timeout);
*
* @param [scheduler] Scheduler used to compute time intervals. If not specified, the timeout scheduler is used.
* @returns {Observable} An observable sequence with time interval information on values.
*/
observableProto.timeInterval = function (scheduler) {
var source = this;
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.
* @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);
function createTimer() {
var myId = id;
timer.setDisposable(scheduler[schedulerMethod](dueTime, function () {
if (id === myId) {
isPromise(other) && (other = observableFromPromise(other));
subscription.setDisposable(other.subscribe(observer));
}
}));
}
createTimer();
original.setDisposable(source.subscribe(function (x) {
if (!switched) {
id++;
observer.onNext(x);
createTimer();
}
}, function (e) {
if (!switched) {
id++;
observer.onError(e);
}
}, function () {
if (!switched) {
id++;
observer.onCompleted();
}
}));
return new CompositeDisposable(subscription, timer);
});
};
/**
* 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.
* @param {Observable} [firstTimeout] Observable sequence that represents the timeout for the first element. If not provided, this defaults to Observable.never().
* @param {Function} [timeoutDurationSelector] Selector to retrieve an observable sequence that represents the timeout between the current element and the next element.
* @param {Observable} [other] Sequence to return in case of a timeout. If not provided, this is set to Observable.throwException().
* @returns {Observable} The source sequence switching to the other sequence in case of a timeout.
*/
observableProto.timeoutWithSelector = function (firstTimeout, timeoutdurationSelector, other) {
if (arguments.length === 1) {
timeoutdurationSelector = firstTimeout;
firstTimeout = observableNever();
}
other || (other = observableThrow(new Error('Timeout')));
var source = this;
return new AnonymousObservable(function (observer) {
var subscription = new SerialDisposable(), timer = new SerialDisposable(), original = new SingleAssignmentDisposable();
subscription.setDisposable(original);
var id = 0, switched = false;
function setTimer(timeout) {
var myId = id;
function timerWins () {
return id === myId;
}
var d = new SingleAssignmentDisposable();
timer.setDisposable(d);
d.setDisposable(timeout.subscribe(function () {
timerWins() && subscription.setDisposable(other.subscribe(observer));
d.dispose();
}, function (e) {
timerWins() && observer.onError(e);
}, function () {
timerWins() && subscription.setDisposable(other.subscribe(observer));
}));
};
setTimer(firstTimeout);
function observerWins() {
var res = !switched;
if (res) { id++; }
return res;
}
original.setDisposable(source.subscribe(function (x) {
if (observerWins()) {
observer.onNext(x);
var timeout;
try {
timeout = timeoutdurationSelector(x);
} catch (e) {
observer.onError(e);
return;
}
setTimer(isPromise(timeout) ? observableFromPromise(timeout) : timeout);
}
}, function (e) {
observerWins() && observer.onError(e);
}, function () {
observerWins() && observer.onCompleted();
}));
return new CompositeDisposable(subscription, timer);
});
};
/**
* 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;
var subscription = source.subscribe(function (x) {
var throttle;
try {
throttle = throttleDurationSelector(x);
} catch (e) {
observer.onError(e);
return;
}
isPromise(throttle) && (throttle = observableFromPromise(throttle));
hasValue = true;
value = x;
id++;
var currentid = id, d = new SingleAssignmentDisposable();
cancelable.setDisposable(d);
d.setDisposable(throttle.subscribe(function () {
hasValue && id === currentid && observer.onNext(value);
hasValue = false;
d.dispose();
}, observer.onError.bind(observer), function () {
hasValue && id === currentid && observer.onNext(value);
hasValue = false;
d.dispose();
}));
}, function (e) {
cancelable.dispose();
observer.onError(e);
hasValue = false;
id++;
}, function () {
cancelable.dispose();
hasValue && observer.onNext(value);
observer.onCompleted();
hasValue = false;
id++;
});
return new CompositeDisposable(subscription, cancelable);
});
};
/**
* 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.
* @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.
* @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(), [scheduler]);
* 2 - res = source.skipUntilWithTime(5000, [scheduler]);
* @param {Date|Number} startTime Time to start taking elements from the source sequence. If this value is less than or equal to Date(), no elements will be skipped.
* @param {Scheduler} [scheduler] Scheduler to run the timer on. If not specified, defaults to Rx.Scheduler.timeout.
* @returns {Observable} An observable sequence with the elements skipped until the specified start time.
*/
observableProto.skipUntilWithTime = function (startTime, scheduler) {
isScheduler(scheduler) || (scheduler = timeoutScheduler);
var source = this, schedulerMethod = startTime instanceof Date ?
'scheduleWithAbsolute' :
'scheduleWithRelative';
return new AnonymousObservable(function (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.
* @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, observer.onCompleted.bind(observer)),
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));
var GroupedObservable = (function (__super__) {
inherits(GroupedObservable, __super__);
function subscribe(observer) {
return this.underlyingObservable.subscribe(observer);
}
function GroupedObservable(key, underlyingObservable, mergedDisposable) {
__super__.call(this, subscribe);
this.key = key;
this.underlyingObservable = !mergedDisposable ?
underlyingObservable :
new AnonymousObservable(function (observer) {
return new CompositeDisposable(mergedDisposable.getDisposable(), underlyingObservable.subscribe(observer));
});
}
return GroupedObservable;
}(Observable));
/**
* Represents an object that is both an observable sequence as well as an observer.
* Each notification is broadcasted to all subscribed observers.
*/
var Subject = Rx.Subject = (function (_super) {
function subscribe(observer) {
checkDisposed.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)); |
packages/ui/src/index.js | she-smashes/thehub | import React from 'react';
import ReactDOM from 'react-dom';
import { Provider } from 'react-redux'
import MuiThemeProvider from 'material-ui/styles/MuiThemeProvider';
import injectTapEventPlugin from 'react-tap-event-plugin';
import { applyMiddleware, combineReducers, compose, createStore } from 'redux';
import promise from "redux-promise";
import { persistStore, persistCombineReducers } from 'redux-persist';
import storage from 'redux-persist/es/storage';
import { PersistGate } from 'redux-persist/es/integration/react';
import './index.css';
// Components
import App from './containers/appContainer/';
// Reducers
import userInfo from './containers/loginFormContainer/reducer';
import eventsList from './containers/eventTimelineContainer/reducer';
import viewInitiatives from './containers/viewInitiativeContainer/reducer';
import badgesList from './containers/badgesContainer/reducer';
import viewTasks from './containers/viewApprovalContainer/reducer';
import allBadgesList from './containers/viewAllBadgesContainer/reducer';
import eventDetails from './containers/eventDetailsContainer/reducer';
import eventEnrollmentsDetails from './containers/eventDetailsContainer/enrollmentsReducer';
import progressCategoriesList from './containers/progressCategoriesContainer/reducer';
import initiativeDetails from './containers/initiativeDetailsContainer/reducer';
import viewEvents from './containers/viewEventsContainer/reducer';
import createEvent from './containers/createEventContainer/reducer';
import approvedInitiatives from './containers/createEventContainer/getInitReducer';
import categories from './containers/createEventContainer/categoriesReducer';
import participants from './containers/createEventContainer/participantsReducer';
import badgesToBeClaimedList from './containers/ViewAllBadgesToBeClaimedContainer/reducer';
import badgesCanBeClaimedList from './containers/claimYourBadgeContainer/reducer';
import eventData from './containers/uploadAttendanceContainer/reducer';
import attendanceInfo from './containers/attendanceContainer/reducer';
import authUserDetails from './containers/loginFormContainer/loginUserInfo';
import { reducer as reduxFormReducer } from 'redux-form';
import registerServiceWorker from './registerServiceWorker';
import thunk from 'redux-thunk';
import { createLogger } from 'redux-logger';
// Persist only userInfo to the localstorage
const config = {
key: 'primary',
storage,
whitelist: ['userInfo']
}
// root reducer configuration
const rootReducer = persistCombineReducers(config, {
userInfo,
eventsList,
viewInitiatives,
viewTasks,
eventDetails,
eventEnrollmentsDetails,
viewEvents,
approvedInitiatives,
categories,
participants,
initiativeDetails,
badgesList,
allBadgesList,
progressCategoriesList,
badgesToBeClaimedList,
badgesCanBeClaimedList,
eventData,
attendanceInfo,
authUserDetails
});
// Create persistor and store for storage and state
const { persistor, store } = configureStore()
function configureStore() {
let store = createStore(rootReducer,
{}, // initial state
compose(
applyMiddleware(promise, thunk, createLogger({
predicate: (getState, action) => false
})),
// applyMiddleware(promise(), thunk, createLogger()),
// added for redux dev tools extension
(typeof window.__REDUX_DEVTOOLS_EXTENSION__ !== 'undefined') ? window.__REDUX_DEVTOOLS_EXTENSION__() : f => f,
))
let persistor = persistStore(store, undefined, () => {
store.getState()
}
);
return { persistor, store }
}
injectTapEventPlugin();
ReactDOM.render(
<Provider store={store}>
<PersistGate persistor={persistor}>
<MuiThemeProvider>
<App />
</MuiThemeProvider>
</PersistGate>
</Provider>
, document.getElementById('root'));
// Commenting this line to make the Loopback API Explorer work
registerServiceWorker();
|
pages/decal/lesson-10/index.js | jubearsun/innovative-design | import React from 'react';
import DocumentTitle from 'react-document-title';
import { prefixLink } from 'gatsby-helpers';
import $ from 'jquery';
import _ from 'lodash';
export default class Index extends React.Component {
constructor(props) {
super(props);
}
componentDidMount() {}
render () {
return (
<DocumentTitle title="Innovative Design">
<div>
<div className="page__wrapper lesson">
<h1 className="section__title">Lesson Ten</h1>
<div className="button__wrapper">
<a href="https://www.dropbox.com/sh/m173b2bqyuaenr9/AACHQCTiBrF32iOY5vP3mcFKa?dl=0">
<button className="download__button">
download files
</button>
</a>
</div>
<div className="lesson__section">
<div className="lesson__section--description left">
<img src="../../img/decal/lesson10.png"/>
</div>
<div className="lesson__section--description right">
<div className="lesson__section--subtitle">tutorial</div>
<div className="lesson__section--info">
Apply everything you've learned this semester by rebranding and creating an advertisement design for a company!
</div>
</div>
</div>
<div className="lesson__section">
<div className="lesson__section--description left">
<img src="../../img/decal/hw10.png"/>
</div>
<div className="lesson__section--description right">
<div className="lesson__section--subtitle">homework</div>
<div className="lesson__section--info">
None!
</div>
</div>
</div>
</div>
</div>
</DocumentTitle>
);
}
}
|
src/routes.js | lvyuanjiao/isomorphic | import React from 'react';
import { Route, IndexRoute } from 'react-router';
import App from './containers/App';
import Home from './containers/Home';
import User from './containers/User';
import About from './containers/About';
import { loadUser } from 'store/reducers/user';
export default (store) => {
const enter = (nextState, replaceState, next) => {
if (!store.getState().user.get('loaded')) {
store.dispatch(loadUser()).then(() => next());
} else {
next();
}
};
return (
<Route path="/" component={App} onEnter={enter}>
<IndexRoute component={Home}/>
<Route path="user" component={User}/>
<Route path="about" component={About}/>
</Route>
);
};
|
src/ModalFooter.js | Terminux/react-bootstrap | import React from 'react';
import classNames from 'classnames';
import tbsUtils, { bsClass } from './utils/bootstrapUtils';
class ModalFooter extends React.Component {
render() {
return (
<div
{...this.props}
className={classNames(this.props.className, tbsUtils.prefix(this.props, 'footer'))}>
{this.props.children}
</div>
);
}
}
ModalFooter.propTypes = {
/**
* A css class applied to the Component
*/
bsClass: React.PropTypes.string
};
ModalFooter.defaultProps = {
bsClass: 'modal'
};
export default bsClass('modal', ModalFooter);
|